public String resolveSystem(String systemId)
    throws MalformedURLException, IOException {

    catalogManager.debug.message(3, "resolveSystem("+systemId+")");

    systemId = normalizeURI(systemId);

    if (systemId != null && systemId.startsWith("urn:publicid:")) {
      systemId = PublicId.decodeURN(systemId);
      return resolvePublic(systemId, null);
    }

    // If there's a SYSTEM entry in this catalog, use it
    if (systemId != null) {
      String resolved = resolveLocalSystem(systemId);
      if (resolved != null) {
	return resolved;
      }
    }

    // Otherwise, look in the subordinate catalogs
    return resolveSubordinateCatalogs(SYSTEM,
				      null,
				      null,
				      systemId);
  }

Return the applicable SYSTEM system identifier.

If a SYSTEM entry exists in the Catalog
for the system ID specified, return the mapped value.

On Windows-based operating systems, the comparison between
the system identifier provided and the SYSTEM entries in the
Catalog is case-insensitive.

@param systemId The system ID to locate in the catalog.

@return The resolved system identifier.

@throws MalformedURLException The formal system identifier of a
subordinate catalog cannot be turned into a valid URL.
@throws IOException Error reading subordinate catalog file.

Return the applicable SYSTEM system identifier .


protected String resolveLocalURI(String uri)
    throws MalformedURLException, IOException {
    Enumeration enumt = catalogEntries.elements();
    while (enumt.hasMoreElements()) {
      CatalogEntry e = (CatalogEntry) enumt.nextElement();
      if (e.getEntryType() == URI
	  && (e.getEntryArg(0).equals(uri))) {
	return e.getEntryArg(1);
      }
    }

    // If there's a REWRITE_URI entry in this catalog, use it
    enumt = catalogEntries.elements();
    String startString = null;
    String prefix = null;
    while (enumt.hasMoreElements()) {
      CatalogEntry e = (CatalogEntry) enumt.nextElement();

      if (e.getEntryType() == REWRITE_URI) {
	String p = e.getEntryArg(0);
	if (p.length() <= uri.length()
	    && p.equals(uri.substring(0, p.length()))) {
	  // Is this the longest prefix?
	  if (startString == null
	      || p.length() > startString.length()) {
	    startString = p;
	    prefix = e.getEntryArg(1);
	  }
	}
      }

      if (prefix != null) {
	// return the systemId with the new prefix
	return prefix + uri.substring(startString.length());
      }
    }

    // If there's a DELEGATE_URI entry in this catalog, use it
    enumt = catalogEntries.elements();
    Vector delCats = new Vector();
    while (enumt.hasMoreElements()) {
      CatalogEntry e = (CatalogEntry) enumt.nextElement();

      if (e.getEntryType() == DELEGATE_URI) {
	String p = e.getEntryArg(0);
	if (p.length() <= uri.length()
	    && p.equals(uri.substring(0, p.length()))) {
	  // delegate this match to the other catalog

	  delCats.addElement(e.getEntryArg(1));
	}
      }
    }

    if (delCats.size() > 0) {
      Enumeration enumCats = delCats.elements();

      if (catalogManager.debug.getDebug() > 1) {
	catalogManager.debug.message(2, "Switching to delegated catalog(s):");
	while (enumCats.hasMoreElements()) {
	  String delegatedCatalog = (String) enumCats.nextElement();
	  catalogManager.debug.message(2, "\t" + delegatedCatalog);
	}
      }

      Catalog dcat = newCatalog();

      enumCats = delCats.elements();
      while (enumCats.hasMoreElements()) {
	String delegatedCatalog = (String) enumCats.nextElement();
	dcat.parseCatalog(delegatedCatalog);
      }

      return dcat.resolveURI(uri);
    }

    return null;
  }

Return the applicable URI in this catalog.

If a URI entry exists in the catalog file
for the URI specified, return the mapped value.

@param uri The URI to locate in the catalog

@return The mapped URI or null
@throws MalformedURLException
@throws IOException

Return the applicable URI in this catalog .


protected synchronized String resolveSubordinateCatalogs(int entityType,
							   String entityName,
							   String publicId,
							   String systemId)
    throws MalformedURLException, IOException {

    for (int catPos = 0; catPos < catalogs.size(); catPos++) {
      Catalog c = null;

      try {
	c = (Catalog) catalogs.elementAt(catPos);
      } catch (ClassCastException e) {
	String catfile = (String) catalogs.elementAt(catPos);
	c = newCatalog();

	try {
	  c.parseCatalog(catfile);
	} catch (MalformedURLException mue) {
	  catalogManager.debug.message(1, "Malformed Catalog URL", catfile);
	} catch (FileNotFoundException fnfe) {
	  catalogManager.debug.message(1, "Failed to load catalog, file not found",
			catfile);
	} catch (IOException ioe) {
	  catalogManager.debug.message(1, "Failed to load catalog, I/O error", catfile);
	}

	catalogs.setElementAt(c, catPos);
      }

      String resolved = null;

      // Ok, now what are we supposed to call here?
      if (entityType == DOCTYPE) {
	resolved = c.resolveDoctype(entityName,
				    publicId,
				    systemId);
      } else if (entityType == DOCUMENT) {
	resolved = c.resolveDocument();
      } else if (entityType == ENTITY) {
	resolved = c.resolveEntity(entityName,
				   publicId,
				   systemId);
      } else if (entityType == NOTATION) {
	resolved = c.resolveNotation(entityName,
				     publicId,
				     systemId);
      } else if (entityType == PUBLIC) {
	resolved = c.resolvePublic(publicId, systemId);
      } else if (entityType == SYSTEM) {
	resolved = c.resolveSystem(systemId);
      } else if (entityType == URI) {
	resolved = c.resolveURI(systemId);
      }

      if (resolved != null) {
	return resolved;
      }
    }

    return null;
  }

Search the subordinate catalogs, in order, looking for a match.

This method searches the Catalog and returns the system
identifier specified for the given entity type with the given
name, public, and system identifiers. In some contexts, these
may be null.

@param entityType The CatalogEntry type for which this query is
being conducted. This is necessary in order to do the approprate
query on a subordinate catalog.
@param entityName The name of the entity being searched for, if
appropriate.
@param publicId The public identifier of the entity in question
(as provided in the source document).
@param systemId The nominal system identifier for the entity
in question (as provided in the source document). This parameter is
overloaded for the URI entry type.

@throws MalformedURLException The formal system identifier of a
delegated catalog cannot be turned into a valid URL.
@throws IOException Error reading delegated catalog file.

@return The system identifier to use.
Note that the nominal system identifier is not returned if a
match is not found in the catalog, instead null is returned
to indicate that no match was found.

Search the subordinate catalogs in order looking for a match .


protected String makeAbsolute(String sysid) {
    URL local = null;

    sysid = fixSlashes(sysid);

    try {
      local = new URL(base, sysid);
    } catch (MalformedURLException e) {
      catalogManager.debug.message(1, "Malformed URL on system identifier", sysid);
    }

    if (local != null) {
      return local.toString();
    } else {
      return sysid;
    }
  }

protected
String
makeAbsolute
(
String
sysid
)
{
URL
local
=
;
sysid
=
fixSlashes
(
sysid
)
;
try
{
local
=
new
URL
(
base
,
sysid
)
;
}
catch
(
MalformedURLException
e
)
{
catalogManager
.
debug
.
message
(
1
,
"Malformed URL on system identifier"
,
sysid
)
;
}
if
(
local
!=
)
{
return
local
.
toString
(
)
;
}
else
{
return
sysid
;
}
}

Construct an absolute URI from a relative one, using the current
base URI.

@param sysid The (possibly relative) system identifier
@return The system identifier made absolute with respect to the
current {@link #base}.

Construct an absolute URI from a relative one using the current base URI .


protected String normalizeURI(String uriref) {
    String newRef = "";
    byte[] bytes;

    if (uriref == null) {
      return null;
    }

    try {
      bytes = uriref.getBytes("UTF-8");
    } catch (UnsupportedEncodingException uee) {
      // this can't happen
      catalogManager.debug.message(1, "UTF-8 is an unsupported encoding!?");
      return uriref;
    }

    for (int count = 0; count < bytes.length; count++) {
      int ch = bytes[count] & 0xFF;

      if ((ch <= 0x20)    // ctrl
	  || (ch > 0x7F)  // high ascii
	  || (ch == 0x22) // "
	  || (ch == 0x3C) // <
	  || (ch == 0x3E) // >
	  || (ch == 0x5C) // \
	  || (ch == 0x5E) // ^
	  || (ch == 0x60) // `
	  || (ch == 0x7B) // {
	  || (ch == 0x7C) // |
	  || (ch == 0x7D) // }
	  || (ch == 0x7F)) {
	newRef += encodedByte(ch);
      } else {
	newRef += (char) bytes[count];
      }
    }

    return newRef;
  }

protected
String
normalizeURI
(
String
uriref
)
{
String
newRef
=
""
;
byte
[
]
bytes
;
if
(
uriref
==
)
{
return
;
}
try
{
bytes
=
uriref
.
getBytes
(
"UTF-8"
)
;
}
catch
(
UnsupportedEncodingException
uee
)
{
// this can't happen
catalogManager
.
debug
.
message
(
1
,
"UTF-8 is an unsupported encoding!?"
)
;
return
uriref
;
}
for
(
int
count
=
0
;
count
<
bytes
.
length
;
count
++
)
{
int
ch
=
bytes
[
count
]
&
0xFF
;
if
(
(
ch
<=
0x20
)
// ctrl
||
(
ch
>
0x7F
)
// high ascii
||
(
ch
==
0x22
)
// "
||
(
ch
==
0x3C
)
// <
||
(
ch
==
0x3E
)
// >
||
(
ch
==
0x5C
)
// \
||
(
ch
==
0x5E
)
// ^
||
(
ch
==
0x60
)
// `
||
(
ch
==
0x7B
)
// {
||
(
ch
==
0x7C
)
// |
||
(
ch
==
0x7D
)
// }
||
(
ch
==
0x7F
)
)
{
newRef
+=
encodedByte
(
ch
)
;
}
else
{
newRef
+=
(
char
)
bytes
[
count
]
;
}
}
return
newRef
;
}

Perform character normalization on a URI reference.

@param uriref The URI reference
@return The normalized URI reference.

Perform character normalization on a URI reference .


protected String encodedByte (int b) {
    String hex = Integer.toHexString(b).toUpperCase();
    if (hex.length() < 2) {
      return "%0" + hex;
    } else {
      return "%" + hex;
    }
  }

protected String encodedByte ( int b ) { String hex = Integer . toHexString ( b ) . toUpperCase ( ) ; if ( hex . length ( ) < 2 ) { return "%0" + hex ; } else { return "%" + hex ; } }

Perform %-encoding on a single byte.

@param b The 8-bit integer that represents th byte. (Bytes are signed
but encoding needs to look at the bytes unsigned.)
@return The %-encoded string for the byte in question.


protected void addDelegate(CatalogEntry entry) {
    int pos = 0;
    String partial = entry.getEntryArg(0);

    Enumeration local = localDelegate.elements();
    while (local.hasMoreElements()) {
      CatalogEntry dpe = (CatalogEntry) local.nextElement();
      String dp = dpe.getEntryArg(0);
      if (dp.equals(partial)) {
	// we already have this prefix
	return;
      }
      if (dp.length() > partial.length()) {
	pos++;
      }
      if (dp.length() < partial.length()) {
	break;
      }
    }

    // now insert partial into the vector at [pos]
    if (localDelegate.size() == 0) {
      localDelegate.addElement(entry);
    } else {
      localDelegate.insertElementAt(entry, pos);
    }
  }

Add to the current list of delegated catalogs.

This method always constructs the {@link #localDelegate}
vector so that it is ordered by length of partial
public identifier.

@param entry The DELEGATE catalog entry

Add to the current list of delegated catalogs .


static <K, V> SoftValueRef<K, V> create(K key, V val, ReferenceQueue<V> q)
   {
      if (val == null)
         return null;
      else
         return new SoftValueRef<K, V>(key, val, q);
   }

static < K , V > SoftValueRef < K , V > create ( K key , V val , ReferenceQueue < V > q ) { if ( val == null ) return null ; else return new SoftValueRef < K , V > ( key , val , q ) ; }

Safely create a new SoftValueRef

@param <K> the key type
@param <V> the value type
@param key the key
@param val the value
@param q   the reference queue
@return the reference or null if the value is null


protected static void fireOnThrowable(int type, Throwable t) {
      Object[] list = listeners.toArray();

      for (int i=0; i<list.length; i++) {
         ((ThrowableListener)list[i]).onThrowable(type, t);
      }
   }

protected static void fireOnThrowable ( int type , Throwable t ) { Object [ ] list = listeners . toArray ( ) ; for ( int i = 0 ; i < list . length ; i ++ ) { ( ( ThrowableListener ) list [ i ] ) . onThrowable ( type , t ) ; } }

Fire onThrowable to all registered listeners.

@param type    The type off the throwable.
@param t       Throwable

Fire onThrowable to all registered listeners .


public static void add(int type, Throwable t) {
      // don't add null throwables
      if (t == null) return;

      try {
         fireOnThrowable(type, t);
      }
      catch (Throwable bad) {
         // don't let these propagate, that could introduce unwanted side-effects
         System.err.println("Unable to handle throwable: " + t + " because of:");
         bad.printStackTrace();
      }
   }

Add a throwable that is to be handled.

@param type    The type off the throwable.
@param t       Throwable to be handled.


private List<T> createImplementation()
   {
      if (delegate instanceof ArrayList == false)
         return new ArrayList<T>(delegate);
      return delegate;
   }

private List < T > createImplementation ( ) { if ( delegate instanceof ArrayList == false ) return new ArrayList < T > ( delegate ) ; return delegate ; }

Create the list implementation

@return the list


public int compareTo(Object other)
   {
      if (other == this) return 0;
      TimerTask t = (TimerTask) other;
      long diff = getNextExecutionTime() - t.getNextExecutionTime();
      return (int) diff;
   }

public int compareTo ( Object other ) { if ( other == this ) return 0 ; TimerTask t = ( TimerTask ) other ; long diff = getNextExecutionTime ( ) - t . getNextExecutionTime ( ) ; return ( int ) diff ; }

A TimerTask is less than another if it will be scheduled before.
@throws ClassCastException if other is not a TimerTask, according to the Comparable contract

A TimerTask is less than another if it will be scheduled before .


public Object getValue()
   {
      try
      {
         String text = getAsText();
         if (text == null)
         {
            return null;
         }
         if (text.startsWith("/"))
         {
            // seems like localhost sometimes will look like:
            // /127.0.0.1 and the getByNames barfs on the slash - JGH
            text = text.substring(1);
         }
         return InetAddress.getByName(StringPropertyReplacer.replaceProperties(text));
      }
      catch (UnknownHostException e)
      {
         throw new NestedRuntimeException(e);
      }
   }

Returns a InetAddress for the input object converted to a string.

@return an InetAddress

@throws NestedRuntimeException   An UnknownHostException occured.

Returns a InetAddress for the input object converted to a string .


private Object getObject(final int index) {
      Object obj = list.get(index);

      return Objects.deref(obj);
   }

private Object getObject ( final int index ) { Object obj = list . get ( index ) ; return Objects . deref ( obj ) ; }

Dereference the object at the given index.

Dereference the object at the given index .


public Object set(final int index, final Object obj) {
      maintain();

      SoftObject soft = SoftObject.create(obj, queue);
      soft = (SoftObject)list.set(index, soft);

      return Objects.deref(soft);
   }

public Object set ( final int index , final Object obj ) { maintain ( ) ; SoftObject soft = SoftObject . create ( obj , queue ) ; soft = ( SoftObject ) list . set ( index , soft ) ; return Objects . deref ( soft ) ; }

Replaces the element at the specified position in this list with the
specified element.

@param index   Index of element to replace.
@param obj     Element to be stored at the specified postion.
@return        The previous element at the given index.

Replaces the element at the specified position in this list with the specified element .


private void maintain() {
      SoftObject obj;
      int count = 0;

      while ((obj = (SoftObject)queue.poll()) != null) {
         count++;
         list.remove(obj);
      }

      if (count != 0) {
         // some temporary debugging fluff
         System.err.println("vm reclaimed " + count + " objects");
      }
   }

private
void
maintain
(
)
{
SoftObject
obj
;
int
count
=
0
;
while
(
(
obj
=
(
SoftObject
)
queue
.
poll
(
)
)
!=
)
{
count
++
;
list
.
remove
(
obj
)
;
}
if
(
count
!=
0
)
{
// some temporary debugging fluff
System
.
err
.
println
(
"vm reclaimed "
+
count
+
" objects"
)
;
}
}

Maintains the collection by removing garbage collected objects.

Maintains the collection by removing garbage collected objects .


public static int addEntryType(String name, int numArgs) {
    entryTypes.put(name, new Integer(nextEntry));
    entryArgs.add(nextEntry, new Integer(numArgs));
    nextEntry++;

    return nextEntry-1;
  }

public static int addEntryType ( String name , int numArgs ) { entryTypes . put ( name , new Integer ( nextEntry ) ) ; entryArgs . add ( nextEntry , new Integer ( numArgs ) ) ; nextEntry ++ ; return nextEntry - 1 ; }

Adds a new catalog entry type.

@param name The name of the catalog entry type. This must be
unique among all types and is case-sensitive. (Adding a duplicate
name effectively replaces the old type with the new type.)
@param numArgs The number of arguments that this entry type
is required to have. There is no provision for variable numbers
of arguments.
@return The type for the new entry.


public static int getEntryType(String name)
    throws CatalogException {
    if (!entryTypes.containsKey(name)) {
      throw new CatalogException(CatalogException.INVALID_ENTRY_TYPE);
    }

    Integer iType = (Integer) entryTypes.get(name);

    if (iType == null) {
      throw new CatalogException(CatalogException.INVALID_ENTRY_TYPE);
    }

    return iType.intValue();
  }

public static int getEntryType ( String name ) throws CatalogException { if ( ! entryTypes . containsKey ( name ) ) { throw new CatalogException ( CatalogException . INVALID_ENTRY_TYPE ) ; } Integer iType = ( Integer ) entryTypes . get ( name ) ; if ( iType == null ) { throw new CatalogException ( CatalogException . INVALID_ENTRY_TYPE ) ; } return iType . intValue ( ) ; }

Lookup an entry type

@param name The name of the catalog entry type.
@return The type of the catalog entry with the specified name.
@throws CatalogException for any error


public static int getEntryArgCount(int type)
    throws CatalogException {
    try {
      Integer iArgs = (Integer) entryArgs.get(type);
      return iArgs.intValue();
    } catch (ArrayIndexOutOfBoundsException e) {
      throw new CatalogException(CatalogException.INVALID_ENTRY_TYPE);
    }
  }

public static int getEntryArgCount ( int type ) throws CatalogException { try { Integer iArgs = ( Integer ) entryArgs . get ( type ) ; return iArgs . intValue ( ) ; } catch ( ArrayIndexOutOfBoundsException e ) { throw new CatalogException ( CatalogException . INVALID_ENTRY_TYPE ) ; } }

Find out how many arguments an entry is required to have.

@param type A valid catalog entry type.
@return The number of arguments that entry type is required to have.
@throws CatalogException for any error

Find out how many arguments an entry is required to have .


public String getEntryArg(int argNum) {
    try {
      String arg = (String) args.get(argNum);
      return arg;
    } catch (ArrayIndexOutOfBoundsException e) {
      return null;
    }
  }

public String getEntryArg ( int argNum ) { try { String arg = ( String ) args . get ( argNum ) ; return arg ; } catch ( ArrayIndexOutOfBoundsException e ) { return null ; } }

Get an entry argument.

@param argNum The argument number (arguments are numbered from 0).
@return The specified argument or null if an invalid argNum is
provided.


public void setContextClassLoader(final Thread thread, final ClassLoader cl)
   {
      AccessController.doPrivileged(new PrivilegedAction()
      {
         public Object run()
         {
            thread.setContextClassLoader(cl);
            return null;
         }
      });
   }

public void setContextClassLoader ( final Thread thread , final ClassLoader cl ) { AccessController . doPrivileged ( new PrivilegedAction ( ) { public Object run ( ) { thread . setContextClassLoader ( cl ) ; return null ; } } ) ; }

Set the context classloader for the given thread

@param thread the thread
@param cl the new context classloader


private void swap(int a, int b)
   {
      // INV: assertExpr(a > 0);
      // INV: assertExpr(a <= size);
      // INV: assertExpr(b > 0);
      // INV: assertExpr(b <= size);
      // INV: assertExpr(queue[a] != null);
      // INV: assertExpr(queue[b] != null);
      // INV: assertExpr(queue[a].index == a);
      // INV: assertExpr(queue[b].index == b);
      TimeoutExtImpl temp = queue[a];
      queue[a] = queue[b];
      queue[a].index = a;
      queue[b] = temp;
      queue[b].index = b;
   }

Swap two nodes in the tree.

@param a the first index
@param b the second index


private TimeoutExtImpl removeNode(int index)
   {
      // INV: assertExpr(index > 0);
      // INV: assertExpr(index <= size);
      TimeoutExtImpl res = queue[index];
      // INV: assertExpr(res != null);
      // INV: assertExpr(res.index == index);
      if (index == size)
      {
         --size;
         queue[index] = null;
         return res;
      }
      swap(index, size); // Exchange removed node with last leaf node
      --size;
      // INV: assertExpr(res.index == size + 1);
      queue[res.index] = null;
      if (normalizeUp(index))
         return res; // Node moved up, so it shouldn't move down
      long t = queue[index].time;
      int c = index << 1;
      while (c <= size)
      {
         // INV: assertExpr(q[index].time == t);
         TimeoutExtImpl l = queue[c];
         // INV: assertExpr(l != null);
         // INV: assertExpr(l.index == c);
         if (c + 1 <= size)
         {
            // two children, swap with smallest
            TimeoutExtImpl r = queue[c + 1];
            // INV: assertExpr(r != null);
            // INV: assertExpr(r.index == c+1);
            if (l.time <= r.time)
            {
               if (t <= l.time)
                  break; // done
               swap(index, c);
               index = c;
            }
            else
            {
               if (t <= r.time)
                  break; // done
               swap(index, c + 1);
               index = c + 1;
            }
         }
         else
         { // one child
            if (t <= l.time)
               break; // done
            swap(index, c);
            index = c;
         }
         c = index << 1;
      }
      return res;
   }

Remove a node from the tree and normalize.

@param index the index in the queue
@return the removed node.

Remove a node from the tree and normalize .


private TimeoutExtImpl cleanupTimeoutExtImpl(TimeoutExtImpl timeout)
   {
      if (timeout != null)
         timeout.target = null;
      return null;
   }

private TimeoutExtImpl cleanupTimeoutExtImpl ( TimeoutExtImpl timeout ) { if ( timeout != null ) timeout . target = null ; return null ; }

Recursive cleanup of a TimeoutImpl

@return null


protected Class<?> loadClass(String className, boolean resolve)
      throws ClassNotFoundException
   {
      // Revert to standard rules
      if (standard)
         return super.loadClass(className, resolve);

      // Ask the parent
      Class<?> clazz = null;
      try
      {
         clazz = parent.loadClass(className);
      }
      catch (ClassNotFoundException e)
      {
         // Not found in parent,
         // maybe it is a proxy registered against this classloader?
         clazz = findLoadedClass(className);
         if (clazz == null)
            throw e;
      }

      // Link the class
      if (resolve)
         resolveClass(clazz);

      return clazz;
   }

Load a class, by asking the parent

@param className the class name to load
@param resolve whether to link the class
@return the loaded class
@throws ClassNotFoundException when the class could not be found


@SuppressWarnings("unused")
   public static void preload()
   {
      for (int i = 0; i < PROTOCOLS.length; i ++)
      {
         try
         {
            URL url = new URL(PROTOCOLS[i], "", -1, "");
            log.trace("Loaded protocol: " + PROTOCOLS[i]);
         }
         catch (Exception e)
         {
            log.warn("Failed to load protocol: " + PROTOCOLS[i], e);
         }
      }
   }

@
SuppressWarnings
(
"unused"
)
public
static
void
preload
(
)
{
for
(
int
i
=
0
;
i
<
PROTOCOLS
.
length
;
i
++
)
{
try
{
URL
url
=
new
URL
(
PROTOCOLS
[
i
]
,
""
,
1
,
""
)
;
log
.
trace
(
"Loaded protocol: "
+
PROTOCOLS
[
i
]
)
;
}
catch
(
Exception
e
)
{
log
.
warn
(
"Failed to load protocol: "
+
PROTOCOLS
[
i
]
,
e
)
;
}
}
}

Preload the JBoss specific protocol handlers, so that URL knows about
them even if the handler factory is changed.

Preload the JBoss specific protocol handlers so that URL knows about them even if the handler factory is changed .


public URLStreamHandler createURLStreamHandler(final String protocol)
   {
      // Check the handler map
      URLStreamHandler handler = (URLStreamHandler) handlerMap.get(protocol);
      if( handler != null )
         return handler;

      // Validate that createURLStreamHandler is not recursing
      String prevProtocol = (String) createURLStreamHandlerProtocol.get();
      if( prevProtocol != null && prevProtocol.equals(protocol) )
         return null;
      createURLStreamHandlerProtocol.set(protocol);

      // See if the handler pkgs definition has changed
      checkHandlerPkgs();

      // Search the handlerPkgs for a matching protocol handler
      ClassLoader ctxLoader = Thread.currentThread().getContextClassLoader();
      for(int p = 0; p < handlerPkgs.length; p ++)
      {
         try
         {
            // Form the standard protocol handler class name
            String classname = handlerPkgs[p] + "." + protocol + ".Handler";
            Class<?> type = null;

            try
            {
               type = ctxLoader.loadClass(classname);
            }
            catch(ClassNotFoundException e)
            {
               // Try our class loader
               type = Class.forName(classname);
            }

            if( type != null )
            {
               handler = (URLStreamHandler) type.newInstance();
               handlerMap.put(protocol, handler);
               log.trace("Found protocol:"+protocol+" handler:"+handler);
            }
         }
         catch (Throwable ignore)
         {
         }
      }

      createURLStreamHandlerProtocol.set(null);
      return handler;
   }

Search the handlerPkgs for URLStreamHandler classes matching the
pkg + protocol + ".Handler" naming convention.

@param protocol The protocol to create a stream handler for
@return The protocol handler or null if not found

Search the handlerPkgs for URLStreamHandler classes matching the pkg + protocol + . Handler naming convention .


private synchronized void checkHandlerPkgs()
   {
      String handlerPkgsProp = System.getProperty("java.protocol.handler.pkgs");
      if( handlerPkgsProp != null && handlerPkgsProp.equals(lastHandlerPkgs) == false )
      {
         // Update the handlerPkgs[] from the handlerPkgsProp
         StringTokenizer tokeninzer = new StringTokenizer(handlerPkgsProp, "|");
         ArrayList<String> tmp = new ArrayList<String>();
         while( tokeninzer.hasMoreTokens() )
         {
            String pkg = tokeninzer.nextToken().intern();
            if( tmp.contains(pkg) == false )
               tmp.add(pkg);
         }
         // Include the JBoss default protocol handler pkg
         if( tmp.contains(PACKAGE_PREFIX) == false )
            tmp.add(PACKAGE_PREFIX);
         handlerPkgs = new String[tmp.size()];
         tmp.toArray(handlerPkgs);
         lastHandlerPkgs = handlerPkgsProp;
      }
   }

See if the java.protocol.handler.pkgs system property has changed
and if it has, parse it to update the handlerPkgs array.

See if the java . protocol . handler . pkgs system property has changed and if it has parse it to update the handlerPkgs array .


public Object getValue()
   {
      try
      {
         ClassLoader loader = Thread.currentThread().getContextClassLoader();
         String classname = getAsText();
         Class<?> type = loader.loadClass(classname);

         return type;
      }
      catch (Exception e)
      {
         throw new NestedRuntimeException(e);
      }
   }

public Object getValue ( ) { try { ClassLoader loader = Thread . currentThread ( ) . getContextClassLoader ( ) ; String classname = getAsText ( ) ; Class < ? > type = loader . loadClass ( classname ) ; return type ; } catch ( Exception e ) { throw new NestedRuntimeException ( e ) ; } }

Returns a Class for the input object converted to a string.

@return a Class object

@throws NestedRuntimeException   Failed to create Class instance.

Returns a Class for the input object converted to a string .


private Set<T> createImplementation()
   {
      if (delegate instanceof HashSet == false)
         return new HashSet<T>(delegate);
      return delegate;
   }

private Set < T > createImplementation ( ) { if ( delegate instanceof HashSet == false ) return new HashSet < T > ( delegate ) ; return delegate ; }

Create the set implementation

@return the set


public static LongCounter makeSynchronized(final LongCounter counter)
   {
      return new Wrapper(counter) {
         /** The serialVersionUID */
         private static final long serialVersionUID = 8903330696503363758L;
            public synchronized long increment() {
               return this.counter.increment();
            }

            public synchronized long decrement() {
               return this.counter.decrement();
            }

            public synchronized long getCount() {
               return this.counter.getCount();
            }

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

            public synchronized int hashCode() {
               return this.counter.hashCode();
            }

            public synchronized boolean equals(final Object obj) {
               return this.counter.equals(obj);
            }

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

            public synchronized Object clone() {
               return this.counter.clone();
            }
         };
   }

public
static
LongCounter
makeSynchronized
(
final
LongCounter
counter
)
{
return
new
Wrapper
(
counter
)
{
/** The serialVersionUID */
private
static
final
long
serialVersionUID
=
8903330696503363758L
;
public
synchronized
long
increment
(
)
{
return
this
.
counter
.
increment
(
)
;
}
public
synchronized
long
decrement
(
)
{
return
this
.
counter
.
decrement
(
)
;
}
public
synchronized
long
getCount
(
)
{
return
this
.
counter
.
getCount
(
)
;
}
public
synchronized
void
reset
(
)
{
this
.
counter
.
reset
(
)
;
}
public
synchronized
int
hashCode
(
)
{
return
this
.
counter
.
hashCode
(
)
;
}
public
synchronized
boolean
equals
(
final
Object
obj
)
{
return
this
.
counter
.
equals
(
obj
)
;
}
public
synchronized
String
toString
(
)
{
return
this
.
counter
.
toString
(
)
;
}
public
synchronized
Object
clone
(
)
{
return
this
.
counter
.
clone
(
)
;
}
}
;
}

Return a synchronized counter.

@param counter    LongCounter to synchronize.
@return           Synchronized counter.


public static LongCounter makeDirectional(final LongCounter counter,
                                             final boolean increasing)
   {
      LongCounter temp;
      if (increasing) {
         temp = new Wrapper(counter) {
            /** The serialVersionUID */
            private static final long serialVersionUID = -8902748795144754375L;
            public long decrement() {
                  throw new UnsupportedOperationException();
               }

               public void reset() {
                  throw new UnsupportedOperationException();
               }
            };
      }
      else {
         temp = new Wrapper(counter) {
            /** The serialVersionUID */
            private static final long serialVersionUID = 2584758778978644599L;
               public long increment() {
                  throw new UnsupportedOperationException();
               }
            };
      }

      return temp;
   }

public
static
LongCounter
makeDirectional
(
final
LongCounter
counter
,
final
boolean
increasing
)
{
LongCounter
temp
;
if
(
increasing
)
{
temp
=
new
Wrapper
(
counter
)
{
/** The serialVersionUID */
private
static
final
long
serialVersionUID
=
8902748795144754375L
;
public
long
decrement
(
)
{
throw
new
UnsupportedOperationException
(
)
;
}
public
void
reset
(
)
{
throw
new
UnsupportedOperationException
(
)
;
}
}
;
}
else
{
temp
=
new
Wrapper
(
counter
)
{
/** The serialVersionUID */
private
static
final
long
serialVersionUID
=
2584758778978644599L
;
public
long
increment
(
)
{
throw
new
UnsupportedOperationException
(
)
;
}
}
;
}
return
temp
;
}

Returns a directional counter.

@param counter       LongCounter to make directional.
@param increasing    True to create an increasing only
or false to create a decreasing only.
@return              A directional counter.


protected boolean inExtensionNamespace() {
    boolean inExtension = false;

    Enumeration elements = namespaceStack.elements();
    while (!inExtension && elements.hasMoreElements()) {
      String ns = (String) elements.nextElement();
      if (ns == null) {
	inExtension = true;
      } else {
	inExtension = (!ns.equals(tr9401NamespaceName)
		       && !ns.equals(namespaceName));
      }
    }

    return inExtension;
  }

protected boolean inExtensionNamespace ( ) { boolean inExtension = false ; Enumeration elements = namespaceStack . elements ( ) ; while ( ! inExtension && elements . hasMoreElements ( ) ) { String ns = ( String ) elements . nextElement ( ) ; if ( ns == null ) { inExtension = true ; } else { inExtension = ( ! ns . equals ( tr9401NamespaceName ) && ! ns . equals ( namespaceName ) ) ; } } return inExtension ; }

Are we in an extension namespace?

@return true if the current stack of open namespaces includes
an extension namespace.


public void checkNotification(int result)
   {
      // Is a notification required?
      chunk += result;
      if (chunk >= chunkSize)
      {
         if (listener != null)
            listener.onStreamNotification(this, chunk);

         // Start a new chunk
         chunk = 0;
      }
   }

public
void
checkNotification
(
int
result
)
{
// Is a notification required?
chunk
+=
result
;
if
(
chunk
>=
chunkSize
)
{
if
(
listener
!=
)
listener
.
onStreamNotification
(
this
,
chunk
)
;
// Start a new chunk
chunk
=
0
;
}
}

Checks whether a notification is required and
notifies as appropriate

@param result the number of bytes written


public static synchronized void rebind(Name name, Object target, boolean createSubcontexts) throws NamingException
   {
      String key = name.toString();
      InitialContext ctx = new InitialContext();
      if (createSubcontexts == true && name.size() > 1)
      {
         int size = name.size() - 1;
         Util.createSubcontext(ctx, name.getPrefix(size));
      }
      rebind(ctx, key, target);
   }

public static synchronized void rebind ( Name name , Object target , boolean createSubcontexts ) throws NamingException { String key = name . toString ( ) ; InitialContext ctx = new InitialContext ( ) ; if ( createSubcontexts == true && name . size ( ) > 1 ) { int size = name . size ( ) - 1 ; Util . createSubcontext ( ctx , name . getPrefix ( size ) ) ; } rebind ( ctx , key , target ) ; }

A convenience method that simplifies the process of rebinding a
non-serializable object into a JNDI context. This version binds the
target object into the default IntitialContext using name path.

@param name the name to use as JNDI path name. The key into the
NonSerializableFactory map is obtained from the toString() value of name.
The name parameter cannot be a 0 length name.
@param target the non-Serializable object to bind.
@param createSubcontexts a flag indicating if subcontexts of name should
be created if they do not already exist.
@throws NamingException thrown on failure to rebind key into ctx.
@author Matt Carter

A convenience method that simplifies the process of rebinding a non - serializable object into a JNDI context . This version binds the target object into the default IntitialContext using name path .


public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable env)
        throws Exception
    {	// Get the nns value from the Reference obj and use it as the map key
        Reference ref = (Reference) obj;
        RefAddr addr = ref.get("nns");
        String key = (String) addr.getContent();
        Object target = wrapperMap.get(key);
        return target;
    }

Transform the obj Reference bound into the JNDI namespace into the
actual non-Serializable object.

@param obj the object bound in the JNDI namespace. This must be an implementation
of javax.naming.Reference with a javax.naming.RefAddr of type "nns" whose
content is the String key used to location the non-Serializable object in the
NonSerializableFactory map.
@param name ignored.
@param nameCtx ignored.
@param env ignored.

@return the non-Serializable object associated with the obj Reference if one
exists, null if one does not.

Transform the obj Reference bound into the JNDI namespace into the actual non - Serializable object .


public static String subst(final StringBuffer buff, final String string,
      final Map map, final String beginToken,
      final String endToken)
   {
      int begin = 0, rangeEnd = 0;
      Range range;

      while ((range = rangeOf(beginToken, endToken, string, rangeEnd)) != null)
      {
         // append the first part of the string
         buff.append(string.substring(begin, range.begin));

         // Get the string to replace from the map
         String key = string.substring(range.begin + beginToken.length(),
            range.end);
         Object value = map.get(key);
         // if mapping does not exist then use empty;
         if (value == null) value = EMPTY;

         // append the replaced string
         buff.append(value);

         // update positions
         begin = range.end + endToken.length();
         rangeEnd = begin;
      }

      // append the rest of the string
      buff.append(string.substring(begin, string.length()));

      return buff.toString();
   }

Substitute sub-strings in side of a string.

@param buff       String buffer to use for substitution (buffer is not reset)
@param string     String to subst mappings in
@param map        Map of from->to strings
@param beginToken Beginning token
@param endToken   Ending token
@return           Substituted string

Substitute sub - strings in side of a string .


public static String[] split(final String string, final String delim,
      final int limit)
   {
      // get the count of delim in string, if count is > limit
      // then use limit for count.  The number of delimiters is less by one
      // than the number of elements, so add one to count.
      int count = count(string, delim) + 1;
      if (limit > 0 && count > limit)
      {
         count = limit;
      }

      String strings[] = new String[count];
      int begin = 0;

      for (int i = 0; i < count; i++)
      {
         // get the next index of delim
         int end = string.indexOf(delim, begin);

         // if the end index is -1 or if this is the last element
         // then use the string's length for the end index
         if (end == -1 || i + 1 == count)
            end = string.length();

         // if end is 0, then the first element is empty
         if (end == 0)
            strings[i] = EMPTY;
         else
            strings[i] = string.substring(begin, end);

         // update the begining index
         begin = end + 1;
      }

      return strings;
   }

Split up a string into multiple strings based on a delimiter.

@param string  String to split up.
@param delim   Delimiter.
@param limit   Limit the number of strings to split into
(-1 for no limit).
@return        Array of strings.

Split up a string into multiple strings based on a delimiter .


public static String join(final byte array[])
   {
      Byte bytes[] = new Byte[array.length];
      for (int i = 0; i < bytes.length; i++)
      {
         bytes[i] = new Byte(array[i]);
      }

      return join(bytes, null);
   }

public static String join ( final byte array [ ] ) { Byte bytes [ ] = new Byte [ array . length ] ; for ( int i = 0 ; i < bytes . length ; i ++ ) { bytes [ i ] = new Byte ( array [ i ] ) ; } return join ( bytes , null ) ; }

Convert and join an array of bytes into one string.

@param array   Array of objects to join as strings.
@return        Converted and joined objects.

Convert and join an array of bytes into one string .


public static final void defaultToString(JBossStringBuilder buffer, Object object)
   {
      if (object == null)
         buffer.append("null");
      else
      {
         buffer.append(object.getClass().getName());
         buffer.append('@');
         buffer.append(Integer.toHexString(System.identityHashCode(object)));
      }
   }

public static final void defaultToString ( JBossStringBuilder buffer , Object object ) { if ( object == null ) buffer . append ( "null" ) ; else { buffer . append ( object . getClass ( ) . getName ( ) ) ; buffer . append ( ' ' ) ; buffer . append ( Integer . toHexString ( System . identityHashCode ( object ) ) ) ; } }

The default toString implementation of an object

@param object the object
@param buffer the string builder


public Object getValue()
   {
      String text = getAsText();
      BlockingMode mode = BlockingMode.toBlockingMode(text);
      return mode;
   }

public Object getValue ( ) { String text = getAsText ( ) ; BlockingMode mode = BlockingMode . toBlockingMode ( text ) ; return mode ; }

Returns a BlockingMode for the input object converted to a string.

@return a BlockingMode enum instance

Returns a BlockingMode for the input object converted to a string .


public void create()
   {
      if( threadSafe )
         entryMap = Collections.synchronizedMap(new HashMap());
      else
         entryMap = new HashMap();
      now = System.currentTimeMillis();
   }

public void create ( ) { if ( threadSafe ) entryMap = Collections . synchronizedMap ( new HashMap ( ) ) ; else entryMap = new HashMap ( ) ; now = System . currentTimeMillis ( ) ; }

Initializes the cache for use. Prior to this the cache has no store.

Initializes the cache for use . Prior to this the cache has no store .


public Object get(Object key)
   {
      TimedEntry entry = (TimedEntry) entryMap.get(key);
      if( entry == null )
         return null;

      if( entry.isCurrent(now) == false )
      {   // Try to refresh the entry
         if( entry.refresh() == false )
         {   // Failed, remove the entry and return null
            entry.destroy();
            entryMap.remove(key);
            return null;
         }
      }
      Object value = entry.getValue();
      return value;
   }

Get the cache value for key if it has not expired. If the TimedEntry
is expired its destroy method is called and then removed from the cache.
@return the TimedEntry value or the original value if it was not an
instance of TimedEntry if key is in the cache, null otherwise.

Get the cache value for key if it has not expired . If the TimedEntry is expired its destroy method is called and then removed from the cache .


public Object peek(Object key)
   {
      TimedEntry entry = (TimedEntry) entryMap.get(key);
      Object value = null;
      if( entry != null )
         value = entry.getValue();
      return value;
   }

public Object peek ( Object key ) { TimedEntry entry = ( TimedEntry ) entryMap . get ( key ) ; Object value = null ; if ( entry != null ) value = entry . getValue ( ) ; return value ; }

Get the cache value for key. This method does not check to see if
the entry has expired.
@return the TimedEntry value or the original value if it was not an
instancee of TimedEntry if key is in the cache, null otherwise.

Get the cache value for key . This method does not check to see if the entry has expired .


public void remove(Object key)
   {
      TimedEntry entry = (TimedEntry) entryMap.remove(key);
      if( entry != null )
         entry.destroy();
   }

public void remove ( Object key ) { TimedEntry entry = ( TimedEntry ) entryMap . remove ( key ) ; if ( entry != null ) entry . destroy ( ) ; }

Remove the entry associated with key and call destroy on the entry
if found.

Remove the entry associated with key and call destroy on the entry if found .


public void flush()
   {
      Map tmpMap = null;
      synchronized( this )
      {
         tmpMap = entryMap;
         if( threadSafe )
            entryMap = Collections.synchronizedMap(new HashMap());
         else
            entryMap = new HashMap();
      }

      // Notify the entries of their removal
      Iterator iter = tmpMap.values().iterator();
      while( iter.hasNext() )
      {
         TimedEntry entry = (TimedEntry) iter.next();
         entry.destroy();
      }
      tmpMap.clear();
   }

public
void
flush
(
)
{
Map
tmpMap
=
;
synchronized
(
this
)
{
tmpMap
=
entryMap
;
if
(
threadSafe
)
entryMap
=
Collections
.
synchronizedMap
(
new
HashMap
(
)
)
;
else
entryMap
=
new
HashMap
(
)
;
}
// Notify the entries of their removal
Iterator
iter
=
tmpMap
.
values
(
)
.
iterator
(
)
;
while
(
iter
.
hasNext
(
)
)
{
TimedEntry
entry
=
(
TimedEntry
)
iter
.
next
(
)
;
entry
.
destroy
(
)
;
}
tmpMap
.
clear
(
)
;
}


public List getValidKeys()
   {
      ArrayList validKeys = new ArrayList();
      synchronized( entryMap )
      {
         Iterator iter = entryMap.entrySet().iterator();
         while( iter.hasNext() )
         {
            Map.Entry entry = (Map.Entry) iter.next();
            TimedEntry value = (TimedEntry) entry.getValue();
            if( value.isCurrent(now) == true )
               validKeys.add(entry.getKey());
         }
      }
      return validKeys;
   }

public List getValidKeys ( ) { ArrayList validKeys = new ArrayList ( ) ; synchronized ( entryMap ) { Iterator iter = entryMap . entrySet ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { Map . Entry entry = ( Map . Entry ) iter . next ( ) ; TimedEntry value = ( TimedEntry ) entry . getValue ( ) ; if ( value . isCurrent ( now ) == true ) validKeys . add ( entry . getKey ( ) ) ; } } return validKeys ; }

Get the list of keys for entries that are not expired.

@return A List of the keys corresponding to valid entries

Get the list of keys for entries that are not expired .


public synchronized void setResolution(int resolution)
   {
      if( resolution <= 0 )
         resolution = 60;
      if( resolution != this.resolution )
      {
         this.resolution = resolution;
         theTimer.cancel();
         theTimer = new ResolutionTimer();
         resolutionTimer.scheduleAtFixedRate(theTimer, 0, 1000*resolution);
      }
   }

public synchronized void setResolution ( int resolution ) { if ( resolution <= 0 ) resolution = 60 ; if ( resolution != this . resolution ) { this . resolution = resolution ; theTimer . cancel ( ) ; theTimer = new ResolutionTimer ( ) ; resolutionTimer . scheduleAtFixedRate ( theTimer , 0 , 1000 * resolution ) ; } }

Set the cache timer resolution

@param resolution - the resolution in seconds of the cache timer. A cache does
not query the system time on every get() invocation. Rather the cache
updates its notion of the current time every 'resolution' seconds.


public TimedEntry peekEntry(Object key)
   {
      TimedEntry entry = (TimedEntry) entryMap.get(key);
      return entry;
   }

public TimedEntry peekEntry ( Object key ) { TimedEntry entry = ( TimedEntry ) entryMap . get ( key ) ; return entry ; }

Get the raw TimedEntry for key without performing any expiration check.
@param key
@return the TimedEntry value associated with key if one exists, null otherwise.

Get the raw TimedEntry for key without performing any expiration check .


public static Iterator getChildrenByTagName(Element element,
                                               String tagName)
   {
      if (element == null) return null;
      // getElementsByTagName gives the corresponding elements in the whole
      // descendance. We want only children

      NodeList children = element.getChildNodes();
      ArrayList goodChildren = new ArrayList();
      for (int i=0; i<children.getLength(); i++) {
         Node currentChild = children.item(i);
         if (currentChild.getNodeType() == Node.ELEMENT_NODE &&
             ((Element)currentChild).getTagName().equals(tagName)) {
            goodChildren.add(currentChild);
         }
      }
      return goodChildren.iterator();
   }

Returns an iterator over the children of the given element with
the given tag name.

@param element    The parent element
@param tagName    The name of the desired child
@return           An interator of children or null if element is null.

Returns an iterator over the children of the given element with the given tag name .


public static Element getUniqueChild(Element element, String tagName)
      throws Exception
   {
      Iterator goodChildren = getChildrenByTagName(element, tagName);

      if (goodChildren != null && goodChildren.hasNext()) {
         Element child = (Element)goodChildren.next();
         if (goodChildren.hasNext()) {
            throw new Exception
               ("expected only one " + tagName + " tag");
         }
         return child;
      } else {
         throw new Exception
            ("expected one " + tagName + " tag");
      }
   }

public
static
Element
getUniqueChild
(
Element
element
,
String
tagName
)
throws
Exception
{
Iterator
goodChildren
=
getChildrenByTagName
(
element
,
tagName
)
;
if
(
goodChildren
!=
&&
goodChildren
.
hasNext
(
)
)
{
Element
child
=
(
Element
)
goodChildren
.
next
(
)
;
if
(
goodChildren
.
hasNext
(
)
)
{
throw
new
Exception
(
"expected only one "
+
tagName
+
" tag"
)
;
}
return
child
;
}
else
{
throw
new
Exception
(
"expected one "
+
tagName
+
" tag"
)
;
}
}

Gets the child of the specified element having the specified unique
name.  If there are more than one children elements with the same name
and exception is thrown.

@param element    The parent element
@param tagName    The name of the desired child
@return           The named child.

@throws Exception   Child was not found or was not unique.

Gets the child of the specified element having the specified unique name . If there are more than one children elements with the same name and exception is thrown .


public static Element getOptionalChild(Element element, String tagName)
      throws Exception
   {
      return getOptionalChild(element, tagName, null);
   }

public static Element getOptionalChild ( Element element , String tagName ) throws Exception { return getOptionalChild ( element , tagName , null ) ; }

Gets the child of the specified element having the
specified name. If the child with this name doesn't exist
then null is returned instead.

@param element the parent element
@param tagName the name of the desired child
@return either the named child or null
@throws Exception

Gets the child of the specified element having the specified name . If the child with this name doesn t exist then null is returned instead .


public static String getElementContent(Element element, String defaultStr)
      throws Exception
   {
      if (element == null)
         return defaultStr;

      NodeList children = element.getChildNodes();
      String result = "";
      for (int i = 0; i < children.getLength(); i++)
      {
         if (children.item(i).getNodeType() == Node.TEXT_NODE ||
             children.item(i).getNodeType() == Node.CDATA_SECTION_NODE)
         {
            result += children.item(i).getNodeValue();
         }
         else if( children.item(i).getNodeType() == Node.COMMENT_NODE )
         {
            // Ignore comment nodes
         }
      }
      return result.trim();
   }

public
static
String
getElementContent
(
Element
element
,
String
defaultStr
)
throws
Exception
{
if
(
element
==
)
return
defaultStr
;
NodeList
children
=
element
.
getChildNodes
(
)
;
String
result
=
""
;
for
(
int
i
=
0
;
i
<
children
.
getLength
(
)
;
i
++
)
{
if
(
children
.
item
(
i
)
.
getNodeType
(
)
==
Node
.
TEXT_NODE
||
children
.
item
(
i
)
.
getNodeType
(
)
==
Node
.
CDATA_SECTION_NODE
)
{
result
+=
children
.
item
(
i
)
.
getNodeValue
(
)
;
}
else
if
(
children
.
item
(
i
)
.
getNodeType
(
)
==
Node
.
COMMENT_NODE
)
{
// Ignore comment nodes
}
}
return
result
.
trim
(
)
;
}

Get the content of the given element.

@param element       The element to get the content for.
@param defaultStr    The default to return when there is no content.
@return              The content of the element or the default.
@throws Exception


public static String getUniqueChildContent(Element element,
                                              String tagName)
      throws Exception
   {
      return getElementContent(getUniqueChild(element, tagName));
   }

public static String getUniqueChildContent ( Element element , String tagName ) throws Exception { return getElementContent ( getUniqueChild ( element , tagName ) ) ; }

Macro to get the content of a unique child element.

@param element    The parent element.
@param tagName    The name of the desired child.
@return           The element content or null.
@throws Exception

Macro to get the content of a unique child element .


public static String getOptionalChildContent(Element element,
                                                String tagName)
      throws Exception
   {
      return getElementContent(getOptionalChild(element, tagName));
   }

public static String getOptionalChildContent ( Element element , String tagName ) throws Exception { return getElementContent ( getOptionalChild ( element , tagName ) ) ; }

Macro to get the content of an optional child element.

@param element    The parent element.
@param tagName    The name of the desired child.
@return           The element content or null.
@throws Exception

Macro to get the content of an optional child element .


public void setMaximumQueueSize(int size)
   {
      // Reset the executor work queue
      ArrayList tmp = new ArrayList();
      queue.drainTo(tmp);
      queue = new LinkedBlockingQueue(size);
      queue.addAll(tmp);

      ThreadFactory tf = executor.getThreadFactory();
      RejectedExecutionHandler handler = executor.getRejectedExecutionHandler();
      long keepAlive = executor.getKeepAliveTime(TimeUnit.SECONDS);
      int cs = executor.getCorePoolSize();
      int mcs = executor.getMaximumPoolSize();
      executor = new ThreadPoolExecutor(cs, mcs, keepAlive, TimeUnit.SECONDS, queue);
      executor.setThreadFactory(tf);
      executor.setRejectedExecutionHandler(handler);
   }

public
void
setMaximumQueueSize
(
int
size
)
{
// Reset the executor work queue
ArrayList
tmp
=
new
ArrayList
(
)
;
queue
.
drainTo
(
tmp
)
;
queue
=
new
LinkedBlockingQueue
(
size
)
;
queue
.
addAll
(
tmp
)
;
ThreadFactory
tf
=
executor
.
getThreadFactory
(
)
;
RejectedExecutionHandler
handler
=
executor
.
getRejectedExecutionHandler
(
)
;
long
keepAlive
=
executor
.
getKeepAliveTime
(
TimeUnit
.
SECONDS
)
;
int
cs
=
executor
.
getCorePoolSize
(
)
;
int
mcs
=
executor
.
getMaximumPoolSize
(
)
;
executor
=
new
ThreadPoolExecutor
(
cs
,
mcs
,
keepAlive
,
TimeUnit
.
SECONDS
,
queue
)
;
executor
.
setThreadFactory
(
tf
)
;
executor
.
setRejectedExecutionHandler
(
handler
)
;
}

This resets the work queue capacity. This requires recreating the
work queue and ThreadPoolExecutor, so this needs to be called
before doing any work with the pool.

@param size new work queue capacity

This resets the work queue capacity . This requires recreating the work queue and ThreadPoolExecutor so this needs to be called before doing any work with the pool .


public void setBlockingMode(String name)
   {
      blockingMode = BlockingMode.toBlockingMode(name);
      if( blockingMode == null )
         blockingMode = BlockingMode.ABORT;
   }

public void setBlockingMode ( String name ) { blockingMode = BlockingMode . toBlockingMode ( name ) ; if ( blockingMode == null ) blockingMode = BlockingMode . ABORT ; }

For backward compatibility with the previous string based mode
@param name - the string form of the mode enum


public void setBlockingModeString(String name)
   {
      blockingMode = BlockingMode.toBlockingMode(name);
      if( blockingMode == null )
         blockingMode = BlockingMode.ABORT;
   }

public void setBlockingModeString ( String name ) { blockingMode = BlockingMode . toBlockingMode ( name ) ; if ( blockingMode == null ) blockingMode = BlockingMode . ABORT ; }

For backward compatibility with the previous string based mode
This is needed for microcontainer as it gets confused with overloaded
setters.
@param name - the string form of the mode enum

For backward compatibility with the previous string based mode This is needed for microcontainer as it gets confused with overloaded setters .


protected void execute(TaskWrapper wrapper)
   {
      if( trace )
         log.trace("execute, wrapper="+wrapper);
      try
      {
         executor.execute(wrapper);
      }
      catch (Throwable t)
      {
         wrapper.rejectTask(new ThreadPoolFullException("Error scheduling work: " + wrapper, t));
      }
   }

protected
void
execute
(
TaskWrapper
wrapper
)
{
if
(
trace
)
log
.
trace
(
"execute, wrapper="
+
wrapper
)
;
try
{
executor
.
execute
(
wrapper
)
;
}
catch
(
Throwable
t
)
{
wrapper
.
rejectTask
(
new
ThreadPoolFullException
(
"Error scheduling work: "
+
wrapper
,
t
)
)
;
}
}

Execute a task

@param wrapper the task wrapper


public String resolveSystem(String systemId)
    throws MalformedURLException, IOException {

    String resolved = super.resolveSystem(systemId);
    if (resolved != null) {
      return resolved;
    }

    Enumeration enumt = catalogEntries.elements();
    while (enumt.hasMoreElements()) {
      CatalogEntry e = (CatalogEntry) enumt.nextElement();
      if (e.getEntryType() == RESOLVER) {
	resolved = resolveExternalSystem(systemId, e.getEntryArg(0));
	if (resolved != null) {
	  return resolved;
	}
      } else if (e.getEntryType() == SYSTEMSUFFIX) {
	String suffix = e.getEntryArg(0);
	String result = e.getEntryArg(1);

	if (suffix.length() <= systemId.length()
	    && systemId.substring(systemId.length()-suffix.length()).equals(suffix)) {
	  return result;
	}
      }
    }

    return resolveSubordinateCatalogs(Catalog.SYSTEM,
				      null,
				      null,
				      systemId);
  }

public String resolveSystem ( String systemId ) throws MalformedURLException , IOException { String resolved = super . resolveSystem ( systemId ) ; if ( resolved != null ) { return resolved ; } Enumeration enumt = catalogEntries . elements ( ) ; while ( enumt . hasMoreElements ( ) ) { CatalogEntry e = ( CatalogEntry ) enumt . nextElement ( ) ; if ( e . getEntryType ( ) == RESOLVER ) { resolved = resolveExternalSystem ( systemId , e . getEntryArg ( 0 ) ) ; if ( resolved != null ) { return resolved ; } } else if ( e . getEntryType ( ) == SYSTEMSUFFIX ) { String suffix = e . getEntryArg ( 0 ) ; String result = e . getEntryArg ( 1 ) ; if ( suffix . length ( ) <= systemId . length ( ) && systemId . substring ( systemId . length ( ) - suffix . length ( ) ) . equals ( suffix ) ) { return result ; } } } return resolveSubordinateCatalogs ( Catalog . SYSTEM , null , null , systemId ) ; }

Return the applicable SYSTEM system identifier, resorting
to external RESOLVERs if necessary.

If a SYSTEM entry exists in the Catalog
for the system ID specified, return the mapped value.

In the Resolver (as opposed to the Catalog) class, if the
URI isn't found by the usual algorithm, SYSTEMSUFFIX entries are
considered.

On Windows-based operating systems, the comparison between
the system identifier provided and the SYSTEM entries in the
Catalog is case-insensitive.

@param systemId The system ID to locate in the catalog.

@return The system identifier to use for systemId.

@throws MalformedURLException The formal system identifier of a
subordinate catalog cannot be turned into a valid URL.
@throws IOException Error reading subordinate catalog file.

Return the applicable SYSTEM system identifier resorting to external RESOLVERs if necessary .


public String resolvePublic(String publicId, String systemId)
    throws MalformedURLException, IOException {

    String resolved = super.resolvePublic(publicId, systemId);
    if (resolved != null) {
      return resolved;
    }

    Enumeration enumt = catalogEntries.elements();
    while (enumt.hasMoreElements()) {
      CatalogEntry e = (CatalogEntry) enumt.nextElement();
      if (e.getEntryType() == RESOLVER) {
	if (systemId != null) {
	  resolved = resolveExternalSystem(systemId,
					   e.getEntryArg(0));
	  if (resolved != null) {
	    return resolved;
	  }
	}
	resolved = resolveExternalPublic(publicId, e.getEntryArg(0));
	if (resolved != null) {
	  return resolved;
	}
      }
    }

    return resolveSubordinateCatalogs(Catalog.PUBLIC,
				      null,
				      publicId,
				      systemId);
  }

public String resolvePublic ( String publicId , String systemId ) throws MalformedURLException , IOException { String resolved = super . resolvePublic ( publicId , systemId ) ; if ( resolved != null ) { return resolved ; } Enumeration enumt = catalogEntries . elements ( ) ; while ( enumt . hasMoreElements ( ) ) { CatalogEntry e = ( CatalogEntry ) enumt . nextElement ( ) ; if ( e . getEntryType ( ) == RESOLVER ) { if ( systemId != null ) { resolved = resolveExternalSystem ( systemId , e . getEntryArg ( 0 ) ) ; if ( resolved != null ) { return resolved ; } } resolved = resolveExternalPublic ( publicId , e . getEntryArg ( 0 ) ) ; if ( resolved != null ) { return resolved ; } } } return resolveSubordinateCatalogs ( Catalog . PUBLIC , null , publicId , systemId ) ; }

Return the applicable PUBLIC or SYSTEM identifier, resorting
to external resolvers if necessary.

This method searches the Catalog and returns the system
identifier specified for the given system or
public identifiers. If
no appropriate PUBLIC or SYSTEM entry is found in the Catalog,
null is returned.

Note that a system or public identifier in the current catalog
(or subordinate catalogs) will be used in preference to an
external resolver. Further, if a systemId is present, the external
resolver(s) will be queried for that before the publicId.

@param publicId The public identifier to locate in the catalog.
Public identifiers are normalized before comparison.
@param systemId The nominal system identifier for the entity
in question (as provided in the source document).

@throws MalformedURLException The formal system identifier of a
subordinate catalog cannot be turned into a valid URL.
@throws IOException Error reading subordinate catalog file.

@return The system identifier to use.
Note that the nominal system identifier is not returned if a
match is not found in the catalog, instead null is returned
to indicate that no match was found.

Return the applicable PUBLIC or SYSTEM identifier resorting to external resolvers if necessary .


protected String resolveExternalSystem(String systemId, String resolver)
	throws MalformedURLException, IOException {
	Resolver r = queryResolver(resolver, "i2l", systemId, null);
	if (r != null) {
	    return r.resolveSystem(systemId);
	} else {
	    return null;
	}
    }

protected String resolveExternalSystem ( String systemId , String resolver ) throws MalformedURLException , IOException { Resolver r = queryResolver ( resolver , "i2l" , systemId , null ) ; if ( r != null ) { return r . resolveSystem ( systemId ) ; } else { return null ; } }

Query an external RFC2483 resolver for a system identifier.

@param systemId The system ID to locate.
@param resolver The name of the resolver to use.

@return The system identifier to use for the systemId.
@throws MalformedURLException
@throws IOException

Query an external RFC2483 resolver for a system identifier .


protected String resolveExternalPublic(String publicId, String resolver)
	throws MalformedURLException, IOException {
	Resolver r = queryResolver(resolver, "fpi2l", publicId, null);
	if (r != null) {
	    return r.resolvePublic(publicId, null);
	} else {
	    return null;
	}
    }

protected String resolveExternalPublic ( String publicId , String resolver ) throws MalformedURLException , IOException { Resolver r = queryResolver ( resolver , "fpi2l" , publicId , null ) ; if ( r != null ) { return r . resolvePublic ( publicId , null ) ; } else { return null ; } }

Query an external RFC2483 resolver for a public identifier.

@param publicId The system ID to locate.
@param resolver The name of the resolver to use.

@throws MalformedURLException
@throws IOException
@return The system identifier to use for the systemId.

Query an external RFC2483 resolver for a public identifier .


protected Resolver queryResolver(String resolver,
				     String command,
				     String arg1,
				     String arg2) {
	String RFC2483 = resolver + "?command=" + command
	    + "&format=tr9401&uri=" + arg1
	    + "&uri2=" + arg2;

	try {
	    URL url = new URL(RFC2483);

	    URLConnection urlCon = url.openConnection();

	    urlCon.setUseCaches(false);

	    Resolver r = (Resolver) newCatalog();

	    String cType = urlCon.getContentType();

	    // I don't care about the character set or subtype
	    if (cType.indexOf(";") > 0) {
		cType = cType.substring(0, cType.indexOf(";"));
	    }

	    r.parseCatalog(cType, urlCon.getInputStream());

	    return r;
	} catch (CatalogException cex) {
	  if (cex.getExceptionType() == CatalogException.UNPARSEABLE) {
	    catalogManager.debug.message(1, "Unparseable catalog: " + RFC2483);
	  } else if (cex.getExceptionType()
		     == CatalogException.UNKNOWN_FORMAT) {
	    catalogManager.debug.message(1, "Unknown catalog format: " + RFC2483);
	  }
	  return null;
	} catch (MalformedURLException mue) {
	    catalogManager.debug.message(1, "Malformed resolver URL: " + RFC2483);
	    return null;
	} catch (IOException ie) {
	    catalogManager.debug.message(1, "I/O Exception opening resolver: " + RFC2483);
	    return null;
	}
    }

Query an external RFC2483 resolver.

@param resolver The URL of the RFC2483 resolver.
@param command The command to send the resolver.
@param arg1 The first argument to the resolver.
@param arg2 The second argument to the resolver, usually null.

@return The Resolver constructed.


private Vector appendVector(Vector vec, Vector appvec) {
	if (appvec != null) {
	    for (int count = 0; count < appvec.size(); count++) {
		vec.addElement(appvec.elementAt(count));
	    }
	}
	return vec;
    }

private Vector appendVector ( Vector vec , Vector appvec ) { if ( appvec != null ) { for ( int count = 0 ; count < appvec . size ( ) ; count ++ ) { vec . addElement ( appvec . elementAt ( count ) ) ; } } return vec ; }

Append two vectors, returning the result.

@param vec The first vector
@param appvec The vector to be appended
@return The vector vec, with appvec's elements appended to it

Append two vectors returning the result .


public Vector resolveAllSystemReverse(String systemId)
	throws MalformedURLException, IOException {
	Vector resolved = new Vector();

	// If there's a SYSTEM entry in this catalog, use it
	if (systemId != null) {
	    Vector localResolved = resolveLocalSystemReverse(systemId);
	    resolved = appendVector(resolved, localResolved);
	}

	// Otherwise, look in the subordinate catalogs
	Vector subResolved = resolveAllSubordinateCatalogs(SYSTEMREVERSE,
							   null,
							   null,
							   systemId);

	return appendVector(resolved, subResolved);
    }

Find the URNs for a given system identifier in all catalogs.

@param systemId The system ID to locate.

@throws MalformedURLException
@throws IOException
@return A vector of URNs that map to the systemId.

Find the URNs for a given system identifier in all catalogs .


public String resolveSystemReverse(String systemId)
	throws MalformedURLException, IOException {
	Vector resolved = resolveAllSystemReverse(systemId);
	if (resolved != null && resolved.size() > 0) {
	    return (String) resolved.elementAt(0);
	} else {
	    return null;
	}
    }

public String resolveSystemReverse ( String systemId ) throws MalformedURLException , IOException { Vector resolved = resolveAllSystemReverse ( systemId ) ; if ( resolved != null && resolved . size ( ) > 0 ) { return ( String ) resolved . elementAt ( 0 ) ; } else { return null ; } }

Find the URN for a given system identifier.

@param systemId The system ID to locate.

@throws MalformedURLException
@throws IOException
@return A (single) URN that maps to the systemId.

Find the URN for a given system identifier .


public Vector resolveAllSystem(String systemId)
	throws MalformedURLException, IOException {
	Vector resolutions = new Vector();

	// If there are SYSTEM entries in this catalog, start with them
	if (systemId != null) {
	    Vector localResolutions = resolveAllLocalSystem(systemId);
	    resolutions = appendVector(resolutions, localResolutions);
	}

	// Then look in the subordinate catalogs
	Vector subResolutions = resolveAllSubordinateCatalogs(SYSTEM,
							      null,
							      null,
							      systemId);
	resolutions = appendVector(resolutions, subResolutions);

	if (resolutions.size() > 0) {
	    return resolutions;
	} else {
	    return null;
	}
    }

Return the applicable SYSTEM system identifiers.

If one or more SYSTEM entries exists in the Catalog
for the system ID specified, return the mapped values.

The caller is responsible for doing any necessary
normalization of the system identifier before calling
this method. For example, a relative system identifier in
a document might be converted to an absolute system identifier
before attempting to resolve it.

Note that this function will force all subordinate catalogs
to be loaded.

On Windows-based operating systems, the comparison between
the system identifier provided and the SYSTEM entries in the
Catalog is case-insensitive.

@param systemId The system ID to locate in the catalog.

@return The system identifier to use for the notation.

@throws MalformedURLException The formal system identifier of a
subordinate catalog cannot be turned into a valid URL.
@throws IOException Error reading subordinate catalog file.

Return the applicable SYSTEM system identifiers .


private Vector resolveAllLocalSystem(String systemId) {
	Vector map = new Vector();
	String osname = System.getProperty("os.name");
	boolean windows = (osname.indexOf("Windows") >= 0);
	Enumeration enumt = catalogEntries.elements();
	while (enumt.hasMoreElements()) {
	    CatalogEntry e = (CatalogEntry) enumt.nextElement();
	    if (e.getEntryType() == SYSTEM
		&& (e.getEntryArg(0).equals(systemId)
		    || (windows
			&& e.getEntryArg(0).equalsIgnoreCase(systemId)))) {
		map.addElement(e.getEntryArg(1));
	    }
	}
	if (map.size() == 0) {
	    return null;
	} else {
	    return map;
	}
    }

private Vector resolveAllLocalSystem ( String systemId ) { Vector map = new Vector ( ) ; String osname = System . getProperty ( "os.name" ) ; boolean windows = ( osname . indexOf ( "Windows" ) >= 0 ) ; Enumeration enumt = catalogEntries . elements ( ) ; while ( enumt . hasMoreElements ( ) ) { CatalogEntry e = ( CatalogEntry ) enumt . nextElement ( ) ; if ( e . getEntryType ( ) == SYSTEM && ( e . getEntryArg ( 0 ) . equals ( systemId ) || ( windows && e . getEntryArg ( 0 ) . equalsIgnoreCase ( systemId ) ) ) ) { map . addElement ( e . getEntryArg ( 1 ) ) ; } } if ( map . size ( ) == 0 ) { return null ; } else { return map ; } }

Return all applicable SYSTEM system identifiers in this
catalog.

If one or more SYSTEM entries exists in the catalog file
for the system ID specified, return the mapped values.

@param systemId The system ID to locate in the catalog

@return A vector of the mapped system identifiers or null

Return all applicable SYSTEM system identifiers in this catalog .


private synchronized Vector resolveAllSubordinateCatalogs(int entityType,
					      String entityName,
					      String publicId,
					      String systemId)
	throws MalformedURLException, IOException {

	Vector resolutions = new Vector();

	for (int catPos = 0; catPos < catalogs.size(); catPos++) {
	    Resolver c = null;

	    try {
		c = (Resolver) catalogs.elementAt(catPos);
	    } catch (ClassCastException e) {
		String catfile = (String) catalogs.elementAt(catPos);
		c = (Resolver) newCatalog();

		try {
		    c.parseCatalog(catfile);
		} catch (MalformedURLException mue) {
		    catalogManager.debug.message(1, "Malformed Catalog URL", catfile);
		} catch (FileNotFoundException fnfe) {
		    catalogManager.debug.message(1, "Failed to load catalog, file not found",
			  catfile);
		} catch (IOException ioe) {
		    catalogManager.debug.message(1, "Failed to load catalog, I/O error", catfile);
		}

		catalogs.setElementAt(c, catPos);
	    }

	    String resolved = null;

	    // Ok, now what are we supposed to call here?
	    if (entityType == DOCTYPE) {
		resolved = c.resolveDoctype(entityName,
					    publicId,
					    systemId);
		if (resolved != null) {
		    // Only find one DOCTYPE resolution
		    resolutions.addElement(resolved);
		    return resolutions;
		}
	    } else if (entityType == DOCUMENT) {
		resolved = c.resolveDocument();
		if (resolved != null) {
		    // Only find one DOCUMENT resolution
		    resolutions.addElement(resolved);
		    return resolutions;
		}
	    } else if (entityType == ENTITY) {
		resolved = c.resolveEntity(entityName,
					   publicId,
					   systemId);
		if (resolved != null) {
		    // Only find one ENTITY resolution
		    resolutions.addElement(resolved);
		    return resolutions;
		}
	    } else if (entityType == NOTATION) {
		resolved = c.resolveNotation(entityName,
					     publicId,
					     systemId);
		if (resolved != null) {
		    // Only find one NOTATION resolution
		    resolutions.addElement(resolved);
		    return resolutions;
		}
	    } else if (entityType == PUBLIC) {
		resolved = c.resolvePublic(publicId, systemId);
		if (resolved != null) {
		    // Only find one PUBLIC resolution
		    resolutions.addElement(resolved);
		    return resolutions;
		}
	    } else if (entityType == SYSTEM) {
		Vector localResolutions = c.resolveAllSystem(systemId);
		resolutions = appendVector(resolutions, localResolutions);
		break;
	    } else if (entityType == SYSTEMREVERSE) {
		Vector localResolutions = c.resolveAllSystemReverse(systemId);
		resolutions = appendVector(resolutions, localResolutions);
	    }
	}

	if (resolutions != null) {
	    return resolutions;
	} else {
	    return null;
	}
    }

Search the subordinate catalogs, in order, looking for all
match.

This method searches the Catalog and returns all of the system
identifiers specified for the given entity type with the given
name, public, and system identifiers. In some contexts, these
may be null.

@param entityType The CatalogEntry type for which this query is
being conducted. This is necessary in order to do the approprate
query on a subordinate catalog.
@param entityName The name of the entity being searched for, if
appropriate.
@param publicId The public identifier of the entity in question
(as provided in the source document).
@param systemId The nominal system identifier for the entity
in question (as provided in the source document).

@throws MalformedURLException The formal system identifier of a
delegated catalog cannot be turned into a valid URL.
@throws IOException Error reading delegated catalog file.

@return The system identifier to use.
Note that the nominal system identifier is not returned if a
match is not found in the catalog, instead null is returned
to indicate that no match was found.

Search the subordinate catalogs in order looking for all match .


public void readCatalog(Catalog catalog, String fileUrl)
    throws MalformedURLException, IOException,
	   CatalogException {

    URL url = null;

    try {
      url = new URL(fileUrl);
    } catch (MalformedURLException e) {
      url = new URL("file:///" + fileUrl);
    }

    debug = catalog.getCatalogManager().debug;

    try {
      URLConnection urlCon = url.openConnection();
      readCatalog(catalog, urlCon.getInputStream());
    } catch (FileNotFoundException e) {
      catalog.getCatalogManager().debug.message(1, "Failed to load catalog, file not found",
		    url.toString());
    }
  }

Parse an XML Catalog file.

@param catalog The catalog to which this catalog file belongs
@param fileUrl The URL or filename of the catalog file to process

@throws MalformedURLException Improper fileUrl
@throws IOException Error reading catalog file


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

    // Create an instance of the parser
    if (parserFactory == null && parserClass == null) {
      debug.message(1, "Cannot read SAX catalog without a parser");
      throw new CatalogException(CatalogException.UNPARSEABLE);
    }

    debug = catalog.getCatalogManager().debug;
    EntityResolver bResolver = catalog.getCatalogManager().getBootstrapResolver();

    this.catalog = catalog;

    try {
      if (parserFactory != null) {
	SAXParser parser = parserFactory.newSAXParser();
	SAXParserHandler spHandler = new SAXParserHandler();
	spHandler.setContentHandler(this);
	if (bResolver != null) {
	  spHandler.setEntityResolver(bResolver);
	}
	parser.parse(new InputSource(is), spHandler);
      } else {
	Parser parser = (Parser) Class.forName(parserClass).newInstance();
	parser.setDocumentHandler(this);
	if (bResolver != null) {
	  parser.setEntityResolver(bResolver);
	}
	parser.parse(new InputSource(is));
      }
    } catch (ClassNotFoundException cnfe) {
      throw new CatalogException(CatalogException.UNPARSEABLE);
    } catch (IllegalAccessException iae) {
      throw new CatalogException(CatalogException.UNPARSEABLE);
    } catch (InstantiationException ie) {
      throw new CatalogException(CatalogException.UNPARSEABLE);
    } catch (ParserConfigurationException pce) {
      throw new CatalogException(CatalogException.UNKNOWN_FORMAT);
    } catch (SAXException se) {
      Exception e = se.getException();
      // FIXME: there must be a better way
      UnknownHostException uhe = new UnknownHostException();
      FileNotFoundException fnfe = new FileNotFoundException();
      if (e != null) {
	if (e.getClass() == uhe.getClass()) {
	  throw new CatalogException(CatalogException.PARSE_FAILED,
				     e.toString());
	} else if (e.getClass() == fnfe.getClass()) {
	  throw new CatalogException(CatalogException.PARSE_FAILED,
				     e.toString());
	}
      }
      throw new CatalogException(se);
    }
  }

Parse an XML Catalog stream.

@param catalog The catalog to which this catalog file belongs
@param is The input stream from which the catalog will be read

@throws MalformedURLException Improper fileUrl
@throws IOException Error reading catalog file
@throws CatalogException A Catalog exception


public void connect() throws IOException
   {
      if (connected)
         return;

      if (!file.exists())
      {
         throw new FileNotFoundException(file.getPath());
      }
      connected = true;
   }

public void connect ( ) throws IOException { if ( connected ) return ; if ( ! file . exists ( ) ) { throw new FileNotFoundException ( file . getPath ( ) ) ; } connected = true ; }

Checks if the underlying file for this connection exists.

@throws FileNotFoundException

Checks if the underlying file for this connection exists .


public OutputStream getOutputStream() throws IOException
   {
      connect();

      SecurityManager sm = System.getSecurityManager();
      if (sm != null)
      {
         // Check for write access
         FilePermission p = new FilePermission(file.getPath(), "write");
         sm.checkPermission(p);
      }
      return new FileOutputStream(file);
   }

public
OutputStream
getOutputStream
(
)
throws
IOException
{
connect
(
)
;
SecurityManager
sm
=
System
.
getSecurityManager
(
)
;
if
(
sm
!=
)
{
// Check for write access
FilePermission
p
=
new
FilePermission
(
file
.
getPath
(
)
,
"write"
)
;
sm
.
checkPermission
(
p
)
;
}
return
new
FileOutputStream
(
file
)
;
}


boolean casNext(Node<K,V> cmp, Node<K,V> val) {
            return nextUpdater.compareAndSet(this, cmp, val);
        }

boolean casNext ( Node < K , V > cmp , Node < K , V > val ) { return nextUpdater . compareAndSet ( this , cmp , val ) ; }


void helpDelete(Node<K,V> b, Node<K,V> f) {
            /*
             * Rechecking links and then doing only one of the
             * help-out stages per call tends to minimize CAS
             * interference among helping threads.
             */
            if (f == next && this == b.next) {
                if (f == null || f.value != f) // not already marked
                    appendMarker(f);
                else
                    b.casNext(this, f.next);
            }
        }

Helps out a deletion by appending marker or unlinking from
predecessor. This is called during traversals when value
field seen to be null.
@param b predecessor
@param f successor

Helps out a deletion by appending marker or unlinking from predecessor . This is called during traversals when value field seen to be null .


V getValidValue() {
            Object v = value;
            if (v == this || v == BASE_HEADER)
                return null;
            return (V)v;
        }

V getValidValue ( ) { Object v = value ; if ( v == this || v == BASE_HEADER ) return null ; return ( V ) v ; }

Return value if this node contains a valid key-value pair,
else null.
@return this node's value if it isn't a marker or header or
is deleted, else null.

Return value if this node contains a valid key - value pair else null .


SnapshotEntry<K,V> createSnapshot() {
            V v = getValidValue();
            if (v == null)
                return null;
            return new SnapshotEntry(key, v);
        }

SnapshotEntry < K , V > createSnapshot ( ) { V v = getValidValue ( ) ; if ( v == null ) return null ; return new SnapshotEntry ( key , v ) ; }

Create and return a new SnapshotEntry holding current
mapping if this node holds a valid value, else null
@return new entry or null

Create and return a new SnapshotEntry holding current mapping if this node holds a valid value else null


final boolean casRight(Index<K,V> cmp, Index<K,V> val) {
            return rightUpdater.compareAndSet(this, cmp, val);
        }

final boolean casRight ( Index < K , V > cmp , Index < K , V > val ) { return rightUpdater . compareAndSet ( this , cmp , val ) ; }


private Logger createLog()
   {
      Class<?> clazz = getClass();
      Logger logger = loggers.get(clazz);
      if (logger == null)
      {
         logger = Logger.getLogger(clazz);
         loggers.put(clazz, logger);
      }
      return logger;
   }

private Logger createLog ( ) { Class < ? > clazz = getClass ( ) ; Logger logger = loggers . get ( clazz ) ; if ( logger == null ) { logger = Logger . getLogger ( clazz ) ; loggers . put ( clazz , logger ) ; } return logger ; }


public static void list(JBossStringBuilder buffer, Collection objects)
   {
      if (objects == null)
         return;

      buffer.append('[');
      if (objects.isEmpty() == false)
      {
         for (Iterator i = objects.iterator(); i.hasNext();)
         {
            Object object = i.next();
            if (object instanceof JBossObject)
               ((JBossObject) object).toShortString(buffer);
            else
               buffer.append(object.toString());
            if (i.hasNext())
               buffer.append(", ");
         }
      }
      buffer.append(']');
   }

public
static
void
list
(
JBossStringBuilder
buffer
,
Collection
objects
)
{
if
(
objects
==
)
return
;
buffer
.
append
(
'
'
)
;
if
(
objects
.
isEmpty
(
)
==
false
)
{
for
(
Iterator
i
=
objects
.
iterator
(
)
;
i
.
hasNext
(
)
;
)
{
Object
object
=
i
.
next
(
)
;
if
(
object
instanceof
JBossObject
)
(
(
JBossObject
)
object
)
.
toShortString
(
buffer
)
;
else
buffer
.
append
(
object
.
toString
(
)
)
;
if
(
i
.
hasNext
(
)
)
buffer
.
append
(
", "
)
;
}
}
buffer
.
append
(
'
'
)
;
}

List the set of JBossObjects

@param buffer the buffer
@param objects the collection of objects


public String getClassShortName()
   {
      String longName = getClass().getName();
      int dot = longName.lastIndexOf('.');
      if (dot != -1)
         return longName.substring(dot + 1);
      return longName;
   }

public String getClassShortName ( ) { String longName = getClass ( ) . getName ( ) ; int dot = longName . lastIndexOf ( ' ' ) ; if ( dot != - 1 ) return longName . substring ( dot + 1 ) ; return longName ; }

Get the class short name

@return the short name of the class


protected String toStringImplementation()
   {
      JBossStringBuilder buffer = new JBossStringBuilder();
      buffer.append(getClassShortName()).append('@');
      buffer.append(Integer.toHexString(System.identityHashCode(this)));
      buffer.append('{');
      toString(buffer);
      buffer.append('}');
      return buffer.toString();
   }

protected String toStringImplementation ( ) { JBossStringBuilder buffer = new JBossStringBuilder ( ) ; buffer . append ( getClassShortName ( ) ) . append ( ' ' ) ; buffer . append ( Integer . toHexString ( System . identityHashCode ( this ) ) ) ; buffer . append ( ' ' ) ; toString ( buffer ) ; buffer . append ( ' ' ) ; return buffer . toString ( ) ; }

Implementation of String

@return the string


public static Iterator names()
   {
      SecurityManager sm = System.getSecurityManager();
      if (sm != null)
         sm.checkPropertiesAccess();
      return props.names();
   }

public static Iterator names ( ) { SecurityManager sm = System . getSecurityManager ( ) ; if ( sm != null ) sm . checkPropertiesAccess ( ) ; return props . names ( ) ; }

Return an iterator over all contained property names.

@return     Property name iterator.

Return an iterator over all contained property names .


public static PropertyGroup getPropertyGroup(final String basename)
   {
      SecurityManager sm = System.getSecurityManager();
      if (sm != null)
         sm.checkPropertiesAccess();
      return props.getPropertyGroup(basename);
   }

public static PropertyGroup getPropertyGroup ( final String basename ) { SecurityManager sm = System . getSecurityManager ( ) ; if ( sm != null ) sm . checkPropertiesAccess ( ) ; return props . getPropertyGroup ( basename ) ; }

Get a property group for the given property base.

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

Get a property group for the given property base .


public static Constructor getCompatibleConstructor(final Class type,
                                                      final Class valueType)
   {
      // first try and find a constructor with the exact argument type
      try {
         return type.getConstructor(new Class[] { valueType });
      }
      catch (Exception ignore) {
         // if the above failed, then try and find a constructor with
         // an compatible argument type

         // get an array of compatible types
         Class[] types = type.getClasses();

         for (int i=0; i<types.length; i++) {
            try {
               return type.getConstructor(new Class[] { types[i] });
            }
            catch (Exception ignore2) {}
         }
      }

      // if we get this far, then we can't find a compatible constructor
      return null;
   }

Get a compatible constructor for the given value type

@param type       Class to look for constructor in
@param valueType  Argument type for constructor
@return           Constructor or null


public static Object copy(final Serializable obj)
      throws IOException, ClassNotFoundException
   {
      ObjectOutputStream out = null;
      ObjectInputStream in = null;
      Object copy = null;

      try {
         // write the object
         ByteArrayOutputStream baos = new ByteArrayOutputStream();
         out = new ObjectOutputStream(baos);
         out.writeObject(obj);
         out.flush();

         // read in the copy
         byte data[] = baos.toByteArray();
         ByteArrayInputStream bais = new ByteArrayInputStream(data);
         in = new ObjectInputStream(bais);
         copy = in.readObject();
      }
      finally {
         Streams.close(out);
         Streams.close(in);
      }

      return copy;
   }

public
static
Object
copy
(
final
Serializable
obj
)
throws
IOException
,
ClassNotFoundException
{
ObjectOutputStream
out
=
;
ObjectInputStream
in
=
;
Object
copy
=
;
try
{
// write the object
ByteArrayOutputStream
baos
=
new
ByteArrayOutputStream
(
)
;
out
=
new
ObjectOutputStream
(
baos
)
;
out
.
writeObject
(
obj
)
;
out
.
flush
(
)
;
// read in the copy
byte
data
[
]
=
baos
.
toByteArray
(
)
;
ByteArrayInputStream
bais
=
new
ByteArrayInputStream
(
data
)
;
in
=
new
ObjectInputStream
(
bais
)
;
copy
=
in
.
readObject
(
)
;
}
finally
{
Streams
.
close
(
out
)
;
Streams
.
close
(
in
)
;
}
return
copy
;
}

Copy an serializable object deeply.

@param obj  Object to copy.
@return     Copied object.

@throws IOException
@throws ClassNotFoundException


public static <T> T deref(final Object obj, Class<T> expected)
   {
      Object result = deref(obj);
      if (result == null)
         return null;
      return expected.cast(result);
   }

public static < T > T deref ( final Object obj , Class < T > expected ) { Object result = deref ( obj ) ; if ( result == null ) return null ; return expected . cast ( result ) ; }

Dereference an object

@param <T> the expected type
@param obj the object or reference
@param expected the expected type
@return the object or null


private void init()
   {
      unboundListeners = Collections.synchronizedList(new ArrayList());
      boundListeners = Collections.synchronizedMap(new HashMap());
      jndiMap = new HashMap();

      PrivilegedAction action = new PrivilegedAction()
      {
         public Object run()
         {
            Object value = System.getProperty(Context.PROVIDER_URL);
            if (value == null) value = NULL_VALUE;
            jndiMap.put(Context.PROVIDER_URL, value);

            value = System.getProperty(Context.INITIAL_CONTEXT_FACTORY);
            if (value == null) value = NULL_VALUE;
            jndiMap.put(Context.INITIAL_CONTEXT_FACTORY, value);

            value = System.getProperty(Context.OBJECT_FACTORIES);
            if (value == null) value = NULL_VALUE;
            jndiMap.put(Context.OBJECT_FACTORIES, value);

            value = System.getProperty(Context.URL_PKG_PREFIXES);
            if (value == null) value = NULL_VALUE;
            jndiMap.put(Context.URL_PKG_PREFIXES, value);

            value = System.getProperty(Context.STATE_FACTORIES);
            if (value == null) value = NULL_VALUE;
            jndiMap.put(Context.STATE_FACTORIES, value);

            value = System.getProperty(Context.DNS_URL);
            if (value == null) value = NULL_VALUE;
            jndiMap.put(Context.DNS_URL, value);

            value = System.getProperty(LdapContext.CONTROL_FACTORIES);
            if (value == null) value = NULL_VALUE;
            jndiMap.put(LdapContext.CONTROL_FACTORIES, value);
            return null;
         }
      };
      AccessController.doPrivileged(action);
   }

private void init ( ) { unboundListeners = Collections . synchronizedList ( new ArrayList ( ) ) ; boundListeners = Collections . synchronizedMap ( new HashMap ( ) ) ; jndiMap = new HashMap ( ) ; PrivilegedAction action = new PrivilegedAction ( ) { public Object run ( ) { Object value = System . getProperty ( Context . PROVIDER_URL ) ; if ( value == null ) value = NULL_VALUE ; jndiMap . put ( Context . PROVIDER_URL , value ) ; value = System . getProperty ( Context . INITIAL_CONTEXT_FACTORY ) ; if ( value == null ) value = NULL_VALUE ; jndiMap . put ( Context . INITIAL_CONTEXT_FACTORY , value ) ; value = System . getProperty ( Context . OBJECT_FACTORIES ) ; if ( value == null ) value = NULL_VALUE ; jndiMap . put ( Context . OBJECT_FACTORIES , value ) ; value = System . getProperty ( Context . URL_PKG_PREFIXES ) ; if ( value == null ) value = NULL_VALUE ; jndiMap . put ( Context . URL_PKG_PREFIXES , value ) ; value = System . getProperty ( Context . STATE_FACTORIES ) ; if ( value == null ) value = NULL_VALUE ; jndiMap . put ( Context . STATE_FACTORIES , value ) ; value = System . getProperty ( Context . DNS_URL ) ; if ( value == null ) value = NULL_VALUE ; jndiMap . put ( Context . DNS_URL , value ) ; value = System . getProperty ( LdapContext . CONTROL_FACTORIES ) ; if ( value == null ) value = NULL_VALUE ; jndiMap . put ( LdapContext . CONTROL_FACTORIES , value ) ; return null ; } } ; AccessController . doPrivileged ( action ) ; }

Initialized listener lists and the JNDI properties cache map


private void updateJndiCache(String name, String value)
   {
      if( name == null )
         return;

      boolean isJndiProperty = name.equals(Context.PROVIDER_URL)
         || name.equals(Context.INITIAL_CONTEXT_FACTORY)
         || name.equals(Context.OBJECT_FACTORIES)
         || name.equals(Context.URL_PKG_PREFIXES)
         || name.equals(Context.STATE_FACTORIES)
         || name.equals(Context.DNS_URL)
         || name.equals(LdapContext.CONTROL_FACTORIES)
      ;
      if( isJndiProperty == true )
         jndiMap.put(name, value);
   }

private void updateJndiCache ( String name , String value ) { if ( name == null ) return ; boolean isJndiProperty = name . equals ( Context . PROVIDER_URL ) || name . equals ( Context . INITIAL_CONTEXT_FACTORY ) || name . equals ( Context . OBJECT_FACTORIES ) || name . equals ( Context . URL_PKG_PREFIXES ) || name . equals ( Context . STATE_FACTORIES ) || name . equals ( Context . DNS_URL ) || name . equals ( LdapContext . CONTROL_FACTORIES ) ; if ( isJndiProperty == true ) jndiMap . put ( name , value ) ; }

Called by setProperty to update the jndiMap cache values.
@param name the property name
@param value the property value

Called by setProperty to update the jndiMap cache values .


public Set keySet(final boolean includeDefaults)
   {
      if (includeDefaults)
      {
         Set set = new HashSet();
         set.addAll(defaults.keySet());
         set.addAll(super.keySet());
         return Collections.synchronizedSet(set);
      }

      return super.keySet();
   }

public Set keySet ( final boolean includeDefaults ) { if ( includeDefaults ) { Set set = new HashSet ( ) ; set . addAll ( defaults . keySet ( ) ) ; set . addAll ( super . keySet ( ) ) ; return Collections . synchronizedSet ( set ) ; } return super . keySet ( ) ; }

Returns a set of keys for all entries in this group and optionally
all of the keys in the defaults map.
@param includeDefaults
@return the key set

Returns a set of keys for all entries in this group and optionally all of the keys in the defaults map .


public Set entrySet(final boolean includeDefaults)
   {
      if (includeDefaults)
      {
         Set set = new HashSet();
         set.addAll(defaults.entrySet());
         set.addAll(super.entrySet());
         return Collections.synchronizedSet(set);
      }

      return super.entrySet();
   }

public Set entrySet ( final boolean includeDefaults ) { if ( includeDefaults ) { Set set = new HashSet ( ) ; set . addAll ( defaults . entrySet ( ) ) ; set . addAll ( super . entrySet ( ) ) ; return Collections . synchronizedSet ( set ) ; } return super . entrySet ( ) ; }

Returns a set of entrys for all entries in this group and optionally
all of the entrys in the defaults map.
@param includeDefaults
@return  the entry set

Returns a set of entrys for all entries in this group and optionally all of the entrys in the defaults map .


public boolean removePropertyListener(PropertyListener listener)
   {
      if (listener == null)
         throw new NullArgumentException("listener");

      boolean removed = false;
      if (listener instanceof BoundPropertyListener)
      {
         removed = removePropertyListener((BoundPropertyListener) listener);
      }
      else
      {
         removed = unboundListeners.remove(listener);
      }

      return removed;
   }

public boolean removePropertyListener ( PropertyListener listener ) { if ( listener == null ) throw new NullArgumentException ( "listener" ) ; boolean removed = false ; if ( listener instanceof BoundPropertyListener ) { removed = removePropertyListener ( ( BoundPropertyListener ) listener ) ; } else { removed = unboundListeners . remove ( listener ) ; } return removed ; }

Remove a property listener.

@param listener   Property listener to remove.
@return           True if listener was removed.


private void firePropertyAdded(List list, PropertyEvent event)
   {
      if (list == null) return;

      int size = list.size();
      for (int i = 0; i < size; i++)
      {
         PropertyListener listener = (PropertyListener) list.get(i);
         listener.propertyAdded(event);
      }
   }

private void firePropertyAdded ( List list , PropertyEvent event ) { if ( list == null ) return ; int size = list . size ( ) ; for ( int i = 0 ; i < size ; i ++ ) { PropertyListener listener = ( PropertyListener ) list . get ( i ) ; listener . propertyAdded ( event ) ; } }

Fire a property added event to the given list of listeners.

@param list    Listener list.
@param event   Property event.

Fire a property added event to the given list of listeners .


private void firePropertyRemoved(List list, PropertyEvent event)
   {
      if (list == null) return;

      int size = list.size();
      for (int i = 0; i < size; i++)
      {
         PropertyListener listener = (PropertyListener) list.get(i);
         listener.propertyRemoved(event);
      }
   }

private void firePropertyRemoved ( List list , PropertyEvent event ) { if ( list == null ) return ; int size = list . size ( ) ; for ( int i = 0 ; i < size ; i ++ ) { PropertyListener listener = ( PropertyListener ) list . get ( i ) ; listener . propertyRemoved ( event ) ; } }

Fire a property removed event to the given list of listeners.

@param list    Listener list.
@param event   Property event.

Fire a property removed event to the given list of listeners .


private void firePropertyChanged(List list, PropertyEvent event)
   {
      if (list == null) return;

      int size = list.size();
      for (int i = 0; i < size; i++)
      {
         PropertyListener listener = (PropertyListener) list.get(i);
         listener.propertyChanged(event);
      }
   }

private void firePropertyChanged ( List list , PropertyEvent event ) { if ( list == null ) return ; int size = list . size ( ) ; for ( int i = 0 ; i < size ; i ++ ) { PropertyListener listener = ( PropertyListener ) list . get ( i ) ; listener . propertyChanged ( event ) ; } }

Fire a property changed event to the given list of listeners.

@param list    Listener list.
@param event   Property event.

Fire a property changed event to the given list of listeners .