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/07/01 00:37:29 UTC
svn commit: r418401 [18/32] - in /incubator/openjpa/trunk: openjpa-lib/
openjpa-lib/src/main/java/org/apache/openjpa/lib/ant/
openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/
openjpa-lib/src/main/java/org/apache/openjpa/lib/jdbc/ openjpa-lib/src/...
Modified: incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/concurrent/Utils.java
URL: http://svn.apache.org/viewvc/incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/concurrent/Utils.java?rev=418401&r1=418400&r2=418401&view=diff
==============================================================================
--- incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/concurrent/Utils.java (original)
+++ incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/concurrent/Utils.java Fri Jun 30 15:37:18 2006
@@ -1,82 +1,72 @@
/*
* Copyright 2006 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
+ * 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
+ * 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 code written by Doug Lea with assistance
* from members of JCP JSR-166 Expert Group. Released to the public domain,
* as explained at http://creativecommons.org/licenses/publicdomain.
- *
- * Thanks to Craig Mattocks for suggesting to use <code>sun.misc.Perf</code>.
+ * Thanks to Craig Mattocks for suggesting to use <code>sun.misc.Perf</code>.
*/
+
package org.apache.openjpa.lib.util.concurrent;
import java.lang.reflect.Array;
-
import java.security.AccessController;
import java.security.PrivilegedAction;
-
import java.util.Collection;
import java.util.Iterator;
-
/**
- * <p>
- * This class groups together the functionality of java.util.concurrent that
+ * This class groups together the functionality of java.util.concurrent that
* cannot be fully and reliably implemented in backport, but for which some
* form of emulation is possible.
- * <p>
- * Currently, this class contains methods related to nanosecond-precision
+ * Currently, this class contains methods related to nanosecond-precision
* timing, particularly via the {@link #nanoTime} method. To measure time
* accurately, this method by default uses <code>java.sun.Perf</code> on
* JDK1.4.2 and it falls back to <code>System.currentTimeMillis</code>
* on earlier JDKs.
- *
+ *
* @author Dawid Kurzyniec
* @version 1.0
*/
public final class Utils {
+
private final static NanoTimer nanoTimer;
- private final static String providerProp = "edu.emory.mathcs.backport.java.util.concurrent.NanoTimerProvider";
+ private final static String providerProp =
+ "edu.emory.mathcs.backport.java.util.concurrent.NanoTimerProvider";
static {
NanoTimer timer = null;
-
try {
- String nanoTimerClassName = (String) AccessController.doPrivileged(new PrivilegedAction() {
- public Object run() {
- return System.getProperty(providerProp);
- }
- });
-
+ String nanoTimerClassName = (String)
+ AccessController.doPrivileged(new PrivilegedAction() {
+ public Object run() {
+ return System.getProperty(providerProp);
+ }
+ });
if (nanoTimerClassName != null) {
Class cls = Class.forName(nanoTimerClassName);
timer = (NanoTimer) cls.newInstance();
}
} catch (Exception e) {
- System.err.println(
- "WARNING: unable to load the system-property-defined " +
- "nanotime provider; switching to the default");
+ System.err.println("WARNING: unable to load the system-property-defined " +
+ "nanotime provider; switching to the default");
e.printStackTrace();
}
if (timer == null) {
try {
timer = new SunPerfProvider();
- } catch (Throwable e) {
- }
+ } catch (Throwable e) {}
}
if (timer == null) {
@@ -86,21 +76,20 @@
nanoTimer = timer;
}
- private Utils() {
- }
+ private Utils() {}
/**
* Returns the current value of the most precise available system timer,
* in nanoseconds. This method can only be used to measure elapsed time and
* is not related to any other notion of system or wall-clock time. The
* value returned represents nanoseconds since some fixed but arbitrary
- * time (perhaps in the future, so values may be negative). This method
+ * time(perhaps in the future, so values may be negative). This method
* provides nanosecond precision, but not necessarily nanosecond accuracy.
* No guarantees are made about how frequently values change. Differences
* in successive calls that span greater than approximately 292 years
* (2^63 nanoseconds) will not accurately compute elapsed time due to
* numerical overflow.
- * <p>
+ *
* <em>Implementation note:</em>By default, this method uses
* <code>sun.misc.Perf</code> on Java 1.4.2, and falls back to
* System.currentTimeMillis() emulation on earlier JDKs. Custom
@@ -108,10 +97,9 @@
* <code>edu.emory.mathcs.backport.java.util.concurrent.NanoTimerProvider</code>.
* The value of the property should name a class implementing
* {@link NanoTimer} interface.
- * <p>
- * Note: on JDK 1.4.2, <code>sun.misc.Perf</code> timer seems to have
+ * Note: on JDK 1.4.2, <code>sun.misc.Perf</code> timer seems to have
* resolution of the order of 1 microsecond, measured on Linux.
- *
+ *
* @return The current value of the system timer, in nanoseconds.
*/
public static long nanoTime() {
@@ -127,8 +115,7 @@
* support for nanosecond-precision wait queues, which are not usually
* present in JVMs prior to 1.5. Loss of precision may cause total waiting
* times to be systematically shorter than specified when re-waits occur.
- *
- * <p>The lock associated with this condition is atomically
+ * The lock associated with this condition is atomically
* released and the current thread becomes disabled for thread scheduling
* purposes and lies dormant until <em>one</em> of five things happens:
* <ul>
@@ -146,12 +133,10 @@
* <li>The specified waiting time elapses; or
* <li>A "<em>spurious wakeup</em>" occurs.
* </ul>
- *
- * <p>In all cases, before this method can return the current thread must
+ * In all cases, before this method can return the current thread must
* re-acquire the lock associated with this condition. When the
* thread returns it is <em>guaranteed</em> to hold this lock.
- *
- * <p>If the current thread:
+ * If the current thread:
* <ul>
* <li>has its interrupted status set on entry to this method; or
* <li>is {@link Thread#interrupt interrupted} while waiting
@@ -161,8 +146,7 @@
* interrupted status is cleared. It is not specified, in the first
* case, whether or not the test for interruption occurs before the lock
* is released.
- *
- * <p>The method returns an estimate of the number of nanoseconds
+ * The method returns an estimate of the number of nanoseconds
* remaining to wait given the supplied <tt>nanosTimeout</tt>
* value upon return, or a value less than or equal to zero if it
* timed out. Accuracy of this estimate is directly dependent on the
@@ -170,65 +154,109 @@
* whether and how long to re-wait in cases where the wait returns but an
* awaited condition still does not hold. Typical uses of this method take
* the following form:
- *
- * <pre>
- * synchronized boolean aMethod(long timeout, TimeUnit unit) {
- * long nanosTimeout = unit.toNanos(timeout);
- * while (!conditionBeingWaitedFor) {
- * if (nanosTimeout > 0)
- * nanosTimeout = theCondition.awaitNanos(nanosTimeout);
- * else
- * return false;
- * }
- * // ...
- * }
+ *
+ * <pre> synchronized boolean aMethod(long timeout, TimeUnit unit) {
+ * long nanosTimeout = unit.toNanos(timeout);
+ * while (!conditionBeingWaitedFor) { if (nanosTimeout > 0)
+ * nanosTimeout = theCondition.awaitNanos(nanosTimeout); else return false;
+ * } // ... }
* </pre>
- *
- * <p><b>Implementation Considerations</b>
- * <p>The current thread is assumed to hold the lock associated with this
+ *
+ * <b>Implementation Considerations</b>
+ * The current thread is assumed to hold the lock associated with this
* <tt>Condition</tt> when this method is called.
* It is up to the implementation to determine if this is
* the case and if not, how to respond. Typically, an exception will be
- * thrown (such as {@link IllegalMonitorStateException}) and the
+ * thrown(such as {@link IllegalMonitorStateException}) and the
* implementation must document that fact.
- *
- * <p>A condition implementation can favor responding to an interrupt over
+ * A condition implementation can favor responding to an interrupt over
* normal method return in response to a signal, or over indicating the
* elapse of the specified waiting time. In either case the implementation
* must ensure that the signal is redirected to another waiting thread, if
* there is one.
- *
+ *
* @param cond the condition to wait for
* @param nanosTimeout the maximum time to wait, in nanoseconds
* @return A value less than or equal to zero if the wait has
* timed out; otherwise an estimate, that
* is strictly less than the <tt>nanosTimeout</tt> argument,
* of the time still remaining when this method returned.
- *
- * @throws InterruptedException if the current thread is interrupted (and
+ *
+ * @throws InterruptedException if the current thread is interrupted(and
* interruption of thread suspension is supported).
*/
public static long awaitNanos(Condition cond, long nanosTimeout)
throws InterruptedException {
- if (nanosTimeout <= 0) {
- return nanosTimeout;
- }
-
+ if (nanosTimeout <= 0) return nanosTimeout;
long now = nanoTime();
cond.await(nanosTimeout, TimeUnit.NANOSECONDS);
-
return nanosTimeout - (nanoTime() - now);
}
- private static long gcd(long a, long b) {
- long r;
+ private static final class SunPerfProvider implements NanoTimer {
+ final sun.misc.Perf perf;
+ final long multiplier, divisor;
+ SunPerfProvider() {
+ perf = (sun.misc.Perf)
+ AccessController.doPrivileged(new PrivilegedAction() {
+ public Object run() {
+ return sun.misc.Perf.getPerf();
+ }
+ });
+ // trying to avoid BOTH overflow and rounding errors
+ long numerator = 1000000000;
+ long denominator = perf.highResFrequency();
+ long gcd = gcd(numerator, denominator);
+ this.multiplier = numerator / gcd;
+ this.divisor = denominator / gcd;
+ }
+ public long nanoTime() {
+ long ctr = perf.highResCounter();
+
+ // anything less sophisticated suffers either from rounding errors
+ // (FP arithmetics, backport v1.0) or overflow, when gcd is small
+ // (a bug in backport v1.0_01 reported by Ramesh Nethi)
+
+ return((ctr / divisor) * multiplier) +
+ (ctr % divisor) * multiplier / divisor;
+
+ // even the above can theoretically cause problems if your JVM is
+ // running for sufficiently long time, but "sufficiently" means 292
+ // years(worst case), or 30,000 years(common case).
- while (b > 0) {
- r = a % b;
- a = b;
- b = r;
+ // Details: when the ticks ctr overflows, there is no way to avoid
+ // discontinuity in computed nanos, even in infinite arithmetics,
+ // unless we count number of overflows that the ctr went through
+ // since the JVM started. This follows from the fact that
+ // (2^64*multiplier/divisor) mod(2^64) > 0 in general case.
+ // Theoretically we could find out the number of overflows by
+ // checking System.currentTimeMillis(), but this is unreliable
+ // since the system time can unpredictably change during the JVM
+ // lifetime.
+ // The time to overflow is 2^63 / ticks frequency. With current
+ // ticks frequencies of several MHz, it gives about 30,000 years
+ // before the problem happens. If ticks frequency reaches 1 GHz, the
+ // time to overflow is 292 years. It is unlikely that the frequency
+ // ever exceeds 1 GHz. We could double the time to overflow
+ // (to 2^64 / frequency) by using unsigned arithmetics, e.g. by
+ // adding the following correction whenever the ticks is negative:
+ // -2*((Long.MIN_VALUE / divisor) * multiplier +
+ // (Long.MIN_VALUE % divisor) * multiplier / divisor)
+ // But, with the worst case of as much as 292 years, it does not
+ // seem justified.
+ }
+ }
+
+ private static final class MillisProvider implements NanoTimer {
+ MillisProvider() {}
+ public long nanoTime() {
+ return System.currentTimeMillis() * 1000000;
}
+ }
+ private static long gcd(long a, long b) {
+ long r;
+ while (b>0) { r = a % b; a = b; b = r; }
return a;
}
@@ -238,24 +266,17 @@
Object[] arr = new Object[len];
Iterator itr = c.iterator();
int idx = 0;
-
while (true) {
- while ((idx < len) && itr.hasNext()) {
+ while (idx < len && itr.hasNext()) {
arr[idx++] = itr.next();
}
-
if (!itr.hasNext()) {
- if (idx == len) {
- return arr;
- }
-
+ if (idx == len) return arr;
// otherwise have to trim
return Arrays.copyOf(arr, idx, Object[].class);
}
-
// otherwise, have to grow
- int newcap = ((arr.length / 2) + 1) * 3;
-
+ int newcap = ((arr.length/2)+1)*3;
if (newcap < arr.length) {
// overflow
if (arr.length < Integer.MAX_VALUE) {
@@ -264,7 +285,6 @@
throw new OutOfMemoryError("required array size too large");
}
}
-
arr = Arrays.copyOf(arr, newcap, Object[].class);
len = newcap;
}
@@ -272,39 +292,29 @@
public static Object[] collectionToArray(Collection c, Object[] a) {
Class aType = a.getClass();
-
// guess the array size; expect to possibly be different
int len = c.size();
- Object[] arr = ((a.length >= len) ? a
- : (Object[]) Array.newInstance(aType.getComponentType(),
- len));
+ Object[] arr = (a.length >= len ? a :
+ (Object[])Array.newInstance(aType.getComponentType(), len));
Iterator itr = c.iterator();
int idx = 0;
-
while (true) {
- while ((idx < len) && itr.hasNext()) {
+ while (idx < len && itr.hasNext()) {
arr[idx++] = itr.next();
}
-
if (!itr.hasNext()) {
- if (idx == len) {
- return arr;
- }
-
+ if (idx == len) return arr;
if (arr == a) {
// orig array -> null terminate
a[idx] = null;
-
return a;
} else {
// have to trim
return Arrays.copyOf(arr, idx, aType);
}
}
-
// otherwise, have to grow
- int newcap = ((arr.length / 2) + 1) * 3;
-
+ int newcap = ((arr.length/2)+1)*3;
if (newcap < arr.length) {
// overflow
if (arr.length < Integer.MAX_VALUE) {
@@ -313,74 +323,8 @@
throw new OutOfMemoryError("required array size too large");
}
}
-
arr = Arrays.copyOf(arr, newcap, aType);
len = newcap;
- }
- }
-
- private static final class SunPerfProvider implements NanoTimer {
- final sun.misc.Perf perf;
- final long multiplier;
- final long divisor;
-
- SunPerfProvider() {
- perf = (sun.misc.Perf) AccessController.doPrivileged(new PrivilegedAction() {
- public Object run() {
- return sun.misc.Perf.getPerf();
- }
- });
-
- // trying to avoid BOTH overflow and rounding errors
- long numerator = 1000000000;
- long denominator = perf.highResFrequency();
- long gcd = gcd(numerator, denominator);
- this.multiplier = numerator / gcd;
- this.divisor = denominator / gcd;
- }
-
- public long nanoTime() {
- long ctr = perf.highResCounter();
-
- // anything less sophisticated suffers either from rounding errors
- // (FP arithmetics, backport v1.0) or overflow, when gcd is small
- // (a bug in backport v1.0_01 reported by Ramesh Nethi)
- return ((ctr / divisor) * multiplier) +
- (((ctr % divisor) * multiplier) / divisor);
-
- // even the above can theoretically cause problems if your JVM is
- // running for sufficiently long time, but "sufficiently" means 292
- // years (worst case), or 30,000 years (common case).
-
- // Details: when the ticks ctr overflows, there is no way to avoid
- // discontinuity in computed nanos, even in infinite arithmetics,
- // unless we count number of overflows that the ctr went through
- // since the JVM started. This follows from the fact that
- // (2^64*multiplier/divisor) mod (2^64) > 0 in general case.
- // Theoretically we could find out the number of overflows by
- // checking System.currentTimeMillis(), but this is unreliable
- // since the system time can unpredictably change during the JVM
- // lifetime.
- // The time to overflow is 2^63 / ticks frequency. With current
- // ticks frequencies of several MHz, it gives about 30,000 years
- // before the problem happens. If ticks frequency reaches 1 GHz, the
- // time to overflow is 292 years. It is unlikely that the frequency
- // ever exceeds 1 GHz. We could double the time to overflow
- // (to 2^64 / frequency) by using unsigned arithmetics, e.g. by
- // adding the following correction whenever the ticks is negative:
- // -2*((Long.MIN_VALUE / divisor) * multiplier +
- // (Long.MIN_VALUE % divisor) * multiplier / divisor)
- // But, with the worst case of as much as 292 years, it does not
- // seem justified.
- }
- }
-
- private static final class MillisProvider implements NanoTimer {
- MillisProvider() {
- }
-
- public long nanoTime() {
- return System.currentTimeMillis() * 1000000;
}
}
}
Modified: incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/concurrent/WaitQueue.java
URL: http://svn.apache.org/viewvc/incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/concurrent/WaitQueue.java?rev=418401&r1=418400&r2=418401&view=diff
==============================================================================
--- incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/concurrent/WaitQueue.java (original)
+++ incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/concurrent/WaitQueue.java Fri Jun 30 15:37:18 2006
@@ -1,19 +1,15 @@
/*
* Copyright 2006 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
+ * 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
+ * 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.
*/
-
/*
* Originally written by Doug Lea and released into the public domain.
* This may be used for any purposes whatsoever without acknowledgment.
@@ -24,29 +20,24 @@
import java.util.*;
-
/**
* Base class for internal queue classes for semaphores, etc.
* Relies on subclasses to actually implement queue mechanics.
* NOTE: this class is NOT present in java.util.concurrent.
*/
public abstract class WaitQueue {
- public abstract void insert(WaitNode w); // assumed not to block
+ public abstract void insert(WaitNode w); // assumed not to block
public abstract WaitNode extract(); // should return null if empty
public abstract boolean hasNodes();
-
public abstract int getLength();
-
public abstract Collection getWaitingThreads();
-
public abstract boolean isWaiting(Thread thread);
public static interface QueuedSync {
// invoked with sync on wait node, (atomically) just before enqueuing
boolean recheck(WaitNode node);
-
// invoked with sync on wait node, (atomically) just before signalling
void takeOver(WaitNode node);
}
@@ -66,40 +57,32 @@
public synchronized boolean signal(QueuedSync sync) {
boolean signalled = waiting;
-
if (signalled) {
waiting = false;
notify();
sync.takeOver(this);
}
-
return signalled;
}
public synchronized boolean doTimedWait(QueuedSync sync, long nanos)
throws InterruptedException {
- if (sync.recheck(this) || !waiting) {
+ if (sync.recheck(this) || !waiting)
return true;
- } else if (nanos <= 0) {
+ else if (nanos <= 0) {
waiting = false;
-
return false;
} else {
long deadline = Utils.nanoTime() + nanos;
-
try {
- for (;;) {
+ for (; ; ) {
TimeUnit.NANOSECONDS.timedWait(this, nanos);
-
- if (!waiting) { // definitely signalled
-
+ if (!waiting) // definitely signalled
return true;
- } else {
+ else {
nanos = deadline - Utils.nanoTime();
-
if (nanos <= 0) { // timed out
waiting = false;
-
return false;
}
}
@@ -110,7 +93,6 @@
throw ex;
} else { // thread was interrupted after it was notified
Thread.currentThread().interrupt();
-
return true;
}
}
@@ -121,15 +103,13 @@
throws InterruptedException {
if (!sync.recheck(this)) {
try {
- while (waiting)
- wait();
+ while (waiting) wait();
} catch (InterruptedException ex) {
if (waiting) { // no notification
waiting = false; // invalidate for the signaller
throw ex;
} else { // thread was interrupted after it was notified
Thread.currentThread().interrupt();
-
return;
}
}
@@ -139,24 +119,22 @@
public synchronized void doWaitUninterruptibly(QueuedSync sync) {
if (!sync.recheck(this)) {
boolean wasInterrupted = Thread.interrupted();
-
try {
while (waiting) {
try {
wait();
} catch (InterruptedException ex) {
wasInterrupted = true;
-
// no need to notify; if we were signalled, we
// must be not waiting, and we'll act like signalled
}
}
- } finally {
- if (wasInterrupted) {
- Thread.currentThread().interrupt();
- }
+ }
+ finally {
+ if (wasInterrupted) Thread.currentThread().interrupt();
}
}
}
}
}
+
Modified: incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/xml/Commentable.java
URL: http://svn.apache.org/viewvc/incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/xml/Commentable.java?rev=418401&r1=418400&r2=418401&view=diff
==============================================================================
--- incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/xml/Commentable.java (original)
+++ incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/xml/Commentable.java Fri Jun 30 15:37:18 2006
@@ -1,13 +1,10 @@
/*
* Copyright 2006 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
+ * 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
+ * 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
@@ -15,22 +12,22 @@
*/
package org.apache.openjpa.lib.xml;
-
/**
- * Implementations of this interface can be adorned with comments.
- *
- * @since 3.3
- * @nojavadoc */
+ * Implementations of this interface can be adorned with comments.
+ *
+ * @since 3.3
+ * @nojavadoc
+ */
public interface Commentable {
public static final String[] EMPTY_COMMENTS = new String[0];
/**
- * Set comments.
+ * Set comments.
*/
public void setComments(String[] comments);
/**
- * Return comments, or empty array if none.
+ * Return comments, or empty array if none.
*/
public String[] getComments();
}
Modified: incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/xml/DocTypeReader.java
URL: http://svn.apache.org/viewvc/incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/xml/DocTypeReader.java?rev=418401&r1=418400&r2=418401&view=diff
==============================================================================
--- incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/xml/DocTypeReader.java (original)
+++ incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/xml/DocTypeReader.java Fri Jun 30 15:37:18 2006
@@ -1,13 +1,10 @@
/*
* Copyright 2006 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
+ * 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
+ * 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
@@ -17,50 +14,47 @@
import java.io.*;
-
/**
- * <p>The DocTypeReader can be used to dynamically include a
- * <code>DOCTYPE</code> declaration in an XML stream. Often it is
- * inconvenient to specify a <code>DOCTYPE</code> in XML files -- you many
- * want the option of parsing the files without reading the DTD, the files
- * may move around, making placing a <code>DOCTYPE</code> path to the DTD in
- * them unattractive, and you may have many files, making an in-line include
- * of the DTD unattractive as well. This class makes
- * it possible to maintain XML files without any <code>DOCTYPE</code>
- * declaration, then dynamically include the <code>DOCTYPE</code> information
- * at runtime.</p>
- *
- * <p>If the XML stream already contains a <code>DOCTYPE</code> declaration,
- * the reader will not add an additional one.</p>
- *
- * <p>The <code>DOCTYPE</code> information given to the reader will be placed
- * in the XML stream it wraps just before the root element of the document.</p>
- *
- * <p>Note that all methods other than the various forms of <code>read</code>
- * apply onto the underlying XML stream and should not be used until the
- * header and doc type have been read.</p>
- *
- * @author Abe White
- * @nojavadoc */
+ * The DocTypeReader can be used to dynamically include a
+ * <code>DOCTYPE</code> declaration in an XML stream. Often it is
+ * inconvenient to specify a <code>DOCTYPE</code> in XML files -- you many
+ * want the option of parsing the files without reading the DTD, the files
+ * may move around, making placing a <code>DOCTYPE</code> path to the DTD in
+ * them unattractive, and you may have many files, making an in-line include
+ * of the DTD unattractive as well. This class makes
+ * it possible to maintain XML files without any <code>DOCTYPE</code>
+ * declaration, then dynamically include the <code>DOCTYPE</code> information
+ * at runtime.
+ * If the XML stream already contains a <code>DOCTYPE</code> declaration,
+ * the reader will not add an additional one.
+ * The <code>DOCTYPE</code> information given to the reader will be placed
+ * in the XML stream it wraps just before the root element of the document.
+ * Note that all methods other than the various forms of <code>read</code>
+ * apply onto the underlying XML stream and should not be used until the
+ * header and doc type have been read.
+ *
+ * @author Abe White
+ * @nojavadoc
+ */
public class DocTypeReader extends Reader {
private Reader _xml = null;
private Reader _docType = null;
- // use to hold all header information until the doctype dec should be
+ // use to hold all header information until the doctype dec should be
// inserted
private char[] _header = null;
private int _headerPos = 0;
/**
- * Construct the reader with an XML stream, and set the
- * <code>DOCTYPE</code> information to be included. The given
- * reader should access an input source containing the exact declaration
- * to include, such as:<br />
- * <code><DOCTYPE schedule SYSTEM "schedule.dtd"></code><br />
- * <code><DOCTYPE html PUBLIC "-//W3C//DTD XHTML ...></code><br />
- * <code><DOCTYPE stock-price [ <ELEMENT symb ... ]></code><br />
- * If the reader is null, no <code>DOCTYPE</code> information will be
- * included in the stream.
+ * Construct the reader with an XML stream, and set the
+ * <code>DOCTYPE</code> information to be included. The given
+ * reader should access an input source containing the exact declaration
+ * to include, such as:<br />
+ * <code><DOCTYPE schedule SYSTEM "schedule.dtd"></code><br />
+ * <code><DOCTYPE html PUBLIC "-//W3C//DTD XHTML ...></code><br />
+ * <code><DOCTYPE stock-price [ <ELEMENT symb ... ]></code><br />
+ * If the reader is null, no <code>DOCTYPE</code> information will be
+ * included in the stream.
*/
public DocTypeReader(Reader xml, Reader docType) throws IOException {
_docType = docType;
@@ -69,16 +63,12 @@
public int read() throws IOException {
int ch = readHeader();
-
- if (ch != -1) {
+ if (ch != -1)
return ch;
- }
ch = readDocType();
-
- if (ch != -1) {
+ if (ch != -1)
return ch;
- }
return _xml.read();
}
@@ -121,77 +111,64 @@
public void close() throws IOException {
_xml.close();
-
- if (_docType != null) {
+ if (_docType != null)
_docType.close();
- }
}
/**
- * Buffer all text until the doc type declaration should be inserted.
+ * Buffer all text until the doc type declaration should be inserted.
*/
private Reader bufferHeader(Reader origXML) throws IOException {
// don't bother if no doc type declaration
if (_docType == null) {
_header = new char[0];
-
return origXML;
}
// create buffer
StringWriter writer = new StringWriter();
PushbackReader xml = new PushbackReader(origXML, 3);
- int ch;
- int ch2;
- int ch3;
+ int ch, ch2, ch3;
boolean comment;
while (true) {
// read leading space
- for (ch = xml.read();
- (ch != -1) && Character.isWhitespace((char) ch);
- ch = xml.read())
+ for (ch = xml.read(); ch != -1
+ && Character.isWhitespace((char) ch); ch = xml.read())
writer.write(ch);
-
- if (ch == -1) {
+ if (ch == -1)
return headerOnly(writer.toString());
- }
// if not XML, finish
if (ch != '<') {
xml.unread(ch);
_header = writer.toString().toCharArray();
-
return xml;
}
// if the root element, finish
ch = xml.read();
-
- if ((ch != '?') && (ch != '!')) {
+ if (ch != '?' && ch != '!') {
xml.unread(ch);
xml.unread('<');
_header = writer.toString().toCharArray();
-
return xml;
}
// if a doc type element, finish
ch2 = xml.read();
-
- if ((ch == '!') && (ch2 == 'D')) {
+ if (ch == '!' && ch2 == 'D') {
xml.unread(ch2);
xml.unread(ch);
xml.unread('<');
_header = writer.toString().toCharArray();
_docType = null; // make sure doc type not included
-
return xml;
}
// is this a comment?
ch3 = xml.read();
- comment = (ch == '!') && (ch2 == '-') && (ch3 == '-');
+ comment = ch == '!' && ch2 == '-' && ch3 == '-';
// place everything read into the header material
writer.write('<');
@@ -202,112 +179,88 @@
// read until the next '>' or '-->' if a comment
ch2 = 0;
ch3 = 0;
-
while ((ch = xml.read()) != -1) {
writer.write(ch);
- if ((!comment && (ch == '>')) ||
- (comment && (ch == '>') && (ch2 == '-') &&
- (ch3 == '-'))) {
+ if ((!comment && ch == '>')
+ || (comment && ch == '>' && ch2 == '-' && ch3 == '-'))
break;
- }
// track last two chars so we can tell if comment is ending
ch3 = ch2;
ch2 = ch;
}
-
- if (ch == -1) {
+ if (ch == -1)
return headerOnly(writer.toString());
- }
// read the space after the declaration
- for (ch = xml.read();
- (ch != -1) && Character.isWhitespace((char) ch);
- ch = xml.read())
+ for (ch = xml.read(); ch != -1
+ && Character.isWhitespace((char) ch); ch = xml.read())
writer.write(ch);
-
- if (ch == -1) {
+ if (ch == -1)
return headerOnly(writer.toString());
- }
-
xml.unread(ch);
}
}
/**
- * If the stream contained only space, think of it as pure XML with no
- * header for consistency with the other methods.
+ * If the stream contained only space, think of it as pure XML with no
+ * header for consistency with the other methods.
*/
private Reader headerOnly(String header) {
_header = new char[0];
_docType = null;
-
return new StringReader(header);
}
/**
- * Return a single character from the buffered header, or -1 if none.
+ * Return a single character from the buffered header, or -1 if none.
*/
private int readHeader() {
- if (_headerPos == _header.length) {
+ if (_headerPos == _header.length)
return -1;
- }
-
return _header[_headerPos++];
}
/**
- * Read from the buffered header to the given array, returning the
- * number of characters read.
+ * Read from the buffered header to the given array, returning the
+ * number of characters read.
*/
private int readHeader(char[] buf, int off, int len) {
int read = 0;
-
- for (; (len > 0) && (_headerPos < _header.length);
- read++, off++, len--)
+ for (; len > 0 && _headerPos < _header.length; read++, off++, len--)
buf[off] = _header[_headerPos++];
return read;
}
/**
- * Return a single character from the doc type declaration, or -1
- * if none.
+ * Return a single character from the doc type declaration, or -1 if none.
*/
private int readDocType() throws IOException {
- if (_docType == null) {
+ if (_docType == null)
return -1;
- }
int ch = _docType.read();
-
- if (ch == -1) {
+ if (ch == -1)
_docType = null;
- }
return ch;
}
/**
- * Read from the doc type declaration to the given array, returning the
- * number of characters read.
+ * Read from the doc type declaration to the given array, returning the
+ * number of characters read.
*/
- private int readDocType(char[] buf, int off, int len)
- throws IOException {
- if (_docType == null) {
+ private int readDocType(char[] buf, int off, int len) throws IOException {
+ if (_docType == null)
return 0;
- }
int read = _docType.read(buf, off, len);
-
- if (read < len) {
+ if (read < len)
_docType = null;
- }
-
- if (read == -1) {
+ if (read == -1)
read = 0;
- }
return read;
}
Modified: incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/xml/Location.java
URL: http://svn.apache.org/viewvc/incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/xml/Location.java?rev=418401&r1=418400&r2=418401&view=diff
==============================================================================
--- incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/xml/Location.java (original)
+++ incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/xml/Location.java Fri Jun 30 15:37:18 2006
@@ -1,13 +1,10 @@
/*
* Copyright 2006 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
+ * 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
+ * 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
@@ -15,20 +12,18 @@
*/
package org.apache.openjpa.lib.xml;
+import java.text.*;
import org.apache.openjpa.lib.util.*;
-
import org.xml.sax.*;
-
import serp.util.*;
-import java.text.*;
-
-
/**
- * @author Stephen Kim
- * @nojavadoc */
+ * @author Stephen Kim
+ * @nojavadoc
+ */
public class Location {
private static final Localizer _loc = Localizer.forPackage(Location.class);
+
private boolean _nullOnNoLocator = false;
private Locator _locator = null;
@@ -45,20 +40,14 @@
*/
public String getLocation(String format) {
if (_locator == null) {
- if (_nullOnNoLocator) {
+ if (_nullOnNoLocator)
return null;
- }
-
return _loc.get("no-locator");
}
-
- String forma = MessageFormat.format(format,
- new Object[] {
- Numbers.valueOf(_locator.getLineNumber()),
- Numbers.valueOf(_locator.getColumnNumber()),
- _locator.getPublicId(), _locator.getSystemId()
- });
-
+ String forma = MessageFormat.format(format, new Object [] {
+ Numbers.valueOf(_locator.getLineNumber()),
+ Numbers.valueOf(_locator.getColumnNumber()), _locator.getPublicId(),
+ _locator.getSystemId()});
return forma;
}
Modified: incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/xml/ValidatingErrorHandler.java
URL: http://svn.apache.org/viewvc/incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/xml/ValidatingErrorHandler.java?rev=418401&r1=418400&r2=418401&view=diff
==============================================================================
--- incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/xml/ValidatingErrorHandler.java (original)
+++ incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/xml/ValidatingErrorHandler.java Fri Jun 30 15:37:18 2006
@@ -1,13 +1,10 @@
/*
* Copyright 2006 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
+ * 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
+ * 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
@@ -17,15 +14,14 @@
import org.xml.sax.*;
-
/**
- * <p>ErrorHandler implementation which overrides the default
- * behavior of ignoring parse errors to throw a {@link SAXException} instead.
- * This handler is used by the validating parsers of the
- * {@link XMLFactory}.</p>
- *
- * @author Abe White
- * @nojavadoc */
+ * ErrorHandler implementation which overrides the default
+ * behavior of ignoring parse errors to throw a {@link SAXException} instead.
+ * This handler is used by the validating parsers of the {@link XMLFactory}.
+ *
+ * @author Abe White
+ * @nojavadoc
+ */
public class ValidatingErrorHandler implements ErrorHandler {
public void warning(SAXParseException e) throws SAXException {
throw e;
Modified: incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/xml/XMLFactory.java
URL: http://svn.apache.org/viewvc/incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/xml/XMLFactory.java?rev=418401&r1=418400&r2=418401&view=diff
==============================================================================
--- incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/xml/XMLFactory.java (original)
+++ incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/xml/XMLFactory.java Fri Jun 30 15:37:18 2006
@@ -1,13 +1,10 @@
/*
* Copyright 2006 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
+ * 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
+ * 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
@@ -15,33 +12,29 @@
*/
package org.apache.openjpa.lib.xml;
-import org.apache.commons.lang.exception.*;
-
-import org.w3c.dom.*;
-
-import org.xml.sax.*;
-
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.sax.*;
-
+import org.apache.commons.lang.exception.*;
+import org.w3c.dom.*;
+import org.xml.sax.*;
/**
- * <p>The XMLFactory produces validating and non-validating DOM level 2
- * and SAX level 2 parsers and XSL transformers through JAXP. It uses
- * caching to avoid repeatedly paying the relatively expensive runtime costs
- * associated with resolving the correct XML implementation through the
- * JAXP configuration mechanisms.</p>
- *
- * @author Abe White
- * @nojavadoc */
+ * The XMLFactory produces validating and non-validating DOM level 2
+ * and SAX level 2 parsers and XSL transformers through JAXP. It uses
+ * caching to avoid repeatedly paying the relatively expensive runtime costs
+ * associated with resolving the correct XML implementation through the
+ * JAXP configuration mechanisms.
+ *
+ * @author Abe White
+ * @nojavadoc
+ */
public class XMLFactory {
// cache parsers and transformers in all possible configurations
private static SAXParserFactory[] _saxFactories = null;
private static DocumentBuilderFactory[] _domFactories = null;
private static SAXTransformerFactory _transFactory = null;
private static ErrorHandler _validating;
-
static {
_saxFactories = new SAXParserFactory[4];
_domFactories = new DocumentBuilderFactory[4];
@@ -49,7 +42,6 @@
SAXParserFactory saxFactory;
DocumentBuilderFactory domFactory;
int arrIdx;
-
for (int validating = 0; validating < 2; validating++) {
for (int namespace = 0; namespace < 2; namespace++) {
arrIdx = factoryIndex(validating == 1, namespace == 1);
@@ -66,19 +58,20 @@
}
}
- _transFactory = (SAXTransformerFactory) TransformerFactory.newInstance();
+ _transFactory = (SAXTransformerFactory) TransformerFactory.
+ newInstance();
_validating = new ValidatingErrorHandler();
}
/**
- * Return a SAXParser with the specified configuration.
+ * Return a SAXParser with the specified configuration.
*/
public static SAXParser getSAXParser(boolean validating,
boolean namespaceAware) {
SAXParser sp;
-
try {
- sp = _saxFactories[factoryIndex(validating, namespaceAware)].newSAXParser();
+ sp = _saxFactories[factoryIndex(validating, namespaceAware)].
+ newSAXParser();
} catch (ParserConfigurationException pce) {
throw new NestableRuntimeException(pce);
} catch (SAXException se) {
@@ -97,43 +90,39 @@
}
/**
- * Return a DocumentBuilder with the specified configuration.
+ * Return a DocumentBuilder with the specified configuration.
*/
public static DocumentBuilder getDOMParser(boolean validating,
boolean namespaceAware) {
DocumentBuilder db;
-
try {
- db = _domFactories[factoryIndex(validating, namespaceAware)].newDocumentBuilder();
+ db = _domFactories[factoryIndex(validating, namespaceAware)].
+ newDocumentBuilder();
} catch (ParserConfigurationException pce) {
throw new NestableRuntimeException(pce);
}
- if (validating) {
+ if (validating)
db.setErrorHandler(_validating);
- }
-
return db;
}
/**
- * Return a new DOM Document.
+ * Return a new DOM Document.
*/
public static Document getDocument() {
return getDOMParser(false, false).newDocument();
}
/**
- * Return a Transformer that will apply the XSL transformation
- * from the given source. If the source is null,
- * no transformation will be applied.
+ * Return a Transformer that will apply the XSL transformation
+ * from the given source. If the source is null,
+ * no transformation will be applied.
*/
public static Transformer getTransformer(Source source) {
try {
- if (source == null) {
+ if (source == null)
return _transFactory.newTransformer();
- }
-
return _transFactory.newTransformer(source);
} catch (TransformerConfigurationException tfce) {
throw new NestableRuntimeException(tfce);
@@ -141,7 +130,7 @@
}
/**
- * Return a Templates for the given XSL source.
+ * Return a Templates for the given XSL source.
*/
public static Templates getTemplates(Source source) {
try {
@@ -152,16 +141,14 @@
}
/**
- * Return a TransformerHandler for transforming SAX events, applying the
- * XSL transform from the given source. If the source is null, no
- * transform will be applied.
+ * Return a TransformerHandler for transforming SAX events, applying the
+ * XSL transform from the given source. If the source is null, no
+ * transform will be applied.
*/
public static TransformerHandler getTransformerHandler(Source source) {
try {
- if (source == null) {
+ if (source == null)
return _transFactory.newTransformerHandler();
- }
-
return _transFactory.newTransformerHandler(source);
} catch (TransformerConfigurationException tfce) {
throw new NestableRuntimeException(tfce);
@@ -169,19 +156,14 @@
}
/**
- * Return the array index of the factory with the given properties.
+ * Return the array index of the factory with the given properties.
*/
private static int factoryIndex(boolean validating, boolean namespaceAware) {
int arrayIndex = 0;
-
- if (validating) {
+ if (validating)
arrayIndex += 2;
- }
-
- if (namespaceAware) {
+ if (namespaceAware)
arrayIndex += 1;
- }
-
return arrayIndex;
}
}
Modified: incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/xml/XMLWriter.java
URL: http://svn.apache.org/viewvc/incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/xml/XMLWriter.java?rev=418401&r1=418400&r2=418401&view=diff
==============================================================================
--- incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/xml/XMLWriter.java (original)
+++ incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/xml/XMLWriter.java Fri Jun 30 15:37:18 2006
@@ -1,13 +1,10 @@
/*
* Copyright 2006 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
+ * 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
+ * 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
@@ -17,23 +14,24 @@
import java.io.*;
-
/**
- * <p>The XMLWriter is a writer type for pretty-printing XML.
- * It assumes that the streamed XML will be given without any whitespace,
- * other than the space within text blocks.</p>
- *
- * @author Abe White
- * @nojavadoc */
+ * The XMLWriter is a writer type for pretty-printing XML.
+ * It assumes that the streamed XML will be given without any whitespace,
+ * other than the space within text blocks.
+ *
+ * @author Abe White
+ * @nojavadoc
+ */
public class XMLWriter extends FilterWriter {
private static String _endl = System.getProperty("line.separator");
+
private int _lastChar = ' ';
private int _lastChar2 = ' ';
private int _lastChar3 = ' ';
private int _depth = 0;
/**
- * Construct an XMLWriter that will write to the given stream.
+ * Construct an XMLWriter that will write to the given stream.
*/
public XMLWriter(Writer out) {
super(out);
@@ -51,24 +49,23 @@
public void write(int c) throws IOException {
// the basic idea of this method is to make sure that when a tag
- // or a text block starts, it is placed on a separate line and
+ // or a text block starts, it is placed on a separate line and
// indented an amount appropriate to the XML tree depth
+
if (_lastChar == '<') {
// tag or processing instruction?
- if ((c != '?') && (c != '!')) {
+ if (c != '?' && c != '!') {
// end tag; decrease depth before writing spaces
- if (c == '/') {
+ if (c == '/')
_depth--;
- }
// tags are always on separate lines
out.write(_endl);
writeSpaces();
// beginning tag; increase depth for tag body
- if (c != '/') {
+ if (c != '/')
_depth++;
- }
}
// if this is not a processing instruction / comment,
@@ -79,25 +76,21 @@
}
} else if (c == '>') {
// if unary tag decrease depth to undo the increase at tag start
- if (_lastChar == '/') {
+ if (_lastChar == '/')
_depth--;
- }
// check for the comment-processing conditions
- if ((_lastChar2 == '<') && (_lastChar == '!')) {
+ if (_lastChar2 == '<' && _lastChar == '!')
out.write("<!");
- } else if ((_lastChar3 == '<') && (_lastChar2 == '!') &&
- (_lastChar == '-')) {
+ else if (_lastChar3 == '<' && _lastChar2 == '!' && _lastChar == '-')
out.write("<!-");
- }
out.write('>');
} else if (c != '<') {
// if we're at "<!--", indent and put in the beginning of
// the comment. if it's "<!-?" where ? is something other
// than -, dump what we've gotten so far
- if ((_lastChar3 == '<') && (_lastChar2 == '!') &&
- (_lastChar == '-')) {
+ if (_lastChar3 == '<' && _lastChar2 == '!' && _lastChar == '-') {
if (c == '-') {
out.write(_endl);
writeSpaces();
@@ -108,15 +101,13 @@
}
}
// if we're at "<!-", keep on not writing data
- else if (!((_lastChar2 == '<') && (_lastChar == '!') && (c == '-'))) {
+ else if (!(_lastChar2 == '<' && _lastChar == '!' && c == '-')) {
// if just ended a tag and about to print text, put on
// separate line
- if ((_lastChar == '>') && (_lastChar2 != '?') &&
- (_lastChar2 != '!')) {
+ if (_lastChar == '>' && _lastChar2 != '?' && _lastChar2 != '!') {
out.write(_endl);
writeSpaces();
}
-
out.write(c);
}
}
Added: incubator/openjpa/trunk/openjpa-lib/src/test/java/org/apache/openjpa/lib/conf/TestConfigurations.java
URL: http://svn.apache.org/viewvc/incubator/openjpa/trunk/openjpa-lib/src/test/java/org/apache/openjpa/lib/conf/TestConfigurations.java?rev=418401&view=auto
==============================================================================
--- incubator/openjpa/trunk/openjpa-lib/src/test/java/org/apache/openjpa/lib/conf/TestConfigurations.java (added)
+++ incubator/openjpa/trunk/openjpa-lib/src/test/java/org/apache/openjpa/lib/conf/TestConfigurations.java Fri Jun 30 15:37:18 2006
@@ -0,0 +1,83 @@
+/*
+ * 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.conf;
+
+import org.apache.openjpa.lib.test.*;
+import org.apache.openjpa.lib.util.*;
+import serp.util.*;
+
+/**
+ * Tests the {@link Configurations} class.
+ *
+ * @author Abe White
+ */
+public class TestConfigurations extends AbstractTestCase {
+ public TestConfigurations(String test) {
+ super(test);
+ }
+
+ public void testParsePlugin() {
+ String str = null;
+ assertNull(Configurations.getClassName(str));
+ assertNull(Configurations.getProperties(str));
+ str = "foo";
+ assertEquals("foo", Configurations.getClassName(str));
+ assertNull(Configurations.getProperties(str));
+ str = "a=b";
+ assertNull(Configurations.getClassName(str));
+ assertEquals("a=b", Configurations.getProperties(str));
+ str = "a=b, c=d";
+ assertNull(Configurations.getClassName(str));
+ assertEquals("a=b, c=d", Configurations.getProperties(str));
+ str = "foo(a=b, c=d)";
+ assertEquals("foo", Configurations.getClassName(str));
+ assertEquals("a=b, c=d", Configurations.getProperties(str));
+ str = " foo( a=\"b,c d\", c=\"d\" ) ";
+ assertEquals("foo", Configurations.getClassName(str));
+ assertEquals("a=\"b,c d\", c=\"d\"", Configurations.getProperties(str));
+ str = " foo( a='b,c d', c='d' ) ";
+ assertEquals("foo", Configurations.getClassName(str));
+ assertEquals("a='b,c d', c='d'", Configurations.getProperties(str));
+ }
+
+ public void testParseProperties() {
+ Options opts = Configurations.parseProperties(null);
+ assertEquals(0, opts.size());
+
+ opts = Configurations.parseProperties(" foo=bar, biz=baz ");
+ assertEquals(2, opts.size());
+ assertEquals("bar", opts.getProperty("foo"));
+ assertEquals("baz", opts.getProperty("biz"));
+
+ opts = Configurations.parseProperties("foo=bar,biz=\"baz,=,baz\",x=y");
+ assertEquals(3, opts.size());
+ assertEquals("bar", opts.getProperty("foo"));
+ assertEquals("baz,=,baz", opts.getProperty("biz"));
+ assertEquals("y", opts.getProperty("x"));
+
+ opts = Configurations.parseProperties
+ ("foo=\"bar bar,10\",biz=\"baz baz\"");
+ assertEquals(2, opts.size());
+ assertEquals("bar bar,10", opts.getProperty("foo"));
+ assertEquals("baz baz", opts.getProperty("biz"));
+ opts = Configurations.parseProperties
+ ("foo='bar bar,10',biz='baz baz'");
+ assertEquals(2, opts.size());
+ assertEquals("bar bar,10", opts.getProperty("foo"));
+ assertEquals("baz baz", opts.getProperty("biz"));
+ }
+
+ public static void main(String[] args) {
+ main(TestConfigurations.class);
+ }
+}
Added: incubator/openjpa/trunk/openjpa-lib/src/test/java/org/apache/openjpa/lib/conf/test/TestConfigurationImpl.java
URL: http://svn.apache.org/viewvc/incubator/openjpa/trunk/openjpa-lib/src/test/java/org/apache/openjpa/lib/conf/test/TestConfigurationImpl.java?rev=418401&view=auto
==============================================================================
--- incubator/openjpa/trunk/openjpa-lib/src/test/java/org/apache/openjpa/lib/conf/test/TestConfigurationImpl.java (added)
+++ incubator/openjpa/trunk/openjpa-lib/src/test/java/org/apache/openjpa/lib/conf/test/TestConfigurationImpl.java Fri Jun 30 15:37:18 2006
@@ -0,0 +1,315 @@
+/*
+ * 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.conf.test;
+
+import java.beans.*;
+import java.io.*;
+import java.lang.reflect.*;
+import java.util.*;
+import org.apache.openjpa.lib.conf.*;
+import org.apache.openjpa.lib.test.*;
+import serp.util.*;
+
+/**
+ * Tests the {@link ConfigurationImpl} type, and in so doing tests
+ * the {@link AbstractConfiguration} as well. This needs to be placed
+ * in a sub-package so that it can have its own localizer.properties
+ * properties, which are required for the bean descriptors used by the
+ * configuration framework {@link Value}.
+ *
+ * @author Abe White
+ */
+public class TestConfigurationImpl extends AbstractTestCase {
+ private ConfigurationTest _conf = new ConfigurationTest();
+ private String _def;
+
+ public TestConfigurationImpl(String test) {
+ super(test);
+ }
+
+ public void setUp() {
+ //### any way to avoid hard coding this?
+ _def = System.getProperty("org.apache.openjpa.properties");
+ System.setProperty("org.apache.openjpa.properties", "test.properties");
+ }
+
+ public void tearDown() throws Exception {
+ System.setProperty("org.apache.openjpa.properties", _def);
+
+ super.tearDown();
+ }
+
+ /**
+ * Test that default properties are found and loaded.
+ */
+ public void testDefaults() {
+ System.setProperty("sysKey", "sysvalue");
+ assertNull(_conf.getTestKey());
+ assertNull(_conf.getSysKey());
+ assertNull(_conf.getPluginKey());
+ assertNull(_conf.getObjectKey());
+ assertTrue(_conf.loadDefaults());
+ assertEquals("testvalue", _conf.getTestKey());
+ assertEquals("sysvalue", _conf.getSysKey());
+ assertNull(_conf.getPluginKey());
+ assertNull(_conf.getObjectKey());
+
+ // override the properties location to a non-existant value
+ _conf.setTestKey(null);
+ _conf.setSysKey(null);
+ //###
+ System.setProperty("org.apache.openjpa.properties", "foo.properties");
+ try {
+ assertTrue(!_conf.loadDefaults());
+ fail("Should have thrown exception for missing resource.");
+ } catch (MissingResourceException mre) {
+ }
+
+ // set back for remainder of tests
+ //###
+ System.setProperty("org.apache.openjpa.properties", "test.properties");
+ System.setProperty("pluginKey", "java.lang.Object");
+ assertTrue(_conf.loadDefaults());
+ assertEquals("testvalue", _conf.getTestKey());
+ assertEquals("sysvalue", _conf.getSysKey());
+ assertEquals("java.lang.Object", _conf.getPluginKey());
+ assertNotNull(_conf.getPluginKeyInstance());
+ assertNull(_conf.getObjectKey());
+ }
+
+ /**
+ * Test that the configuration is serialized to properties correctly.
+ */
+ public void testToProperties() {
+ assertTrue(_conf.loadDefaults());
+ assertEquals("testvalue", _conf.getTestKey());
+ Map props = _conf.toProperties(false);
+ assertEquals("testvalue", props.get("testKey"));
+ assertFalse(props.containsKey("objectKey"));
+ _conf.setTestKey("foo");
+ _conf.setPluginKey(new Object());
+ _conf.setObjectKey(new Object());
+ props = _conf.toProperties(false);
+ assertEquals("foo", props.get("testKey"));
+ assertEquals("java.lang.Object", props.get("pluginKey"));
+ assertFalse(props.containsKey("objectKey"));
+ }
+
+ /**
+ * Tests properties caching.
+ */
+ public void testPropertiesCaching() {
+ _conf.setTestKey("val");
+ _conf.setPluginKey("java.lang.Object");
+ Map props1 = _conf.toProperties(false);
+ Map props2 = _conf.toProperties(false);
+ _conf.setObjectKey(new Object());
+ assertNotNull(_conf.getPluginKeyInstance()); // instantiate
+ Map props3 = _conf.toProperties(false);
+ _conf.setTestKey("changed");
+ Map props4 = _conf.toProperties(false);
+ _conf.setPluginKey(new Integer(1));
+ Map props5 = _conf.toProperties(false);
+ assertEquals(props1, props2);
+ assertEquals(props1, props3);
+ assertNotEquals(props1, props4);
+ assertNotEquals(props4, props5);
+ }
+
+ /**
+ * Test the equals method.
+ */
+ public void testEquals() {
+ ConfigurationTest conf = new ConfigurationTest();
+ conf.setTestKey(_conf.getTestKey());
+ conf.setSysKey(_conf.getSysKey());
+ conf.setPluginKey(_conf.getPluginKey());
+ conf.setObjectKey(_conf.getObjectKey());
+ assertEquals(_conf, conf);
+
+ conf.setTestKey("newval");
+ assertTrue(!_conf.equals(conf));
+ conf.setTestKey(_conf.getTestKey());
+ assertEquals(_conf, conf);
+
+ conf.setObjectKey(new Object());
+ assertEquals(_conf, conf);
+
+ conf.setPluginKey(new StringBuffer());
+ assertTrue(!_conf.equals(conf));
+ }
+
+ /**
+ * Test using bean introspection.
+ */
+ public void testBeanAccessors() throws Exception {
+ PropertyDescriptor[] pds = _conf.getPropertyDescriptors();
+ for (int i = 0; i < pds.length; i++) {
+ assertNotNull(pds[i].getShortDescription());
+ assertNotNull(pds[i].getDisplayName());
+
+ assertNotNull(pds[i].getWriteMethod());
+ assertNotNull(pds[i].getReadMethod());
+
+ pds[i].getReadMethod().invoke(_conf, (Object[]) null);
+
+ Method setter = pds[i].getWriteMethod();
+ Method getter = pds[i].getReadMethod();
+ Class param = pds[i].getReadMethod().getReturnType();
+
+ Object setVal = null;
+ if (param == int.class)
+ setVal = randomInt();
+ else if (param == long.class)
+ setVal = randomLong();
+ else if (param == String.class)
+ setVal = randomString();
+ else if (param == boolean.class)
+ setVal = new Boolean(!(((Boolean) getter.invoke(_conf,
+ (Object[]) null)).booleanValue()));
+ else
+ continue;
+
+ setter.invoke(_conf, new Object [] { setVal });
+ assertEquals(setVal, getter.invoke(_conf, (Object[]) null));
+ }
+ }
+
+ /**
+ * Test freezing.
+ */
+ public void testFreezing() {
+ assertTrue(!_conf.isReadOnly());
+ _conf.setReadOnly(true);
+ assertTrue(_conf.isReadOnly());
+ try {
+ _conf.setTestKey("bar");
+ fail("Allowed set on read only configuration.");
+ } catch (RuntimeException re) {
+ }
+ try {
+ Properties p = new Properties();
+ p.put("x", "y");
+ _conf.fromProperties(p);
+ fail("Allowed fromMap on read only configuration.");
+ } catch (RuntimeException re) {
+ }
+ }
+
+ /**
+ * Test serialization.
+ */
+ public void testSerialization() throws Exception {
+ assertTrue(_conf.loadDefaults());
+ _conf.setTestKey("testvalue");
+ _conf.setSysKey("sysvalue");
+ _conf.setObjectKey(new Object());
+ _conf.setPluginKey(new Object());
+
+ ConfigurationTest copy = (ConfigurationTest) roundtrip(_conf, true);
+ assertEquals("testvalue", copy.getTestKey());
+ assertEquals("sysvalue", copy.getSysKey());
+ assertNull(copy.getObjectKey());
+ assertEquals("java.lang.Object", copy.getPluginKey());
+ assertNotNull(copy.getPluginKeyInstance());
+
+ copy.setTestKey("testvalue2");
+ copy.setSysKey("sysvalue2");
+ copy.setPluginKey(new StringBuffer());
+
+ ConfigurationTest copy2 = (ConfigurationTest) roundtrip(copy, true);
+ assertEquals("testvalue2", copy2.getTestKey());
+ assertEquals("sysvalue2", copy2.getSysKey());
+ assertNull(copy2.getObjectKey());
+ assertEquals("java.lang.StringBuffer", copy2.getPluginKey());
+ assertEquals("", copy2.getPluginKeyInstance().toString());
+ }
+
+ public static void main(String[] args) {
+ main();
+ }
+
+ private static class ConfigurationTest extends ConfigurationImpl {
+ private final StringValue _testKey;
+ private final StringValue _sysKey;
+ private final PluginValue _pluginKey;
+ private final ObjectValue _objectKey;
+
+ public ConfigurationTest() {
+ this(true);
+ }
+
+ public ConfigurationTest(boolean canSetPlugin) {
+ super(false);
+ _testKey = addString("testKey");
+ _sysKey = addString("sysKey");
+ _pluginKey = addPlugin("pluginKey", canSetPlugin);
+ _objectKey = addObject("objectKey");
+ }
+
+ public String getProductName() {
+ return "test";
+ }
+
+ public String getTestKey() {
+ return _testKey.get();
+ }
+
+ public void setTestKey(String val) {
+ assertNotReadOnly();
+ _testKey.set(val);
+ }
+
+ public String getSysKey() {
+ return _sysKey.get();
+ }
+
+ public void setSysKey(String val) {
+ assertNotReadOnly();
+ _sysKey.set(val);
+ }
+
+ public String getPluginKey() {
+ return _pluginKey.getString();
+ }
+
+ public void setPluginKey(String val) {
+ assertNotReadOnly();
+ _pluginKey.setString(val);
+ }
+
+ public Object getPluginKeyInstance() {
+ if (_pluginKey.get() == null)
+ return _pluginKey.instantiate(Object.class, this);
+ return _pluginKey.get();
+ }
+
+ public void setPluginKey(Object val) {
+ assertNotReadOnly();
+ _pluginKey.set(val);
+ }
+
+ public Object getObjectKey() {
+ return _objectKey.get();
+ }
+
+ public void setObjectKey(Object val) {
+ assertNotReadOnly();
+ _objectKey.set(val);
+ }
+
+ public void deriveObjectKey(Object val) {
+ _objectKey.set(val, true);
+ }
+ }
+}
Added: incubator/openjpa/trunk/openjpa-lib/src/test/java/org/apache/openjpa/lib/conf/test/TestPluginValue.java
URL: http://svn.apache.org/viewvc/incubator/openjpa/trunk/openjpa-lib/src/test/java/org/apache/openjpa/lib/conf/test/TestPluginValue.java?rev=418401&view=auto
==============================================================================
--- incubator/openjpa/trunk/openjpa-lib/src/test/java/org/apache/openjpa/lib/conf/test/TestPluginValue.java (added)
+++ incubator/openjpa/trunk/openjpa-lib/src/test/java/org/apache/openjpa/lib/conf/test/TestPluginValue.java Fri Jun 30 15:37:18 2006
@@ -0,0 +1,172 @@
+/*
+ * 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.conf.test;
+
+import org.apache.openjpa.lib.conf.*;
+import org.apache.openjpa.lib.test.*;
+import serp.util.*;
+
+/**
+ * Tests the {@link Value}, {@link PluginValue}, and
+ * {@link PluginListValue} classes.
+ *
+ * @author Abe White
+ */
+public class TestPluginValue extends AbstractTestCase {
+ public TestPluginValue(String test) {
+ super(test);
+ }
+
+ public void testDefault() {
+ defaultTest(new StringValue("testKey"));
+ defaultTest(new PluginValue("testKey", true));
+ defaultTest(new PluginListValue("testKey"));
+ pluginDefaultTest(new PluginValue("testKey", true));
+ }
+
+ private void defaultTest(Value val) {
+ assertNull(val.getString());
+ val.setString("foo");
+ assertEquals("foo", val.getString());
+ val.setString(null);
+ assertNull(val.getString());
+ val.setDefault("xxx");
+ val.setString(null);
+ assertEquals("xxx", val.getString());
+ val.setString("bar");
+ assertEquals("bar", val.getString());
+ val.setString(" ");
+ assertEquals("xxx", val.getString());
+ val.setString("yyy");
+ assertEquals("yyy", val.getString());
+ val.setString(null);
+ assertEquals("xxx", val.getString());
+ }
+
+ private void pluginDefaultTest(PluginValue val) {
+ val.setDefault("foo");
+ val.setString("x=y");
+ assertEquals("foo(x=y)", val.getString());
+ val.set(new Integer(1));
+ assertEquals("java.lang.Integer", val.getString());
+ assertEquals(new Integer(1), val.get());
+ val.set(null);
+ assertEquals("foo", val.getString());
+ assertEquals(null, val.get());
+ }
+
+ public void testAlias() {
+ aliasTest(new StringValue("testKey"));
+ aliasTest(new PluginValue("testKey", true));
+ aliasTest(new PluginListValue("testKey"));
+ emptyAliasTest(new StringValue("testKey"));
+ emptyAliasTest(new StringValue("testKey"));
+ pluginAliasTest(new PluginValue("testKey", true));
+ pluginAliasTest(new PluginListValue("testKey"));
+ pluginListAliasTest(new PluginListValue("testKey"));
+ }
+
+ private void aliasTest(Value val) {
+ val.setAliases(new String[] { "foo", "bar" });
+ val.setDefault("bar");
+ assertEquals("bar", val.getDefault());
+ val.setString(null);
+ assertEquals("foo", val.getString());
+ val.setDefault("xxx");
+ val.setString(null);
+ assertEquals("xxx", val.getString());
+ val.setDefault("bar");
+ val.setString(null);
+ assertEquals("foo", val.getString());
+ val.setString("yyy");
+ val.setAliases(new String[] { "xxx", "yyy" });
+ assertEquals("xxx", val.getString());
+ }
+
+ private void emptyAliasTest(Value val) {
+ val.setDefault("foo");
+ val.setAliases(new String[] { "false", null });
+ val.setString("false");
+ assertEquals("false", val.getString());
+ val.setString(null);
+ assertEquals("foo", val.getString());
+ }
+
+ private void pluginAliasTest(Value val) {
+ // test plugin name-only aliases
+ val.setString("foo(biz=baz)");
+ assertEquals("foo(biz=baz)", val.getString());
+ val.setAliases(new String[] { "xxx", "foo" });
+ assertEquals("xxx(biz=baz)", val.getString());
+ }
+
+ private void pluginListAliasTest(Value val) {
+ // and test on lists
+ val.setString("foo(biz=baz), foo(a=b),xxx, foo, yyy");
+ assertEquals("foo(biz=baz), foo(a=b), xxx, foo, yyy", val.getString());
+ val.setAliases(new String[] { "bar", "foo" });
+ assertEquals("bar(biz=baz), bar(a=b), xxx, bar, yyy", val.getString());
+
+ val.setAliases(new String[] { "none", null });
+ val.setString("none");
+ assertTrue(((PluginListValue) val).getClassNames().length == 0);
+ }
+
+ public void testPluginListParsing() {
+ PluginListValue val = new PluginListValue("testKey");
+ assertEquals(0, val.getClassNames().length);
+ val.setString("foo");
+ assertEquals(1, val.getClassNames().length);
+ assertEquals("foo", val.getClassNames()[0]);
+ assertNull(val.getProperties()[0]);
+ val.setString("foo()");
+ assertEquals(1, val.getClassNames().length);
+ assertEquals("foo", val.getClassNames()[0]);
+ assertNull(val.getProperties()[0]);
+ val.setString("foo(a=b)");
+ assertEquals(1, val.getClassNames().length);
+ assertEquals("foo", val.getClassNames()[0]);
+ assertEquals("a=b", val.getProperties()[0]);
+ val.setString("foo(a=b, c=\"d,e f\", g=\"h\")");
+ assertEquals(1, val.getClassNames().length);
+ assertEquals("foo", val.getClassNames()[0]);
+ assertEquals("a=b, c=\"d,e f\", g=\"h\"", val.getProperties()[0]);
+ val.setString("foo(a=b, c=\"d,e f\"), bar, biz(a=c, d=g), baz()");
+ assertEquals(4, val.getClassNames().length);
+ assertEquals("foo", val.getClassNames()[0]);
+ assertEquals("a=b, c=\"d,e f\"", val.getProperties()[0]);
+ assertEquals("bar", val.getClassNames()[1]);
+ assertNull(val.getProperties()[1]);
+ assertEquals("biz", val.getClassNames()[2]);
+ assertEquals("a=c, d=g", val.getProperties()[2]);
+ assertEquals("baz", val.getClassNames()[3]);
+ assertNull(val.getProperties()[3]);
+ }
+
+ /**
+ * Required because we use a 'testKey' dummy property name.
+ */
+ public String getTestKey() {
+ return null;
+ }
+
+ /**
+ * Required because we use a 'testKey' dummy property name.
+ */
+ public void setTestKey(String key) {
+ }
+
+ public static void main(String[] args) {
+ main();
+ }
+}