You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@openjpa.apache.org by pc...@apache.org on 2006/06/28 21:34:40 UTC
svn commit: r417856 [17/22] - in /incubator/openjpa/trunk/openjpa-lib: java/
main/ main/java/ main/java/org/apache/openjpa/lib/ant/
main/java/org/apache/openjpa/lib/conf/ main/java/org/apache/openjpa/lib/jdbc/
main/java/org/apache/openjpa/lib/log/ main...
Modified: incubator/openjpa/trunk/openjpa-lib/main/java/org/apache/openjpa/lib/util/Services.java
URL: http://svn.apache.org/viewvc/incubator/openjpa/trunk/openjpa-lib/main/java/org/apache/openjpa/lib/util/Services.java?rev=417856&r1=415364&r2=417856&view=diff
==============================================================================
--- incubator/openjpa/trunk/openjpa-lib/main/java/org/apache/openjpa/lib/util/Services.java (original)
+++ incubator/openjpa/trunk/openjpa-lib/main/java/org/apache/openjpa/lib/util/Services.java Wed Jun 28 12:34:33 2006
@@ -15,217 +15,194 @@
*/
package org.apache.openjpa.lib.util;
-
import java.io.*;
+
import java.net.*;
+
import java.util.*;
-/**
- * <p>Utility classes to locate services, as defined in the
- * <a href="http://java.sun.com/j2se/1.3/docs/guide/jar/jar.html
- * #Service%20Provider">Jar File Specification</a>.
- * Most of the methods in this class can also
- * be found in the <em>sun.misc.Service</em> class, but since it is
- * undocumented, we cannot rely on its API.</p>
+/**
+ * <p>Utility classes to locate services, as defined in the <a
+ * href="http://java.sun.com/j2se/1.3/docs/guide/jar/jar.html
+ * #Service%20Provider">Jar File Specification</a>. Most of the methods in this
+ * class can also be found in the <em>sun.misc.Service</em> class, but since
+ * it is undocumented, we cannot rely on its API.</p>
*
- * <p>Service location for a specified interface is done by searching
- * for the resource <em>/META-INF/services/</em><i>service.class.name</i>,
- * and loading the resource.</p>
+ * <p>Service location for a specified interface is done by searching for the
+ * resource <em>/META-INF/services/</em><i>service.class.name</i>, and
+ * loading the resource.</p>
*
- * <p>Methods in this class that do not declare exceptions will never
- * throw Runtime exceptions: exceptions are silently swallowed
- * and empty array values are returned.</p>
+ * <p>Methods in this class that do not declare exceptions will never throw
+ * Runtime exceptions: exceptions are silently swallowed and empty array values
+ * are returned.</p>
*
- * @author Marc Prud'hommeaux
- * @nojavadoc
+ * @author Marc Prud'hommeaux
+ * @nojavadoc
*/
-public class Services
-{
- private static final String PREFIX = "META-INF/services/";
-
-
- /**
- * Return an array of Strings of class names of all known
- * service implementors of the specified interface or class.
- */
- public static String[] getImplementors (Class serviceClass)
- {
- return getImplementors (serviceClass, null);
- }
-
-
- /**
- * Return an array of Strings of class names of all known
- * service implementors of the specified interface or class.
- */
- public static String[] getImplementors (Class serviceClass,
- ClassLoader loader)
- {
- return getImplementors (serviceClass.getName (), loader);
- }
-
-
- /**
- * Return an array of Strings of class names of all known
- * service implementors of the specified class name (as resolved
- * by the current thread's context class loader).
- */
- public static String[] getImplementors (String serviceName)
- {
- return getImplementors (serviceName, null);
- }
-
-
- /**
- * Return an array of Strings of class names of all known
- * service implementors of the specified class name, as resolved
- * by the specified {@link ClassLoader}.
- */
- public static String[] getImplementors (String serviceName,
- ClassLoader loader)
- {
- if (loader == null)
- loader = Thread.currentThread ().getContextClassLoader ();
-
- try
- {
- Set resourceList = new TreeSet ();
- Enumeration resources = loader.getResources (PREFIX + serviceName);
- while (resources.hasMoreElements ())
- addResources ((URL)resources.nextElement (), resourceList);
-
- return (String[]) resourceList.toArray
- (new String[resourceList.size ()]);
- }
- catch (Exception e)
- {
- // silently swallow all exceptions.
- return new String[0];
- }
- }
-
-
- /**
- * Parse the URL resource and add the listed class names
- * to the specified Set. Class names are separated by lines.
- * Lines starting with '#' are ignored.
- */
- private static void addResources (URL url, Set set)
- throws IOException
- {
- InputStream in = url.openConnection ().getInputStream ();
- BufferedReader reader = new BufferedReader (new InputStreamReader (in));
-
- try
- {
- String line;
- while ((line = reader.readLine ()) != null)
- {
- if (line.trim ().startsWith ("#") ||
- line.trim ().length () == 0)
- continue;
-
- StringTokenizer tok = new StringTokenizer (line, "# \t");
- if (tok.hasMoreTokens ())
- {
- String next = tok.nextToken ();
- if (next != null)
- {
- next = next.trim ();
- if (next.length () > 0 && !next.startsWith ("#"))
- set.add (next);
- }
- }
- }
- }
- finally
- {
- reader.close ();
- }
- }
-
-
- public static Class[] getImplementorClasses (Class serviceClass)
- {
- return getImplementorClasses (serviceClass.getName (), null);
- }
-
-
- public static Class[] getImplementorClasses (Class serviceClass,
- ClassLoader loader)
- {
- return getImplementorClasses (serviceClass.getName (), loader);
- }
-
-
- /**
- * Return an array of Class objects of all known
- * service implementors of the specified class name (as resolved
- * by the current thread's context class loader).
- */
- public static Class[] getImplementorClasses (String serviceName)
- {
- return getImplementorClasses (serviceName, null);
- }
-
-
- public static Class[] getImplementorClasses (String serviceName,
- ClassLoader loader)
- {
- try
- {
- return getImplementorClasses (serviceName, loader, true);
- }
- catch (Exception cnfe)
- {
- // this will never happen with skipmissing
- return new Class[0];
- }
- }
-
-
- /**
- * Return an array of Class objects of all known
- * service implementors of the specified class name, as resolved
- * by the specified {@link ClassLoader}.
- *
- * @param skipMissing if true, then ignore classes that cannot
- * be loaded by the classloader; otherwise,
- * resolution failures will throw a
- * {@link ClassNotFoundException}.
- */
- public static Class[] getImplementorClasses (String serviceName,
- ClassLoader loader, boolean skipMissing)
- throws ClassNotFoundException
- {
- if (loader == null)
- loader = Thread.currentThread ().getContextClassLoader ();
-
- String[] names = getImplementors (serviceName, loader);
- if (names == null)
- return new Class[0];
-
- List classes = new ArrayList (names.length);
- for (int i = 0; i < names.length; i++)
- {
- try
- {
- classes.add (Class.forName (names[i], false, loader));
- }
- catch (ClassNotFoundException e)
- {
- if (!skipMissing)
- throw e;
- }
- catch (UnsupportedClassVersionError ecve)
- {
- // #skim - prob should fail regardless
- if (!skipMissing)
- throw ecve;
- }
- }
- return (Class[]) classes.toArray (new Class[classes.size ()]);
- }
-}
+public class Services {
+ private static final String PREFIX = "META-INF/services/";
+
+ /**
+ * Return an array of Strings of class names of all known service
+ * implementors of the specified interface or class.
+ */
+ public static String[] getImplementors(Class serviceClass) {
+ return getImplementors(serviceClass, null);
+ }
+
+ /**
+ * Return an array of Strings of class names of all known service
+ * implementors of the specified interface or class.
+ */
+ public static String[] getImplementors(Class serviceClass,
+ ClassLoader loader) {
+ return getImplementors(serviceClass.getName(), loader);
+ }
+
+ /**
+ * Return an array of Strings of class names of all known service
+ * implementors of the specified class name (as resolved by the current
+ * thread's context class loader).
+ */
+ public static String[] getImplementors(String serviceName) {
+ return getImplementors(serviceName, null);
+ }
+
+ /**
+ * Return an array of Strings of class names of all known service
+ * implementors of the specified class name, as resolved by the specified
+ * {@link ClassLoader}.
+ */
+ public static String[] getImplementors(String serviceName,
+ ClassLoader loader) {
+ if (loader == null) {
+ loader = Thread.currentThread().getContextClassLoader();
+ }
+
+ try {
+ Set resourceList = new TreeSet();
+ Enumeration resources = loader.getResources(PREFIX + serviceName);
+
+ while (resources.hasMoreElements())
+ addResources((URL) resources.nextElement(), resourceList);
+
+ return (String[]) resourceList.toArray(new String[resourceList.size()]);
+ } catch (Exception e) {
+ // silently swallow all exceptions.
+ return new String[0];
+ }
+ }
+
+ /**
+ * Parse the URL resource and add the listed class names to the specified
+ * Set. Class names are separated by lines. Lines starting with '#' are
+ * ignored.
+ */
+ private static void addResources(URL url, Set set)
+ throws IOException {
+ InputStream in = url.openConnection().getInputStream();
+
+ try {
+ BufferedReader reader = new BufferedReader(new InputStreamReader(in));
+ String line;
+
+ while ((line = reader.readLine()) != null) {
+ if (line.trim().startsWith("#") || (line.trim().length() == 0)) {
+ continue;
+ }
+
+ StringTokenizer tok = new StringTokenizer(line, "# \t");
+
+ if (tok.hasMoreTokens()) {
+ String next = tok.nextToken();
+
+ if (next != null) {
+ next = next.trim();
+
+ if ((next.length() > 0) && !next.startsWith("#")) {
+ set.add(next);
+ }
+ }
+ }
+ }
+ } finally {
+ try {
+ in.close();
+ } catch (IOException ioe) {
+ // silently consume exception
+ }
+ }
+ }
+
+ public static Class[] getImplementorClasses(Class serviceClass) {
+ return getImplementorClasses(serviceClass.getName(), null);
+ }
+
+ public static Class[] getImplementorClasses(Class serviceClass,
+ ClassLoader loader) {
+ return getImplementorClasses(serviceClass.getName(), loader);
+ }
+
+ /**
+ * Return an array of Class objects of all known service implementors of the
+ * specified class name (as resolved by the current thread's context class
+ * loader).
+ */
+ public static Class[] getImplementorClasses(String serviceName) {
+ return getImplementorClasses(serviceName, null);
+ }
+
+ public static Class[] getImplementorClasses(String serviceName,
+ ClassLoader loader) {
+ try {
+ return getImplementorClasses(serviceName, loader, true);
+ } catch (Exception cnfe) {
+ // this will never happen with skipmissing
+ return new Class[0];
+ }
+ }
+
+ /**
+ * Return an array of Class objects of all known service implementors of the
+ * specified class name, as resolved by the specified {@link ClassLoader}.
+ *
+ * @param skipMissing if true, then ignore classes that cannot be loaded by
+ * the classloader; otherwise, resolution failures will throw a
+ * {@link ClassNotFoundException}.
+ */
+ public static Class[] getImplementorClasses(String serviceName,
+ ClassLoader loader, boolean skipMissing) throws ClassNotFoundException {
+ if (loader == null) {
+ loader = Thread.currentThread().getContextClassLoader();
+ }
+
+ String[] names = getImplementors(serviceName, loader);
+
+ if (names == null) {
+ return new Class[0];
+ }
+
+ List classes = new ArrayList(names.length);
+
+ for (int i = 0; i < names.length; i++) {
+ try {
+ classes.add(Class.forName(names[i], false, loader));
+ } catch (ClassNotFoundException e) {
+ if (!skipMissing) {
+ throw e;
+ }
+ } catch (UnsupportedClassVersionError ecve) {
+ if (!skipMissing) {
+ throw ecve;
+ }
+ } catch (LinkageError le) {
+ if (!skipMissing) {
+ throw le;
+ }
+ }
+ }
+ return (Class[]) classes.toArray(new Class[classes.size()]);
+ }
+}
Modified: incubator/openjpa/trunk/openjpa-lib/main/java/org/apache/openjpa/lib/util/SimpleRegex.java
URL: http://svn.apache.org/viewvc/incubator/openjpa/trunk/openjpa-lib/main/java/org/apache/openjpa/lib/util/SimpleRegex.java?rev=417856&r1=415364&r2=417856&view=diff
==============================================================================
--- incubator/openjpa/trunk/openjpa-lib/main/java/org/apache/openjpa/lib/util/SimpleRegex.java (original)
+++ incubator/openjpa/trunk/openjpa-lib/main/java/org/apache/openjpa/lib/util/SimpleRegex.java Wed Jun 28 12:34:33 2006
@@ -18,133 +18,136 @@
/**
* <p>Allows for simple regex style testing of strings. The wildcard '.'
- * is used to represent any single character, while '.*' is used to represent
- * any series of 0 or more characters.</p>
+ * is used to represent any single character, while '.*' is used to represent
+ * any series of 0 or more characters.</p>
*
- * <p>Examples:<br />
- * <code>
- * SimpleRegex re = new SimpleRegex ("the qu.ck .* dog", true);
- * boolean matches = re.matches ("The quick fox jumped over the lazy dog");
- * </code></p>
- * @nojavadoc
- */
-public class SimpleRegex
-{
- private final String expr;
- private final boolean caseInsensitive;
-
-
- public SimpleRegex (String expr, boolean caseInsensitive)
- {
- this.caseInsensitive = caseInsensitive;
-
- // If we're case insensitive, toLowerCase the expr. We'll toLowerCase
- // each target, too, in the matches call.
- if (caseInsensitive)
- this.expr = expr.toLowerCase ();
- else
- this.expr = expr;
- }
-
-
- public boolean matches (String target)
- {
- // If we're case insensitive, toLowerCase the target
- if (caseInsensitive)
- target = target.toLowerCase ();
-
- // By default, we are not position independent ("mobile"). We only
- // become position independent once we hit our first ".*".
- boolean mobile = false;
-
- // Find occurrences of ".*" in the expression.
- int exprPos = 0;
- int targetPos = 0;
- while (true)
- {
- // Find the next occurrence of ".*"
- int star = expr.indexOf (".*", exprPos);
-
- // If we're at a ".*" now, simply skip it and become position
- // independent
- if (star == exprPos)
- {
- mobile = true;
- exprPos += 2;
- continue;
- }
- // If there are no more ".*"s, then we're effectively no longer
- // position independent (assuming we even were before), since
- // we must match the end of the string
- else if (star == -1)
- {
- int len = expr.length () - exprPos;
-
- // If we're not mobile, then the remainder of the expr and
- // target must be the same length. If not, then it's not a
- // match. If we're mobile, then the length doesn't have to
- // be the same as long as the remainder of the expression
- // is equal to the end of the target
- if (!mobile && targetPos != target.length () - len)
- return false;
-
- // Match the end of the target to the remainder of the
- // expression
- int match = indexOf (target, target.length () - len, exprPos,
- len, true);
- if (match != -1)
- return true;
- return false;
- }
-
- // Match the fragment of the expression to the target
- int match = indexOf (target, targetPos, exprPos,
- star - exprPos, !mobile);
- if (match == -1)
- return false;
- targetPos = match + star - exprPos;
- exprPos = star + 2;
- mobile = true;
- }
- }
-
-
- /**
- * Match a section of target to a fragment of the expression.
- * If we're only to match the beginning of the target, beginOnly
- * will be true, otherwise we can match anymore in the target (starting
- * at the targetStart position). A "." in the expression matches any
- * character.
- */
- private int indexOf (String target, int targetStart,
- int exprStart, int exprLength, boolean beginOnly)
- {
- // Run through the target seeing if there is a match
- while (target.length () - targetStart >= exprLength)
- {
- // Assume success. If there isn't a match we'll break out
- boolean found = true;
- for (int i = 0; i < exprLength; i++)
- {
- // "." in the expr matches any character in the target
- if (expr.charAt (exprStart + i) != '.' &&
- expr.charAt (exprStart + i) !=
- target.charAt (targetStart + i))
- {
- found = false;
- break;
- }
- }
- if (found)
- return targetStart;
-
- // If we're position dependent (beginOnly == true), then don't
- // continue the search
- if (beginOnly)
- return -1;
-
- targetStart++;
- }
- return -1;
- }
+ * <p>Examples:<br />
+ * <code>
+ * SimpleRegex re = new SimpleRegex ("the qu.ck .* dog", true);
+ * boolean matches = re.matches ("The quick fox jumped over the lazy dog");
+ * </code></p>
+ * @nojavadoc */
+public class SimpleRegex {
+ private final String expr;
+ private final boolean caseInsensitive;
+
+ public SimpleRegex(String expr, boolean caseInsensitive) {
+ this.caseInsensitive = caseInsensitive;
+
+ // If we're case insensitive, toLowerCase the expr. We'll toLowerCase
+ // each target, too, in the matches call.
+ if (caseInsensitive) {
+ this.expr = expr.toLowerCase();
+ } else {
+ this.expr = expr;
+ }
+ }
+
+ public boolean matches(String target) {
+ // If we're case insensitive, toLowerCase the target
+ if (caseInsensitive) {
+ target = target.toLowerCase();
+ }
+
+ // By default, we are not position independent ("mobile"). We only
+ // become position independent once we hit our first ".*".
+ boolean mobile = false;
+
+ // Find occurrences of ".*" in the expression.
+ int exprPos = 0;
+ int targetPos = 0;
+
+ while (true) {
+ // Find the next occurrence of ".*"
+ int star = expr.indexOf(".*", exprPos);
+
+ // If we're at a ".*" now, simply skip it and become position
+ // independent
+ if (star == exprPos) {
+ mobile = true;
+ exprPos += 2;
+
+ continue;
+ }
+ // If there are no more ".*"s, then we're effectively no longer
+ // position independent (assuming we even were before), since
+ // we must match the end of the string
+ else if (star == -1) {
+ int len = expr.length() - exprPos;
+
+ // If we're not mobile, then the remainder of the expr and
+ // target must be the same length. If not, then it's not a
+ // match. If we're mobile, then the length doesn't have to
+ // be the same as long as the remainder of the expression
+ // is equal to the end of the target
+ if (!mobile && (targetPos != (target.length() - len))) {
+ return false;
+ }
+
+ // Match the end of the target to the remainder of the
+ // expression
+ int match = indexOf(target, target.length() - len, exprPos,
+ len, true);
+
+ if (match != -1) {
+ return true;
+ }
+
+ return false;
+ }
+
+ // Match the fragment of the expression to the target
+ int match = indexOf(target, targetPos, exprPos, star - exprPos,
+ !mobile);
+
+ if (match == -1) {
+ return false;
+ }
+
+ targetPos = (match + star) - exprPos;
+ exprPos = star + 2;
+ mobile = true;
+ }
+ }
+
+ /**
+ * Match a section of target to a fragment of the expression.
+ * If we're only to match the beginning of the target, beginOnly
+ * will be true, otherwise we can match anymore in the target (starting
+ * at the targetStart position). A "." in the expression matches any
+ * character.
+ */
+ private int indexOf(String target, int targetStart, int exprStart,
+ int exprLength, boolean beginOnly) {
+ // Run through the target seeing if there is a match
+ while ((target.length() - targetStart) >= exprLength) {
+ // Assume success. If there isn't a match we'll break out
+ boolean found = true;
+
+ for (int i = 0; i < exprLength; i++) {
+ // "." in the expr matches any character in the target
+ if ((expr.charAt(exprStart + i) != '.') &&
+ (expr.charAt(exprStart + i) != target.charAt(targetStart +
+ i))) {
+ found = false;
+
+ break;
+ }
+ }
+
+ if (found) {
+ return targetStart;
+ }
+
+ // If we're position dependent (beginOnly == true), then don't
+ // continue the search
+ if (beginOnly) {
+ return -1;
+ }
+
+ targetStart++;
+ }
+
+ return -1;
+ }
}
Modified: incubator/openjpa/trunk/openjpa-lib/main/java/org/apache/openjpa/lib/util/SimpleResourceBundleProvider.java
URL: http://svn.apache.org/viewvc/incubator/openjpa/trunk/openjpa-lib/main/java/org/apache/openjpa/lib/util/SimpleResourceBundleProvider.java?rev=417856&r1=415364&r2=417856&view=diff
==============================================================================
--- incubator/openjpa/trunk/openjpa-lib/main/java/org/apache/openjpa/lib/util/SimpleResourceBundleProvider.java (original)
+++ incubator/openjpa/trunk/openjpa-lib/main/java/org/apache/openjpa/lib/util/SimpleResourceBundleProvider.java Wed Jun 28 12:34:33 2006
@@ -15,46 +15,35 @@
*/
package org.apache.openjpa.lib.util;
-
import java.util.*;
/**
- * <p>{@link ResourceBundleProvider} that uses Java's built-in resource
- * bundle lookup methods.</p>
+ * <p>{@link ResourceBundleProvider} that uses Java's built-in resource
+ * bundle lookup methods.</p>
*
- * @author Abe White
+ * @author Abe White
*/
-class SimpleResourceBundleProvider
- implements ResourceBundleProvider
-{
- public ResourceBundle findResource (String name, Locale locale,
- ClassLoader loader)
- {
- ResourceBundle bundle = null;
- if (loader != null)
- {
- try
- {
- bundle = ResourceBundle.getBundle (name, locale, loader);
- }
- catch (Throwable t)
- {
- }
- }
+class SimpleResourceBundleProvider implements ResourceBundleProvider {
+ public ResourceBundle findResource(String name, Locale locale,
+ ClassLoader loader) {
+ ResourceBundle bundle = null;
+
+ if (loader != null) {
+ try {
+ bundle = ResourceBundle.getBundle(name, locale, loader);
+ } catch (Throwable t) {
+ }
+ }
- // try with the default class loader
- if (bundle == null)
- {
- try
- {
- bundle = ResourceBundle.getBundle (name, locale);
- }
- catch (Throwable t)
- {
- }
- }
+ // try with the default class loader
+ if (bundle == null) {
+ try {
+ bundle = ResourceBundle.getBundle(name, locale);
+ } catch (Throwable t) {
+ }
+ }
- return bundle;
- }
+ return bundle;
+ }
}
Added: incubator/openjpa/trunk/openjpa-lib/main/java/org/apache/openjpa/lib/util/SizedMap.java
URL: http://svn.apache.org/viewvc/incubator/openjpa/trunk/openjpa-lib/main/java/org/apache/openjpa/lib/util/SizedMap.java?rev=417856&view=auto
==============================================================================
--- incubator/openjpa/trunk/openjpa-lib/main/java/org/apache/openjpa/lib/util/SizedMap.java (added)
+++ incubator/openjpa/trunk/openjpa-lib/main/java/org/apache/openjpa/lib/util/SizedMap.java Wed Jun 28 12:34:33 2006
@@ -0,0 +1,48 @@
+/*
+ * Copyright 2006 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.openjpa.lib.util;
+
+import java.util.*;
+
+
+/**
+ * <p>A {@link Map} type that maintains a maximum size, automatically
+ * removing entries when the maximum is exceeded.</p>
+ *
+ * @author Abe White
+ */
+public interface SizedMap extends Map {
+ /**
+ * The maximum number of entries, or Integer.MAX_VALUE for no limit.
+ */
+ public int getMaxSize();
+
+ /**
+ * The maximum number of entries, or Integer.MAX_VALUE for no limit.
+ */
+ public void setMaxSize(int max);
+
+ /**
+ * Whether the map is full.
+ */
+ public boolean isFull();
+
+ /**
+ * Overridable callback for when an overflow entry is automatically
+ * removed.
+ */
+ public void overflowRemoved(Object key, Object value);
+}
Propchange: incubator/openjpa/trunk/openjpa-lib/main/java/org/apache/openjpa/lib/util/SizedMap.java
------------------------------------------------------------------------------
svn:executable = *
Modified: incubator/openjpa/trunk/openjpa-lib/main/java/org/apache/openjpa/lib/util/StreamResourceBundleProvider.java
URL: http://svn.apache.org/viewvc/incubator/openjpa/trunk/openjpa-lib/main/java/org/apache/openjpa/lib/util/StreamResourceBundleProvider.java?rev=417856&r1=415364&r2=417856&view=diff
==============================================================================
--- incubator/openjpa/trunk/openjpa-lib/main/java/org/apache/openjpa/lib/util/StreamResourceBundleProvider.java (original)
+++ incubator/openjpa/trunk/openjpa-lib/main/java/org/apache/openjpa/lib/util/StreamResourceBundleProvider.java Wed Jun 28 12:34:33 2006
@@ -15,43 +15,41 @@
*/
package org.apache.openjpa.lib.util;
-
import java.io.*;
+
import java.util.*;
/**
- * <p>{@link ResourceBundleProvider} that uses the
- * {@link ClassLoader#getResourceAsStream} method to load resources.
- * Created for use under WSAD.</p>
+ * <p>{@link ResourceBundleProvider} that uses the
+ * {@link ClassLoader#getResourceAsStream} method to load resources.
+ * Created for use under WSAD.</p>
*
- * @author Stephen Kim
+ * @author Stephen Kim
*/
-class StreamResourceBundleProvider
- implements ResourceBundleProvider
-{
- public ResourceBundle findResource (String name, Locale locale,
- ClassLoader loader)
- {
- String rsrc = name.replace ('.', '/') + ".properties";
- if (loader == null)
- loader = Thread.currentThread ().getContextClassLoader ();
-
- InputStream in = loader.getResourceAsStream (rsrc);
- if (in != null)
- {
- try
- {
- return new PropertyResourceBundle (in);
- }
- catch (Exception e)
- {
- }
- finally
- {
- try { in.close (); } catch (IOException ioe) {}
- }
- }
- return null;
- }
+class StreamResourceBundleProvider implements ResourceBundleProvider {
+ public ResourceBundle findResource(String name, Locale locale,
+ ClassLoader loader) {
+ String rsrc = name.replace('.', '/') + ".properties";
+
+ if (loader == null) {
+ loader = Thread.currentThread().getContextClassLoader();
+ }
+
+ InputStream in = loader.getResourceAsStream(rsrc);
+
+ if (in != null) {
+ try {
+ return new PropertyResourceBundle(in);
+ } catch (Exception e) {
+ } finally {
+ try {
+ in.close();
+ } catch (IOException ioe) {
+ }
+ }
+ }
+
+ return null;
+ }
}
Modified: incubator/openjpa/trunk/openjpa-lib/main/java/org/apache/openjpa/lib/util/StringDistance.java
URL: http://svn.apache.org/viewvc/incubator/openjpa/trunk/openjpa-lib/main/java/org/apache/openjpa/lib/util/StringDistance.java?rev=417856&r1=415364&r2=417856&view=diff
==============================================================================
--- incubator/openjpa/trunk/openjpa-lib/main/java/org/apache/openjpa/lib/util/StringDistance.java (original)
+++ incubator/openjpa/trunk/openjpa-lib/main/java/org/apache/openjpa/lib/util/StringDistance.java Wed Jun 28 12:34:33 2006
@@ -18,199 +18,189 @@
import java.util.*;
-/**
+/**
* Utilities for calculating string distance.
- *
- * @author Marc Prud'hommeaux
- * @nojavadoc
- */
-public class StringDistance
-{
- /**
- * Returns the candidate string with the closest Levenshtein distance
- * to the given string.
- *
- * @see #getClosestLevenshteinDistance(String,Collection,int)
- */
- public static String getClosestLevenshteinDistance (String str,
- String[] candidates)
- {
- if (candidates == null)
- return null;
- return getClosestLevenshteinDistance (str, Arrays.asList (candidates));
- }
-
-
- /**
- * Returns the candidate string with the closest Levenshtein distance
- * to the given string.
- *
- * @see #getClosestLevenshteinDistance(String,Collection,int)
- */
- public static String getClosestLevenshteinDistance (String str,
- Collection candidates)
- {
- return getClosestLevenshteinDistance (str, candidates,
- Integer.MAX_VALUE);
- }
-
-
- /**
- * Returns the candidate string with the closest Levenshtein distance
- * to the given string.
- *
- * @see #getClosestLevenshteinDistance(String,Collection,int)
- */
- public static String getClosestLevenshteinDistance (String str,
- String[] candidates, int threshold)
- {
- if (candidates == null)
- return null;
- return getClosestLevenshteinDistance (str, Arrays.asList (candidates),
- threshold);
- }
-
-
- /**
- * Returns the candidate string with the closest Levenshtein distance
- * to the given string and using the threshold as the specified
- * percentage of the length of the candidate string (0.0f-1.0f).
- *
- * @see #getClosestLevenshteinDistance(String,Collection,int)
- */
- public static String getClosestLevenshteinDistance (String str,
- String[] candidates, float thresholdPercentage)
- {
- if (candidates == null)
- return null;
-
- return getClosestLevenshteinDistance (str, Arrays.asList (candidates),
- thresholdPercentage);
- }
-
-
- /**
- * Returns the candidate string with the closest Levenshtein distance
- * to the given string and using the threshold as the specified
- * percentage of the length of the candidate string (0.0f-1.0f).
- *
- * @see #getClosestLevenshteinDistance(String,Collection,int)
- */
- public static String getClosestLevenshteinDistance (String str,
- Collection candidates, float thresholdPercentage)
- {
- if (str == null)
- return null;
-
- thresholdPercentage = Math.min (thresholdPercentage, 1.0f);
- thresholdPercentage = Math.max (thresholdPercentage, 0.0f);
-
- return getClosestLevenshteinDistance (str, candidates,
- (int)(str.length () * thresholdPercentage));
- }
-
-
- /**
- * Returns the candidate string with the closest Levenshtein distance
- * to the given string.
- *
- * @param str the string to check
- * @param candidates the list of strings to test against
- * @param threshold the threshold distance a candidate must meet
- *
- * @see #getLevenshteinDistance
- */
- public static String getClosestLevenshteinDistance (String str,
- Collection candidates, int threshhold)
- {
- if (candidates == null || candidates.isEmpty ())
- return null;
-
- String minString = null;
- int minValue = Integer.MAX_VALUE;
-
- for (Iterator i = candidates.iterator (); i.hasNext (); )
- {
- String candidate = (String) i.next ();
- int distance = getLevenshteinDistance (str, candidate);
- if (distance < minValue)
- {
- minValue = distance;
- minString = candidate;
- }
- }
-
- // return the lowest close string only if we surpass the threshhold
- if (minValue <= threshhold)
- return minString;
- else
- return null;
- }
-
-
- /**
- * Returns the Levenshtein distance between the two strings.
- * The distance is the minimum number of changes that need to be
- * applied to the first string in order to get to the second
- * string. For details of the algorithm, see
- * <a href="http://en.wikipedia.org/wiki/Levenshtein_distance">
- * http://en.wikipedia.org/wiki/Levenshtein_distance</a>.
- */
- public static int getLevenshteinDistance (String s, String t)
- {
- int n = s.length ();
- int m = t.length ();
-
- if (n == 0)
- return m;
-
- if (m == 0)
- return n;
-
- int[][] matrix = new int[n+1][m+1];
-
- for (int i = 0; i <= n; i++)
- matrix[i][0] = i;
-
- for (int j = 0; j <= m; j++)
- matrix[0][j] = j;
-
- for (int i = 1; i <= n; i++)
- {
- int si = s.charAt (i - 1);
-
- for (int j = 1; j <= m; j++)
- {
- int tj = t.charAt (j - 1);
-
- int cost;
-
- if (si == tj)
- cost = 0;
- else
- cost = 1;
-
- matrix[i][j] = min (matrix[i-1][j]+1,
- matrix[i][j-1]+1,
- matrix[i-1][j-1] + cost);
- }
- }
-
- return matrix[n][m];
- }
-
-
- private static int min (int a, int b, int c)
- {
- int mi = a;
+ *
+ * @author Marc Prud'hommeaux
+ * @nojavadoc */
+public class StringDistance {
+ /**
+ * Returns the candidate string with the closest Levenshtein distance
+ * to the given string.
+ *
+ * @see #getClosestLevenshteinDistance(String,Collection,int)
+ */
+ public static String getClosestLevenshteinDistance(String str,
+ String[] candidates) {
+ if (candidates == null) {
+ return null;
+ }
+
+ return getClosestLevenshteinDistance(str, Arrays.asList(candidates));
+ }
+
+ /**
+ * Returns the candidate string with the closest Levenshtein distance
+ * to the given string.
+ *
+ * @see #getClosestLevenshteinDistance(String,Collection,int)
+ */
+ public static String getClosestLevenshteinDistance(String str,
+ Collection candidates) {
+ return getClosestLevenshteinDistance(str, candidates, Integer.MAX_VALUE);
+ }
+
+ /**
+ * Returns the candidate string with the closest Levenshtein distance
+ * to the given string.
+ *
+ * @see #getClosestLevenshteinDistance(String,Collection,int)
+ */
+ public static String getClosestLevenshteinDistance(String str,
+ String[] candidates, int threshold) {
+ if (candidates == null) {
+ return null;
+ }
+
+ return getClosestLevenshteinDistance(str, Arrays.asList(candidates),
+ threshold);
+ }
+
+ /**
+ * Returns the candidate string with the closest Levenshtein distance
+ * to the given string and using the threshold as the specified
+ * percentage of the length of the candidate string (0.0f-1.0f).
+ *
+ * @see #getClosestLevenshteinDistance(String,Collection,int)
+ */
+ public static String getClosestLevenshteinDistance(String str,
+ String[] candidates, float thresholdPercentage) {
+ if (candidates == null) {
+ return null;
+ }
+
+ return getClosestLevenshteinDistance(str, Arrays.asList(candidates),
+ thresholdPercentage);
+ }
+
+ /**
+ * Returns the candidate string with the closest Levenshtein distance
+ * to the given string and using the threshold as the specified
+ * percentage of the length of the candidate string (0.0f-1.0f).
+ *
+ * @see #getClosestLevenshteinDistance(String,Collection,int)
+ */
+ public static String getClosestLevenshteinDistance(String str,
+ Collection candidates, float thresholdPercentage) {
+ if (str == null) {
+ return null;
+ }
+
+ thresholdPercentage = Math.min(thresholdPercentage, 1.0f);
+ thresholdPercentage = Math.max(thresholdPercentage, 0.0f);
+
+ return getClosestLevenshteinDistance(str, candidates,
+ (int) (str.length() * thresholdPercentage));
+ }
+
+ /**
+ * Returns the candidate string with the closest Levenshtein distance
+ * to the given string.
+ *
+ * @param str the string to check
+ * @param candidates the list of strings to test against
+ * @param threshold the threshold distance a candidate must meet
+ *
+ * @see #getLevenshteinDistance
+ */
+ public static String getClosestLevenshteinDistance(String str,
+ Collection candidates, int threshhold) {
+ if ((candidates == null) || candidates.isEmpty()) {
+ return null;
+ }
+
+ String minString = null;
+ int minValue = Integer.MAX_VALUE;
+
+ for (Iterator i = candidates.iterator(); i.hasNext();) {
+ String candidate = (String) i.next();
+ int distance = getLevenshteinDistance(str, candidate);
+
+ if (distance < minValue) {
+ minValue = distance;
+ minString = candidate;
+ }
+ }
+
+ // return the lowest close string only if we surpass the threshhold
+ if (minValue <= threshhold) {
+ return minString;
+ } else {
+ return null;
+ }
+ }
+
+ /**
+ * Returns the Levenshtein distance between the two strings.
+ * The distance is the minimum number of changes that need to be
+ * applied to the first string in order to get to the second
+ * string. For details of the algorithm, see
+ * <a href="http://en.wikipedia.org/wiki/Levenshtein_distance">
+ * http://en.wikipedia.org/wiki/Levenshtein_distance</a>.
+ */
+ public static int getLevenshteinDistance(String s, String t) {
+ int n = s.length();
+ int m = t.length();
+
+ if (n == 0) {
+ return m;
+ }
+
+ if (m == 0) {
+ return n;
+ }
+
+ int[][] matrix = new int[n + 1][m + 1];
+
+ for (int i = 0; i <= n; i++)
+ matrix[i][0] = i;
+
+ for (int j = 0; j <= m; j++)
+ matrix[0][j] = j;
+
+ for (int i = 1; i <= n; i++) {
+ int si = s.charAt(i - 1);
+
+ for (int j = 1; j <= m; j++) {
+ int tj = t.charAt(j - 1);
+
+ int cost;
+
+ if (si == tj) {
+ cost = 0;
+ } else {
+ cost = 1;
+ }
+
+ matrix[i][j] = min(matrix[i - 1][j] + 1, matrix[i][j - 1] + 1,
+ matrix[i - 1][j - 1] + cost);
+ }
+ }
+
+ return matrix[n][m];
+ }
+
+ private static int min(int a, int b, int c) {
+ int mi = a;
+
+ if (b < mi) {
+ mi = b;
+ }
+
+ if (c < mi) {
+ mi = c;
+ }
- if (b < mi)
- mi = b;
-
- if (c < mi)
- mi = c;
-
- return mi;
- }
+ return mi;
+ }
}
-
Modified: incubator/openjpa/trunk/openjpa-lib/main/java/org/apache/openjpa/lib/util/TemporaryClassLoader.java
URL: http://svn.apache.org/viewvc/incubator/openjpa/trunk/openjpa-lib/main/java/org/apache/openjpa/lib/util/TemporaryClassLoader.java?rev=417856&r1=415364&r2=417856&view=diff
==============================================================================
--- incubator/openjpa/trunk/openjpa-lib/main/java/org/apache/openjpa/lib/util/TemporaryClassLoader.java (original)
+++ incubator/openjpa/trunk/openjpa-lib/main/java/org/apache/openjpa/lib/util/TemporaryClassLoader.java Wed Jun 28 12:34:33 2006
@@ -15,96 +15,92 @@
*/
package org.apache.openjpa.lib.util;
+import serp.bytecode.lowlevel.*;
import java.io.*;
-import serp.bytecode.lowlevel.*;
+import java.util.*;
-/**
+/**
* <p>ClassLoader implementation that allows classes to be temporarily
* loaded and then thrown away. Useful for the enhancer to be able
* to run against a class without first loading (and thus polluting)
* the parent ClassLoader.</p>
- *
- * @author Marc Prud'hommeaux
- * @nojavadoc
- */
-public class TemporaryClassLoader
- extends ClassLoader
-{
- public TemporaryClassLoader (ClassLoader parent)
- {
- super (parent);
- }
-
-
- public Class loadClass (String name)
- throws ClassNotFoundException
- {
- return loadClass (name, false);
- }
-
-
- protected Class loadClass (String name, boolean resolve)
- throws ClassNotFoundException
- {
- // see if we've already loaded it
- Class c = findLoadedClass (name);
- if (c != null)
- return c;
-
- // bug #283. defer to system if the name is a protected name.
- // "sun." is required for JDK 1.4, which has an access check for
- // sun.reflect.GeneratedSerializationConstructorAccessor1
- if (name.startsWith ("java.") || name.startsWith ("javax.")
- || name.startsWith ("sun."))
- return Class.forName (name, resolve, getClass ().getClassLoader ());
-
- String resourceName = name.replace ('.', '/') + ".class";
- InputStream resource = getResourceAsStream (resourceName);
- if (resource == null)
- throw new ClassNotFoundException (name);
-
- ByteArrayOutputStream bout = new ByteArrayOutputStream ();
- byte[] b = new byte[1024];
- try
- {
- for (int n = 0; (n = resource.read (b, 0, b.length)) != -1;
- bout.write (b, 0, n));
- byte[] classBytes = bout.toByteArray ();
- if (isAnnotation (classBytes))
- return Class.forName (name, resolve, getClass ().
- getClassLoader ());
-
- try
- {
- return defineClass (name, classBytes, 0, classBytes.length);
- }
- catch (SecurityException e)
- {
- // possible prohibited package: defer to the parent
- return super.loadClass (name, resolve);
- }
- }
- catch (IOException ioe)
- {
- // defer to the parent
- return super.loadClass (name, resolve);
- }
- }
-
-
- /**
- * Fast-parse the given class bytecode to determine if it is an
- * annotation class.
- */
- private static boolean isAnnotation (byte[] b)
- {
- if (JavaVersions.VERSION < 5)
- return false;
- int idx = ConstantPoolTable.getEndIndex (b);
- int access = ConstantPoolTable.readUnsignedShort (b, idx);
- return (access & 0x2000) != 0; // access constant for annotation type
- }
+ *
+ * @author Marc Prud'hommeaux
+ * @nojavadoc */
+public class TemporaryClassLoader extends ClassLoader {
+ public TemporaryClassLoader(ClassLoader parent) {
+ super(parent);
+ }
+
+ public Class loadClass(String name) throws ClassNotFoundException {
+ return loadClass(name, false);
+ }
+
+ protected Class loadClass(String name, boolean resolve)
+ throws ClassNotFoundException {
+ // see if we've already loaded it
+ Class c = findLoadedClass(name);
+
+ if (c != null) {
+ return c;
+ }
+
+ // bug #283. defer to system if the name is a protected name.
+ // "sun." is required for JDK 1.4, which has an access check for
+ // sun.reflect.GeneratedSerializationConstructorAccessor1
+ if (name.startsWith("java.") || name.startsWith("javax.") ||
+ name.startsWith("sun.")) {
+ return Class.forName(name, resolve, getClass().getClassLoader());
+ }
+
+ String resourceName = name.replace('.', '/') + ".class";
+ InputStream resource = getResourceAsStream(resourceName);
+
+ if (resource == null) {
+ throw new ClassNotFoundException(name);
+ }
+
+ ByteArrayOutputStream bout = new ByteArrayOutputStream();
+ byte[] b = new byte[1024];
+
+ try {
+ for (int n = 0; (n = resource.read(b, 0, b.length)) != -1;
+ bout.write(b, 0, n))
+ ;
+
+ byte[] classBytes = bout.toByteArray();
+
+ if (isAnnotation(classBytes)) {
+ return Class.forName(name, resolve, getClass().getClassLoader());
+ }
+
+ try {
+ return defineClass(name, classBytes, 0, classBytes.length);
+ } catch (SecurityException e) {
+ // possible prohibited package: defer to the parent
+ return super.loadClass(name, resolve);
+ }
+ } catch (IOException ioe) {
+ // defer to the parent
+ return super.loadClass(name, resolve);
+ }
+ }
+
+ /**
+ * Fast-parse the given class bytecode to determine if it is an
+ * annotation class.
+ */
+ private static boolean isAnnotation(byte[] b) {
+ if (JavaVersions.VERSION < 5) {
+ return false;
+ }
+
+ int idx = ConstantPoolTable.getEndIndex(b);
+ int access = ConstantPoolTable.readUnsignedShort(b, idx);
+
+ return (access & 0x2000) != 0; // access constant for annotation type
+ }
}
Modified: incubator/openjpa/trunk/openjpa-lib/main/java/org/apache/openjpa/lib/util/TypedProperties.java
URL: http://svn.apache.org/viewvc/incubator/openjpa/trunk/openjpa-lib/main/java/org/apache/openjpa/lib/util/TypedProperties.java?rev=417856&r1=415364&r2=417856&view=diff
==============================================================================
--- incubator/openjpa/trunk/openjpa-lib/main/java/org/apache/openjpa/lib/util/TypedProperties.java (original)
+++ incubator/openjpa/trunk/openjpa-lib/main/java/org/apache/openjpa/lib/util/TypedProperties.java Wed Jun 28 12:34:33 2006
@@ -15,377 +15,341 @@
*/
package org.apache.openjpa.lib.util;
-
import java.util.*;
/**
- * <p>A specialization of the {@link Properties} map type with added
- * convenience methods to retrieve and set options as primitive values.
- * The internal representation of all data is kept in string form.</p>
+ * <p>A specialization of the {@link Properties} map type with added
+ * convenience methods to retrieve and set options as primitive values.
+ * The internal representation of all data is kept in string form.</p>
*
- * @author Abe White
- * @nojavadoc
- */
-public class TypedProperties
- extends Properties
-{
- /**
- * Default constructor.
- */
- public TypedProperties ()
- {
- super ();
- }
-
-
- /**
- * Construct the properties instance with the given set of defaults.
- *
- * @see Properties#Properties(Properties)
- */
- public TypedProperties (Properties defaults)
- {
- super (defaults);
- }
-
-
- /**
- * Return the property under the given key as a boolean, or false if
- * it does not exist and has no set default.
- */
- public boolean getBooleanProperty (String key)
- {
- return getBooleanProperty (key, false);
- }
-
-
- /**
- * Return the property under the given key as a boolean, or the given
- * default if it does not exist.
- */
- public boolean getBooleanProperty (String key, boolean def)
- {
- String val = getProperty (key);
- if (val == null)
- return def;
- return "t".equalsIgnoreCase (val) || "true".equalsIgnoreCase (val);
- }
-
-
- /**
- * Return the property under the given key as a float, or 0 if
- * it does not exist and has no set default.
- *
- * @throws NumberFormatException on parse error
- */
- public float getFloatProperty (String key)
- {
- return getFloatProperty (key, 0F);
- }
-
-
- /**
- * Return the property under the given key as a float, or the given
- * default if it does not exist.
- *
- * @throws NumberFormatException on parse error
- */
- public float getFloatProperty (String key, float def)
- {
- String val = getProperty (key);
- return (val == null) ? def : Float.parseFloat (val);
- }
-
-
- /**
- * Return the property under the given key as a double, or 0 if
- * it does not exist and has no set default.
- *
- * @throws NumberFormatException on parse error
- */
- public double getDoubleProperty (String key)
- {
- return getDoubleProperty (key, 0D);
- }
-
-
- /**
- * Return the property under the given key as a double, or the given
- * default if it does not exist.
- *
- * @throws NumberFormatException on parse error
- */
- public double getDoubleProperty (String key, double def)
- {
- String val = getProperty (key);
- return (val == null) ? def : Double.parseDouble (val);
- }
-
-
- /**
- * Return the property under the given key as a long, or 0 if
- * it does not exist and has no set default.
- *
- * @throws NumberFormatException on parse error
- */
- public long getLongProperty (String key)
- {
- return getLongProperty (key, 0L);
- }
-
-
- /**
- * Return the property under the given key as a double, or the given
- * default if it does not exist.
- *
- * @throws NumberFormatException on parse error
- */
- public long getLongProperty (String key, long def)
- {
- String val = getProperty (key);
- return (val == null) ? def : Long.parseLong (val);
- }
-
-
- /**
- * Return the property under the given key as an int, or 0 if
- * it does not exist and has no set default.
- *
- * @throws NumberFormatException on parse error
- */
- public int getIntProperty (String key)
- {
- return getIntProperty (key, 0);
- }
-
-
- /**
- * Return the property under the given key as an int, or the given
- * default if it does not exist.
- *
- * @throws NumberFormatException on parse error
- */
- public int getIntProperty (String key, int def)
- {
- String val = getProperty (key);
- return (val == null) ? def : Integer.parseInt (val);
- }
-
-
- /**
- * Overrides {@link Properties#setProperty(String,String)} to remove
- * the key if the given value is <code>null</code>.
- *
- * @see Properties#setProperty(String,String)
- */
- public Object setProperty (String key, String val)
- {
- if (val == null)
- return remove (key);
- return super.setProperty (key, val);
- }
-
-
- /**
- * Set the given key to a string version of the given value.
- *
- * @see Properties#setProperty(String,String)
- */
- public void setProperty (String key, boolean val)
- {
- setProperty (key, String.valueOf (val));
- }
-
-
- /**
- * Set the given key to a string version of the given value.
- *
- * @see Properties#setProperty(String,String)
- */
- public void setProperty (String key, double val)
- {
- setProperty (key, String.valueOf (val));
- }
-
-
- /**
- * Set the given key to a string version of the given value.
- *
- * @see Properties#setProperty(String,String)
- */
- public void setProperty (String key, float val)
- {
- setProperty (key, String.valueOf (val));
- }
-
-
- /**
- * Set the given key to a string version of the given value.
- *
- * @see Properties#setProperty(String,String)
- */
- public void setProperty (String key, int val)
- {
- setProperty (key, String.valueOf (val));
- }
-
-
- /**
- * Set the given key to a string version of the given value.
- *
- * @see Properties#setProperty(String,String)
- */
- public void setProperty (String key, long val)
- {
- setProperty (key, String.valueOf (val));
- }
-
-
- /**
- * Remove the given property.
- */
- public String removeProperty (String key)
- {
- Object val = remove (key);
- return (val == null) ? null : val.toString ();
- }
-
-
- /**
- * Remove the given property, or return the given default if it does
- * not exist.
- */
- public String removeProperty (String key, String def)
- {
- if (!containsKey (key))
- return def;
- return removeProperty (key);
- }
-
-
- /**
- * Remove the property under the given key as a boolean.
- */
- public boolean removeBooleanProperty (String key)
- {
- String val = removeProperty (key);
- return "t".equalsIgnoreCase (val) || "true".equalsIgnoreCase (val);
- }
-
-
- /**
- * Remove the property under the given key as a boolean, or return the
- * given default if it does not exist.
- */
- public boolean removeBooleanProperty (String key, boolean def)
- {
- if (!containsKey (key))
- return def;
- return removeBooleanProperty (key);
- }
-
-
- /**
- * Remove the property under the given key as a double.
- *
- * @throws NumberFormatException on parse error
- */
- public double removeDoubleProperty (String key)
- {
- String val = removeProperty (key);
- return (val == null) ? 0D : Double.parseDouble (val);
- }
-
-
- /**
- * Remove the property under the given key as a double, or return the
- * given default if it does not exist.
- *
- * @throws NumberFormatException on parse error
- */
- public double removeDoubleProperty (String key, double def)
- {
- if (!containsKey (key))
- return def;
- return removeDoubleProperty (key);
- }
-
-
- /**
- * Remove the property under the given key as a float.
- *
- * @throws NumberFormatException on parse error
- */
- public float removeFloatProperty (String key)
- {
- String val = removeProperty (key);
- return (val == null) ? 0F : Float.parseFloat (val);
- }
-
-
- /**
- * Remove the property under the given key as a float, or return the
- * given default if it does not exist.
- *
- * @throws NumberFormatException on parse error
- */
- public float removeFloatProperty (String key, float def)
- {
- if (!containsKey (key))
- return def;
- return removeFloatProperty (key);
- }
-
-
- /**
- * Remove the property under the given key as a int.
- *
- * @throws NumberFormatException on parse error
- */
- public int removeIntProperty (String key)
- {
- String val = removeProperty (key);
- return (val == null) ? 0 : Integer.parseInt (val);
- }
-
-
- /**
- * Remove the property under the given key as a int, or return the
- * given default if it does not exist.
- *
- * @throws NumberFormatException on parse error
- */
- public int removeIntProperty (String key, int def)
- {
- if (!containsKey (key))
- return def;
- return removeIntProperty (key);
- }
-
-
- /**
- * Remove the property under the given key as a long.
- *
- * @throws NumberFormatException on parse error
- */
- public long removeLongProperty (String key)
- {
- String val = removeProperty (key);
- return (val == null) ? 0L : Long.parseLong (val);
- }
-
-
- /**
- * Remove the property under the given key as a long, or return the
- * given default if it does not exist.
- *
- * @throws NumberFormatException on parse error
- */
- public long removeLongProperty (String key, long def)
- {
- if (!containsKey (key))
- return def;
- return removeLongProperty (key);
- }
+ * @author Abe White
+ * @nojavadoc */
+public class TypedProperties extends Properties {
+ /**
+ * Default constructor.
+ */
+ public TypedProperties() {
+ super();
+ }
+
+ /**
+ * Construct the properties instance with the given set of defaults.
+ *
+ * @see Properties#Properties(Properties)
+ */
+ public TypedProperties(Properties defaults) {
+ super(defaults);
+ }
+
+ /**
+ * Return the property under the given key as a boolean, or false if
+ * it does not exist and has no set default.
+ */
+ public boolean getBooleanProperty(String key) {
+ return getBooleanProperty(key, false);
+ }
+
+ /**
+ * Return the property under the given key as a boolean, or the given
+ * default if it does not exist.
+ */
+ public boolean getBooleanProperty(String key, boolean def) {
+ String val = getProperty(key);
+
+ if (val == null) {
+ return def;
+ }
+
+ return "t".equalsIgnoreCase(val) || "true".equalsIgnoreCase(val);
+ }
+
+ /**
+ * Return the property under the given key as a float, or 0 if
+ * it does not exist and has no set default.
+ *
+ * @throws NumberFormatException on parse error
+ */
+ public float getFloatProperty(String key) {
+ return getFloatProperty(key, 0F);
+ }
+
+ /**
+ * Return the property under the given key as a float, or the given
+ * default if it does not exist.
+ *
+ * @throws NumberFormatException on parse error
+ */
+ public float getFloatProperty(String key, float def) {
+ String val = getProperty(key);
+
+ return (val == null) ? def : Float.parseFloat(val);
+ }
+
+ /**
+ * Return the property under the given key as a double, or 0 if
+ * it does not exist and has no set default.
+ *
+ * @throws NumberFormatException on parse error
+ */
+ public double getDoubleProperty(String key) {
+ return getDoubleProperty(key, 0D);
+ }
+
+ /**
+ * Return the property under the given key as a double, or the given
+ * default if it does not exist.
+ *
+ * @throws NumberFormatException on parse error
+ */
+ public double getDoubleProperty(String key, double def) {
+ String val = getProperty(key);
+
+ return (val == null) ? def : Double.parseDouble(val);
+ }
+
+ /**
+ * Return the property under the given key as a long, or 0 if
+ * it does not exist and has no set default.
+ *
+ * @throws NumberFormatException on parse error
+ */
+ public long getLongProperty(String key) {
+ return getLongProperty(key, 0L);
+ }
+
+ /**
+ * Return the property under the given key as a double, or the given
+ * default if it does not exist.
+ *
+ * @throws NumberFormatException on parse error
+ */
+ public long getLongProperty(String key, long def) {
+ String val = getProperty(key);
+
+ return (val == null) ? def : Long.parseLong(val);
+ }
+
+ /**
+ * Return the property under the given key as an int, or 0 if
+ * it does not exist and has no set default.
+ *
+ * @throws NumberFormatException on parse error
+ */
+ public int getIntProperty(String key) {
+ return getIntProperty(key, 0);
+ }
+
+ /**
+ * Return the property under the given key as an int, or the given
+ * default if it does not exist.
+ *
+ * @throws NumberFormatException on parse error
+ */
+ public int getIntProperty(String key, int def) {
+ String val = getProperty(key);
+
+ return (val == null) ? def : Integer.parseInt(val);
+ }
+
+ /**
+ * Overrides {@link Properties#setProperty(String,String)} to remove
+ * the key if the given value is <code>null</code>.
+ *
+ * @see Properties#setProperty(String,String)
+ */
+ public Object setProperty(String key, String val) {
+ if (val == null) {
+ return remove(key);
+ }
+
+ return super.setProperty(key, val);
+ }
+
+ /**
+ * Set the given key to a string version of the given value.
+ *
+ * @see Properties#setProperty(String,String)
+ */
+ public void setProperty(String key, boolean val) {
+ setProperty(key, String.valueOf(val));
+ }
+
+ /**
+ * Set the given key to a string version of the given value.
+ *
+ * @see Properties#setProperty(String,String)
+ */
+ public void setProperty(String key, double val) {
+ setProperty(key, String.valueOf(val));
+ }
+
+ /**
+ * Set the given key to a string version of the given value.
+ *
+ * @see Properties#setProperty(String,String)
+ */
+ public void setProperty(String key, float val) {
+ setProperty(key, String.valueOf(val));
+ }
+
+ /**
+ * Set the given key to a string version of the given value.
+ *
+ * @see Properties#setProperty(String,String)
+ */
+ public void setProperty(String key, int val) {
+ setProperty(key, String.valueOf(val));
+ }
+
+ /**
+ * Set the given key to a string version of the given value.
+ *
+ * @see Properties#setProperty(String,String)
+ */
+ public void setProperty(String key, long val) {
+ setProperty(key, String.valueOf(val));
+ }
+
+ /**
+ * Remove the given property.
+ */
+ public String removeProperty(String key) {
+ Object val = remove(key);
+
+ return (val == null) ? null : val.toString();
+ }
+
+ /**
+ * Remove the given property, or return the given default if it does
+ * not exist.
+ */
+ public String removeProperty(String key, String def) {
+ if (!containsKey(key)) {
+ return def;
+ }
+
+ return removeProperty(key);
+ }
+
+ /**
+ * Remove the property under the given key as a boolean.
+ */
+ public boolean removeBooleanProperty(String key) {
+ String val = removeProperty(key);
+
+ return "t".equalsIgnoreCase(val) || "true".equalsIgnoreCase(val);
+ }
+
+ /**
+ * Remove the property under the given key as a boolean, or return the
+ * given default if it does not exist.
+ */
+ public boolean removeBooleanProperty(String key, boolean def) {
+ if (!containsKey(key)) {
+ return def;
+ }
+
+ return removeBooleanProperty(key);
+ }
+
+ /**
+ * Remove the property under the given key as a double.
+ *
+ * @throws NumberFormatException on parse error
+ */
+ public double removeDoubleProperty(String key) {
+ String val = removeProperty(key);
+
+ return (val == null) ? 0D : Double.parseDouble(val);
+ }
+
+ /**
+ * Remove the property under the given key as a double, or return the
+ * given default if it does not exist.
+ *
+ * @throws NumberFormatException on parse error
+ */
+ public double removeDoubleProperty(String key, double def) {
+ if (!containsKey(key)) {
+ return def;
+ }
+
+ return removeDoubleProperty(key);
+ }
+
+ /**
+ * Remove the property under the given key as a float.
+ *
+ * @throws NumberFormatException on parse error
+ */
+ public float removeFloatProperty(String key) {
+ String val = removeProperty(key);
+
+ return (val == null) ? 0F : Float.parseFloat(val);
+ }
+
+ /**
+ * Remove the property under the given key as a float, or return the
+ * given default if it does not exist.
+ *
+ * @throws NumberFormatException on parse error
+ */
+ public float removeFloatProperty(String key, float def) {
+ if (!containsKey(key)) {
+ return def;
+ }
+
+ return removeFloatProperty(key);
+ }
+
+ /**
+ * Remove the property under the given key as a int.
+ *
+ * @throws NumberFormatException on parse error
+ */
+ public int removeIntProperty(String key) {
+ String val = removeProperty(key);
+
+ return (val == null) ? 0 : Integer.parseInt(val);
+ }
+
+ /**
+ * Remove the property under the given key as a int, or return the
+ * given default if it does not exist.
+ *
+ * @throws NumberFormatException on parse error
+ */
+ public int removeIntProperty(String key, int def) {
+ if (!containsKey(key)) {
+ return def;
+ }
+
+ return removeIntProperty(key);
+ }
+
+ /**
+ * Remove the property under the given key as a long.
+ *
+ * @throws NumberFormatException on parse error
+ */
+ public long removeLongProperty(String key) {
+ String val = removeProperty(key);
+
+ return (val == null) ? 0L : Long.parseLong(val);
+ }
+
+ /**
+ * Remove the property under the given key as a long, or return the
+ * given default if it does not exist.
+ *
+ * @throws NumberFormatException on parse error
+ */
+ public long removeLongProperty(String key, long def) {
+ if (!containsKey(key)) {
+ return def;
+ }
+
+ return removeLongProperty(key);
+ }
}
Added: incubator/openjpa/trunk/openjpa-lib/main/java/org/apache/openjpa/lib/util/UUIDGenerator.java
URL: http://svn.apache.org/viewvc/incubator/openjpa/trunk/openjpa-lib/main/java/org/apache/openjpa/lib/util/UUIDGenerator.java?rev=417856&view=auto
==============================================================================
--- incubator/openjpa/trunk/openjpa-lib/main/java/org/apache/openjpa/lib/util/UUIDGenerator.java (added)
+++ incubator/openjpa/trunk/openjpa-lib/main/java/org/apache/openjpa/lib/util/UUIDGenerator.java Wed Jun 28 12:34:33 2006
@@ -0,0 +1,193 @@
+/*
+ * Copyright 2006 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.openjpa.lib.util;
+
+import org.apache.commons.lang.exception.*;
+
+import java.io.*;
+
+import java.net.*;
+
+import java.security.*;
+
+import java.util.*;
+
+
+/**
+ * <p>UUID value generator. Based on the time-based generator in the LGPL
+ * project:<br />
+ * http://www.doomdark.org/doomdark/proj/jug/<br />
+ * The code has been vastly simplified and modified to replace the ethernet
+ * address of the host machine with the IP, since we do not want to require
+ * native libs and Java cannot access the MAC address directly.</p>
+ *
+ * <p>Aside from the above modification, implements the IETF UUID draft
+ * specification, found here:
+ * http://www1.ics.uci.edu/~ejw/authoring/uuid-guid
+ * draft-leach-uuids-guids-01.txt</p>
+ *
+ * @author Abe White
+ * @since 3.3
+ * @nojavadoc */
+public class UUIDGenerator {
+ // indexes within the uuid array for certain boundaries
+ private static final byte IDX_TIME_HI = 6;
+ private static final byte IDX_TYPE = 6; // multiplexed
+ private static final byte IDX_TIME_MID = 4;
+ private static final byte IDX_TIME_LO = 0;
+ private static final byte IDX_TIME_SEQ = 8;
+ private static final byte IDX_VARIATION = 8; // multiplexed
+
+ // offset to move from 1/1/1970, which is 0-time for Java, to gregorian
+ // 0-time 10/15/1582, and multiplier to go from 100nsec to msec units
+ private static final long GREG_OFFSET = 0x01b21dd213814000L;
+ private static final long MILLI_MULT = 10000L;
+
+ // type of UUID; is this part of the spec?
+ private final static byte TYPE_TIME_BASED = 1;
+
+ // random number generator used to reduce conflicts with other JVMs, and
+ // hasher for strings. note that secure random is very slow the first time
+ // it is used; consider switching to a standard random
+ private static final Random RANDOM = new SecureRandom();
+
+ // 4-byte IP address + 2 random bytes to compensate for the fact that
+ // the MAC address is usually 6 bytes
+ private static final byte[] IP;
+
+ // counter is initialized not to 0 but to a random 8-bit number, and each
+ // time clock changes, lowest 8-bits of counter are preserved. the purpose
+ // is to reduce chances of multi-JVM collisions without reducing perf
+ // awhite: I don't really understand this precaution, but it was in the
+ // original algo
+ private static int _counter;
+
+ // last used millis time, and a randomized sequence that gets reset
+ // whenever the time is reset
+ private static long _last = 0L;
+ private static byte[] _seq = new byte[2];
+
+ static {
+ byte[] ip = null;
+
+ try {
+ ip = InetAddress.getLocalHost().getAddress();
+ } catch (IOException ioe) {
+ throw new NestableRuntimeException(ioe);
+ }
+
+ IP = new byte[6];
+ RANDOM.nextBytes(IP);
+ System.arraycopy(ip, 0, IP, 2, ip.length);
+
+ resetTime();
+ }
+
+ /**
+ * Return a unique UUID value.
+ */
+ public static byte[] next() {
+ // set ip addr
+ byte[] uuid = new byte[16];
+ System.arraycopy(IP, 0, uuid, 10, IP.length);
+
+ // set time info
+ long now = System.currentTimeMillis();
+
+ synchronized (UUIDGenerator.class) {
+ // if time moves backwards somehow, spec says to reset randomization
+ if (now < _last) {
+ resetTime();
+ } else if ((now == _last) && (_counter == MILLI_MULT)) {
+ // if we run out of slots in this milli, increment
+ now++;
+ _last = now;
+ _counter &= 0xFF; // rest counter?
+ } else if (now > _last) {
+ _last = now;
+ _counter &= 0xFF; // rest counter?
+ }
+
+ // translate timestamp to 100ns slot since beginning of gregorian
+ now *= MILLI_MULT;
+ now += GREG_OFFSET;
+
+ // add nano slot
+ now += _counter;
+ _counter++; // increment counter
+
+ // set random info
+ for (int i = 0; i < _seq.length; i++)
+ uuid[IDX_TIME_SEQ + i] = _seq[i];
+ }
+
+ // have to break up time because bytes are spread through uuid
+ int timeHi = (int) (now >>> 32);
+ int timeLo = (int) now;
+
+ uuid[IDX_TIME_HI] = (byte) (timeHi >>> 24);
+ uuid[IDX_TIME_HI + 1] = (byte) (timeHi >>> 16);
+ uuid[IDX_TIME_MID] = (byte) (timeHi >>> 8);
+ uuid[IDX_TIME_MID + 1] = (byte) timeHi;
+
+ uuid[IDX_TIME_LO] = (byte) (timeLo >>> 24);
+ uuid[IDX_TIME_LO + 1] = (byte) (timeLo >>> 16);
+ uuid[IDX_TIME_LO + 2] = (byte) (timeLo >>> 8);
+ uuid[IDX_TIME_LO + 3] = (byte) timeLo;
+
+ // set type info
+ uuid[IDX_TYPE] &= (byte) 0x0F;
+ uuid[IDX_TYPE] |= (byte) (TYPE_TIME_BASED << 4);
+ uuid[IDX_VARIATION] &= 0x3F;
+ uuid[IDX_VARIATION] |= 0x80;
+
+ return uuid;
+ }
+
+ /**
+ * Return the next unique uuid value as a 16-character string.
+ */
+ public static String nextString() {
+ byte[] bytes = next();
+
+ try {
+ return new String(bytes, "ISO-8859-1");
+ } catch (Exception e) {
+ return new String(bytes);
+ }
+ }
+
+ /**
+ * Return the next unique uuid value as a 32-character hex string.
+ */
+ public static String nextHex() {
+ return Base16Encoder.encode(next());
+ }
+
+ /**
+ * Reset the random time sequence and counter. Must be called from
+ * synchronized code.
+ */
+ private static void resetTime() {
+ _last = 0L;
+ RANDOM.nextBytes(_seq);
+
+ // awhite: I don't understand this; copied from original algo
+ byte[] tmp = new byte[1];
+ RANDOM.nextBytes(tmp);
+ _counter = tmp[0] & 0xFF;
+ }
+}
Propchange: incubator/openjpa/trunk/openjpa-lib/main/java/org/apache/openjpa/lib/util/UUIDGenerator.java
------------------------------------------------------------------------------
svn:executable = *
Modified: incubator/openjpa/trunk/openjpa-lib/main/java/org/apache/openjpa/lib/util/ZipResourceBundleProvider.java
URL: http://svn.apache.org/viewvc/incubator/openjpa/trunk/openjpa-lib/main/java/org/apache/openjpa/lib/util/ZipResourceBundleProvider.java?rev=417856&r1=415364&r2=417856&view=diff
==============================================================================
--- incubator/openjpa/trunk/openjpa-lib/main/java/org/apache/openjpa/lib/util/ZipResourceBundleProvider.java (original)
+++ incubator/openjpa/trunk/openjpa-lib/main/java/org/apache/openjpa/lib/util/ZipResourceBundleProvider.java Wed Jun 28 12:34:33 2006
@@ -15,56 +15,61 @@
*/
package org.apache.openjpa.lib.util;
-
import java.io.*;
+
import java.util.*;
import java.util.zip.*;
/**
- * <p>{@link ResourceBundleProvider} that expects the
- * {@link ClassLoader#getResourceAsStream} method to return a zipped input
- * stream. Created for use under Weblogic RARs.</p>
+ * <p>{@link ResourceBundleProvider} that expects the
+ * {@link ClassLoader#getResourceAsStream} method to return a zipped input
+ * stream. Created for use under Weblogic RARs.</p>
*
- * @author Patrick Linskey
+ * @author Patrick Linskey
*/
-class ZipResourceBundleProvider
- implements ResourceBundleProvider
-{
- public ResourceBundle findResource (String name, Locale locale,
- ClassLoader loader)
- {
- String rsrc = name.replace ('.', '/') + ".properties";
- if (loader == null)
- loader = Thread.currentThread ().getContextClassLoader ();
-
- InputStream in = loader.getResourceAsStream (rsrc);
- if (in == null)
- return null;
-
- ZipInputStream zip = new ZipInputStream (in);
- try
- {
- ZipEntry ze;
- while (true)
- {
- ze = zip.getNextEntry ();
- if (ze == null)
- break;
-
- if (rsrc.equals (ze.getName ()))
- return new PropertyResourceBundle (zip);
-
- zip.closeEntry ();
- }
- }
- catch (Exception e)
- {
- }
- finally
- {
- try { zip.close (); } catch (IOException ioe) {}
- }
- return null;
- }
+class ZipResourceBundleProvider implements ResourceBundleProvider {
+ public ResourceBundle findResource(String name, Locale locale,
+ ClassLoader loader) {
+ String rsrc = name.replace('.', '/') + ".properties";
+
+ if (loader == null) {
+ loader = Thread.currentThread().getContextClassLoader();
+ }
+
+ InputStream in = loader.getResourceAsStream(rsrc);
+
+ if (in == null) {
+ return null;
+ }
+
+ ZipInputStream zip = new ZipInputStream(in);
+ ResourceBundle bundle = null;
+
+ try {
+ ZipEntry ze;
+
+ while (true) {
+ ze = zip.getNextEntry();
+
+ if (ze == null) {
+ break;
+ }
+
+ if (rsrc.equals(ze.getName())) {
+ return new PropertyResourceBundle(zip);
+ }
+
+ zip.closeEntry();
+ }
+ } catch (Exception e) {
+ } finally {
+ try {
+ zip.close();
+ } catch (IOException ioe) {
+ }
+ }
+
+ return null;
+ }
}
Added: incubator/openjpa/trunk/openjpa-lib/main/java/org/apache/openjpa/lib/util/concurrent/AbstractCollection.java
URL: http://svn.apache.org/viewvc/incubator/openjpa/trunk/openjpa-lib/main/java/org/apache/openjpa/lib/util/concurrent/AbstractCollection.java?rev=417856&view=auto
==============================================================================
--- incubator/openjpa/trunk/openjpa-lib/main/java/org/apache/openjpa/lib/util/concurrent/AbstractCollection.java (added)
+++ incubator/openjpa/trunk/openjpa-lib/main/java/org/apache/openjpa/lib/util/concurrent/AbstractCollection.java Wed Jun 28 12:34:33 2006
@@ -0,0 +1,48 @@
+/*
+ * Copyright 2006 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/*
+ * Written by Dawid Kurzyniec, based on public domain code written by Doug Lea
+ * and publictly available documentation, and released to the public domain, as
+ * explained at http://creativecommons.org/licenses/publicdomain
+ */
+package org.apache.openjpa.lib.util.concurrent;
+
+
+/**
+ * Overrides toArray() and toArray(Object[]) in AbstractCollection to provide
+ * implementations valid for concurrent collections.
+ *
+ * @author Doug Lea
+ * @author Dawid Kurzyniec
+ */
+abstract class AbstractCollection extends java.util.AbstractCollection {
+ /**
+ * Sole constructor. (For invocation by subclass constructors, typically
+ * implicit.)
+ */
+ protected AbstractCollection() {
+ super();
+ }
+
+ public Object[] toArray() {
+ return Utils.collectionToArray(this);
+ }
+
+ public Object[] toArray(Object[] a) {
+ return Utils.collectionToArray(this, a);
+ }
+}
Propchange: incubator/openjpa/trunk/openjpa-lib/main/java/org/apache/openjpa/lib/util/concurrent/AbstractCollection.java
------------------------------------------------------------------------------
svn:executable = *
Added: incubator/openjpa/trunk/openjpa-lib/main/java/org/apache/openjpa/lib/util/concurrent/AbstractConcurrentEventManager.java
URL: http://svn.apache.org/viewvc/incubator/openjpa/trunk/openjpa-lib/main/java/org/apache/openjpa/lib/util/concurrent/AbstractConcurrentEventManager.java?rev=417856&view=auto
==============================================================================
--- incubator/openjpa/trunk/openjpa-lib/main/java/org/apache/openjpa/lib/util/concurrent/AbstractConcurrentEventManager.java (added)
+++ incubator/openjpa/trunk/openjpa-lib/main/java/org/apache/openjpa/lib/util/concurrent/AbstractConcurrentEventManager.java Wed Jun 28 12:34:33 2006
@@ -0,0 +1,106 @@
+/*
+ * Copyright 2006 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.openjpa.lib.util.concurrent;
+
+import org.apache.openjpa.lib.util.*;
+
+import java.util.*;
+
+
+/**
+ * <p>Base event manager that handles adding/removing listeners
+ * and firing events. Meant for high concurrency. This class is
+ * reentrant-safe; listeners can be added and removed by other listeners when * they receive events. The changes will not be visible until the event fire
+ * that initiated the recursive sequence of calls completes, however.</p>
+ *
+ * @author Abe White
+ */
+public abstract class AbstractConcurrentEventManager implements EventManager {
+ private static Exception[] EMPTY_EXCEPTIONS = new Exception[0];
+ private Collection _listeners = new CopyOnWriteArraySet();
+
+ /**
+ * Register an event listener.
+ */
+ public void addListener(Object listener) {
+ if (listener != null) {
+ _listeners.add(listener);
+ }
+ }
+
+ /**
+ * Remove an event listener.
+ */
+ public boolean removeListener(Object listener) {
+ return _listeners.remove(listener);
+ }
+
+ /**
+ * Return whether the given instance is in the list of listeners.
+ */
+ public boolean hasListener(Object listener) {
+ return _listeners.contains(listener);
+ }
+
+ /**
+ * Return true if there are any registered listeners.
+ */
+ public boolean hasListeners() {
+ return !_listeners.isEmpty();
+ }
+
+ /**
+ * Return a read-only list of listeners.
+ */
+ public Collection getListeners() {
+ return Collections.unmodifiableCollection(_listeners);
+ }
+
+ /**
+ * Fire the given event to all listeners.
+ */
+ public Exception[] fireEvent(Object event) {
+ if (_listeners.isEmpty()) {
+ return EMPTY_EXCEPTIONS;
+ }
+
+ List exceptions = null;
+
+ for (Iterator itr = _listeners.iterator(); itr.hasNext();) {
+ try {
+ fireEvent(event, itr.next());
+ } catch (Exception e) {
+ if (exceptions == null) {
+ exceptions = new LinkedList();
+ }
+
+ exceptions.add(e);
+ }
+ }
+
+ if (exceptions == null) {
+ return EMPTY_EXCEPTIONS;
+ }
+
+ return (Exception[]) exceptions.toArray(new Exception[exceptions.size()]);
+ }
+
+ /**
+ * Implement this method to fire the given event to the given listener.
+ */
+ protected abstract void fireEvent(Object event, Object listener)
+ throws Exception;
+}
Propchange: incubator/openjpa/trunk/openjpa-lib/main/java/org/apache/openjpa/lib/util/concurrent/AbstractConcurrentEventManager.java
------------------------------------------------------------------------------
svn:executable = *
Added: incubator/openjpa/trunk/openjpa-lib/main/java/org/apache/openjpa/lib/util/concurrent/AbstractQueue.java
URL: http://svn.apache.org/viewvc/incubator/openjpa/trunk/openjpa-lib/main/java/org/apache/openjpa/lib/util/concurrent/AbstractQueue.java?rev=417856&view=auto
==============================================================================
--- incubator/openjpa/trunk/openjpa-lib/main/java/org/apache/openjpa/lib/util/concurrent/AbstractQueue.java (added)
+++ incubator/openjpa/trunk/openjpa-lib/main/java/org/apache/openjpa/lib/util/concurrent/AbstractQueue.java Wed Jun 28 12:34:33 2006
@@ -0,0 +1,193 @@
+/*
+ * Copyright 2006 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/*
+ * Written by Doug Lea with assistance from members of JCP JSR-166
+ * Expert Group and released to the public domain, as explained at
+ * http://creativecommons.org/licenses/publicdomain
+ */
+package org.apache.openjpa.lib.util.concurrent;
+
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.NoSuchElementException;
+
+
+/**
+ * This class provides skeletal implementations of some {@link Queue}
+ * operations. The implementations in this class are appropriate when
+ * the base implementation does <em>not</em> allow <tt>null</tt>
+ * elements. Methods {@link #add add}, {@link #remove remove}, and
+ * {@link #element element} are based on {@link #offer offer}, {@link
+ * #poll poll}, and {@link #peek peek}, respectively but throw
+ * exceptions instead of indicating failure via <tt>false</tt> or
+ * <tt>null</tt> returns.
+ *
+ * <p> A <tt>Queue</tt> implementation that extends this class must
+ * minimally define a method {@link Queue#offer} which does not permit
+ * insertion of <tt>null</tt> elements, along with methods {@link
+ * Queue#peek}, {@link Queue#poll}, {@link Collection#size}, and a
+ * {@link Collection#iterator} supporting {@link
+ * Iterator#remove}. Typically, additional methods will be overridden
+ * as well. If these requirements cannot be met, consider instead
+ * subclassing {@link AbstractCollection}.
+ *
+ * <p>This class is a member of the
+ * <a href="{@docRoot}/../guide/collections/index.html">
+ * Java Collections Framework</a>.
+ *
+ * @since 1.5
+ * @author Doug Lea
+ */
+abstract class AbstractQueue extends AbstractCollection implements Queue {
+ /**
+ * Constructor for use by subclasses.
+ */
+ protected AbstractQueue() {
+ }
+
+ /**
+ * Inserts the specified element into this queue if it is possible to do so
+ * immediately without violating capacity restrictions, returning
+ * <tt>true</tt> upon success and throwing an <tt>IllegalStateException</tt>
+ * if no space is currently available.
+ *
+ * <p>This implementation returns <tt>true</tt> if <tt>offer</tt> succeeds,
+ * else throws an <tt>IllegalStateException</tt>.
+ *
+ * @param e the element to add
+ * @return <tt>true</tt> (as specified by {@link Collection#add})
+ * @throws IllegalStateException if the element cannot be added at this
+ * time due to capacity restrictions
+ * @throws ClassCastException if the class of the specified element
+ * prevents it from being added to this queue
+ * @throws NullPointerException if the specified element is null and
+ * this queue not permit null elements
+ * @throws IllegalArgumentException if some property of this element
+ * prevents it from being added to this queue
+ */
+ public boolean add(Object e) {
+ if (offer(e)) {
+ return true;
+ } else {
+ throw new IllegalStateException("Queue full");
+ }
+ }
+
+ /**
+ * Retrieves and removes the head of this queue. This method differs
+ * from {@link #poll poll} only in that it throws an exception if this
+ * queue is empty.
+ *
+ * <p>This implementation returns the result of <tt>poll</tt>
+ * unless the queue is empty.
+ *
+ * @return the head of this queue
+ * @throws NoSuchElementException if this queue is empty
+ */
+ public Object remove() {
+ Object x = poll();
+
+ if (x != null) {
+ return x;
+ } else {
+ throw new NoSuchElementException();
+ }
+ }
+
+ /**
+ * Retrieves, but does not remove, the head of this queue. This method
+ * differs from {@link #peek peek} only in that it throws an exception if
+ * this queue is empty.
+ *
+ * <p>This implementation returns the result of <tt>peek</tt>
+ * unless the queue is empty.
+ *
+ * @return the head of this queue
+ * @throws NoSuchElementException if this queue is empty
+ */
+ public Object element() {
+ Object x = peek();
+
+ if (x != null) {
+ return x;
+ } else {
+ throw new NoSuchElementException();
+ }
+ }
+
+ /**
+ * Removes all of the elements from this queue.
+ * The queue will be empty after this call returns.
+ *
+ * <p>This implementation repeatedly invokes {@link #poll poll} until it
+ * returns <tt>null</tt>.
+ */
+ public void clear() {
+ while (poll() != null)
+ ;
+ }
+
+ /**
+ * Adds all of the elements in the specified collection to this
+ * queue. Attempts to addAll of a queue to itself result in
+ * <tt>IllegalArgumentException</tt>. Further, the behavior of
+ * this operation is undefined if the specified collection is
+ * modified while the operation is in progress.
+ *
+ * <p>This implementation iterates over the specified collection,
+ * and adds each element returned by the iterator to this
+ * queue, in turn. A runtime exception encountered while
+ * trying to add an element (including, in particular, a
+ * <tt>null</tt> element) may result in only some of the elements
+ * having been successfully added when the associated exception is
+ * thrown.
+ *
+ * @param c collection containing elements to be added to this queue
+ * @return <tt>true</tt> if this queue changed as a result of the call
+ * @throws ClassCastException if the class of an element of the specified
+ * collection prevents it from being added to this queue
+ * @throws NullPointerException if the specified collection contains a
+ * null element and this queue does not permit null elements,
+ * or if the specified collection is null
+ * @throws IllegalArgumentException if some property of an element of the
+ * specified collection prevents it from being added to this
+ * queue, or if the specified collection is this queue
+ * @throws IllegalStateException if not all the elements can be added at
+ * this time due to insertion restrictions
+ * @see #add(Object)
+ */
+ public boolean addAll(Collection c) {
+ if (c == null) {
+ throw new NullPointerException();
+ }
+
+ if (c == this) {
+ throw new IllegalArgumentException();
+ }
+
+ boolean modified = false;
+ Iterator e = c.iterator();
+
+ while (e.hasNext()) {
+ if (add(e.next())) {
+ modified = true;
+ }
+ }
+
+ return modified;
+ }
+}
Propchange: incubator/openjpa/trunk/openjpa-lib/main/java/org/apache/openjpa/lib/util/concurrent/AbstractQueue.java
------------------------------------------------------------------------------
svn:executable = *