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 [10/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/FormatPreservingProperties.java
URL: http://svn.apache.org/viewvc/incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/FormatPreservingProperties.java?rev=418401&r1=418400&r2=418401&view=diff
==============================================================================
--- incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/FormatPreservingProperties.java (original)
+++ incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/FormatPreservingProperties.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,64 +12,54 @@
*/
package org.apache.openjpa.lib.util;
-import org.apache.commons.collections.set.*;
-
import java.io.*;
-
import java.util.*;
-
+import org.apache.commons.collections.set.*;
/*
- * ### things to add:
-* - should probably be a SourceTracker
- *
-* - if an entry is removed, should there be an option to remove comments
- * just before the entry (a la javadoc)?
- *
+ * ### things to add: - should probably be a SourceTracker
+ * - if an entry is removed, should there be an option to remove comments
+ * just before the entry(a la javadoc)?
* - should we have an option to clean up whitespace?
- *
* - potentially would be interesting to add comments about each
- * property that OpenJPA adds to this object. We'd want to make the
- * automatic comment-removing code work first, though, so that if
- * someone then removed the property, the comments would go away.
- *
+ * property that OpenJPA adds to this object. We'd want to make the
+ * automatic comment-removing code work first, though, so that if
+ * someone then removed the property, the comments would go away.
* - would be neat if DuplicateKeyException could report line numbers of
- * offending entries.
- *
+ * offending entries.
* - putAll() with another FormatPreservingProperties should be smarter
*/
-
/**
- * <p>A specialization of {@link Properties} that stores its contents
- * in the same order and with the same formatting as was used to read
- * the contents from an input stream. This is useful because it means
- * that a properties file loaded via this object and then written
- * back out later on will only be different where changes or
- * additions were made.</p>
- *
- * <p>By default, the {@link #store} method in this class does not
- * behave the same as {@link Properties#store}. You can cause an
- * instance to approximate the behavior of {@link Properties#store}
- * by invoking {@link #setDefaultEntryDelimiter} with <code>=</code>,
- * {@link #setAddWhitespaceAfterDelimiter} with <code>false</code>, and
- * {@link #setAllowDuplicates} with <code>true</code>. However, this
- * will only influence how the instance will write new values, not how
- * it will write existing key-value pairs that are modified.</p>
- *
- * <p>In conjunction with a conservative output writer, it is
- * possible to only write to disk changes / additions.</p>
- *
- * <p>This implementation does not permit escaped ' ', '=', ':'
-* characters in key names.</p>
- *
- * @since 3.3
+ * A specialization of {@link Properties} that stores its contents
+ * in the same order and with the same formatting as was used to read
+ * the contents from an input stream. This is useful because it means
+ * that a properties file loaded via this object and then written
+ * back out later on will only be different where changes or
+ * additions were made.
+ * By default, the {@link #store} method in this class does not
+ * behave the same as {@link Properties#store}. You can cause an
+ * instance to approximate the behavior of {@link Properties#store}
+ * by invoking {@link #setDefaultEntryDelimiter} with <code>=</code>,
+ * {@link #setAddWhitespaceAfterDelimiter} with <code>false</code>, and
+ * {@link #setAllowDuplicates} with <code>true</code>. However, this
+ * will only influence how the instance will write new values, not how
+ * it will write existing key-value pairs that are modified.
+ * In conjunction with a conservative output writer, it is
+ * possible to only write to disk changes / additions.
+ * This implementation does not permit escaped ' ', '=', ':'
+ * characters in key names.
+ *
+ * @since 3.3
*/
public class FormatPreservingProperties extends Properties {
- private static Localizer _loc = Localizer.forPackage(FormatPreservingProperties.class);
+ private static Localizer _loc = Localizer.forPackage
+ (FormatPreservingProperties.class);
+
private char defaultEntryDelimiter = ':';
private boolean addWhitespaceAfterDelimiter = true;
private boolean allowDuplicates = false;
private boolean insertTimestamp = false;
+
private PropertySource source;
private ListOrderedSet newKeys = new ListOrderedSet();
private HashSet modifiedKeys = new HashSet();
@@ -90,96 +77,84 @@
}
/**
- * The character to use as a delimiter between property keys and values.
- *
- * @param defaultEntryDelimiter either ':' or '='
+ * The character to use as a delimiter between property keys and values.
+ *
+ * @param defaultEntryDelimiter either ':' or '='
*/
public void setDefaultEntryDelimiter(char defaultEntryDelimiter) {
this.defaultEntryDelimiter = defaultEntryDelimiter;
}
/**
- * See {@link #setDefaultEntryDelimiter}
+ * See {@link #setDefaultEntryDelimiter}
*/
public char getDefaultEntryDelimiter() {
return this.defaultEntryDelimiter;
}
/**
- * <p>If set to <code>true</code>, this properties object will add a
- * space after the delimiter character (if the delimiter is not
- * the space character). Else, this will not add a
- * space.</p>
- *
- * <p>Default value: <code>true</code>. Note that {@link
- * Properties#store} never writes whitespace.</p>
+ * If set to <code>true</code>, this properties object will add a
+ * space after the delimiter character(if the delimiter is not
+ * the space character). Else, this will not add a space.
+ * Default value: <code>true</code>. Note that {@link
+ * Properties#store} never writes whitespace.
*/
public void setAddWhitespaceAfterDelimiter(boolean add) {
this.addWhitespaceAfterDelimiter = add;
}
/**
- * <p>If set to <code>true</code>, this properties object will add a
- * space after the delimiter character (if the delimiter is not
- * the space character). Else, this will not add a
- * space.</p>
- *
- * <p>Default value: <code>true</code>. Note that {@link
- * Properties#store} never writes whitespace.</p>
+ * If set to <code>true</code>, this properties object will add a
+ * space after the delimiter character(if the delimiter is not
+ * the space character). Else, this will not add a space.
+ * Default value: <code>true</code>. Note that {@link
+ * Properties#store} never writes whitespace.
*/
public boolean getAddWhitespaceAfterDelimiter() {
return this.addWhitespaceAfterDelimiter;
}
/**
- * <p>If set to <code>true</code>, this properties object will add a
- * timestamp to the beginning of the file, just after the header
- * (if any) is printed. Else, this will not add a
- * timestamp.</p>
- *
- * <p>Default value: <code>false</code>. Note that {@link
- * Properties#store} always writes a timestamp.</p>
+ * If set to <code>true</code>, this properties object will add a
+ * timestamp to the beginning of the file, just after the header
+ * (if any) is printed. Else, this will not add a timestamp.
+ * Default value: <code>false</code>. Note that {@link
+ * Properties#store} always writes a timestamp.
*/
public void setInsertTimestamp(boolean insertTimestamp) {
this.insertTimestamp = insertTimestamp;
}
/**
- * <p>If set to <code>true</code>, this properties object will add a
- * timestamp to the beginning of the file, just after the header
- * (if any) is printed. Else, this will not add a
- * timestamp.</p>
- *
- * <p>Default value: <code>false</code>. Note that {@link
- * Properties#store} always writes a timestamp.</p>
+ * If set to <code>true</code>, this properties object will add a
+ * timestamp to the beginning of the file, just after the header
+ * (if any) is printed. Else, this will not add a timestamp.
+ * Default value: <code>false</code>. Note that {@link
+ * Properties#store} always writes a timestamp.
*/
public boolean getInsertTimestamp() {
return this.insertTimestamp;
}
/**
- * <p>If set to <code>true</code>, duplicate properties are allowed, and
- * the last property setting in the input will overwrite any previous
- * settings. If set to <code>false</code>, duplicate property definitions
- * in the input will cause an exception to be thrown during
- * {@link #load}.</p>
- *
- * <p>Default value: <code>false</code>. Note that {@link
- * Properties#store} always allows duplicates.</p>
+ * If set to <code>true</code>, duplicate properties are allowed, and
+ * the last property setting in the input will overwrite any previous
+ * settings. If set to <code>false</code>, duplicate property definitions
+ * in the input will cause an exception to be thrown during {@link #load}.
+ * Default value: <code>false</code>. Note that {@link
+ * Properties#store} always allows duplicates.
*/
public void setAllowDuplicates(boolean allowDuplicates) {
this.allowDuplicates = allowDuplicates;
}
/**
- * <p>If set to <code>true</code>, duplicate properties are allowed, and
- * the last property setting in the input will overwrite any previous
- * settings. If set to <code>false</code>, duplicate property definitions
- * in the input will cause an exception to be thrown during
- * {@link #load}.</p>
- *
- * <p>Default value: <code>false</code>. Note that {@link
- * Properties#store} always allows duplicates.</p>
+ * If set to <code>true</code>, duplicate properties are allowed, and
+ * the last property setting in the input will overwrite any previous
+ * settings. If set to <code>false</code>, duplicate property definitions
+ * in the input will cause an exception to be thrown during {@link #load}.
+ * Default value: <code>false</code>. Note that {@link
+ * Properties#store} always allows duplicates.
*/
public boolean getAllowDuplicates() {
return this.allowDuplicates;
@@ -198,48 +173,44 @@
}
/**
- * Circumvents the superclass {@link #putAll} implementation,
- * putting all the key-value pairs via {@link #put}.
+ * Circumvents the superclass {@link #putAll} implementation,
+ * putting all the key-value pairs via {@link #put}.
*/
public void putAll(Map m) {
Map.Entry e;
-
- for (Iterator iter = m.entrySet().iterator(); iter.hasNext();) {
+ for (Iterator iter = m.entrySet().iterator(); iter.hasNext(); ) {
e = (Map.Entry) iter.next();
put(e.getKey(), e.getValue());
}
}
/**
- * Removes the key from the bookkeeping collectiotns as well.
+ * Removes the key from the bookkeeping collectiotns as well.
*/
public Object remove(Object key) {
newKeys.remove(key);
-
return super.remove(key);
}
public void clear() {
super.clear();
- if (source != null) {
+ if (source != null)
source.clear();
- }
newKeys.clear();
modifiedKeys.clear();
}
public Object clone() {
- FormatPreservingProperties c = (FormatPreservingProperties) super.clone();
+ FormatPreservingProperties c = (FormatPreservingProperties)
+ super.clone();
- if (source != null) {
- c.source = (PropertySource) source.clone();
- }
+ if (source != null)
+ c.source = (PropertySource)source.clone();
- if (modifiedKeys != null) {
- c.modifiedKeys = (HashSet) modifiedKeys.clone();
- }
+ if (modifiedKeys != null)
+ c.modifiedKeys = (HashSet)modifiedKeys.clone();
if (newKeys != null) {
c.newKeys = new ListOrderedSet();
@@ -267,31 +238,29 @@
// represents an actual change in value, mark the modification
// or addition in the bookkeeping collections.
if (!isLoading && isNotDeserializing && !val.equals(o)) {
- if (o != null) {
+ if (o != null)
modifiedKeys.add(key);
- } else if (!newKeys.contains(key)) {
+ else if (!newKeys.contains(key))
newKeys.add(key);
- }
}
-
return o;
}
/**
- * Loads the properties in <code>in</code>, according to the rules
- * described in {@link Properties#load}. If {@link #getAllowDuplicates}
- * returns <code>true</code>, this will throw a {@link
- * DuplicateKeyException} if duplicate property declarations are
- * encountered.
- *
- * @see Properties#load
+ * Loads the properties in <code>in</code>, according to the rules
+ * described in {@link Properties#load}. If {@link #getAllowDuplicates}
+ * returns <code>true</code>, this will throw a {@link
+ * DuplicateKeyException} if duplicate property declarations are
+ * encountered.
+ *
+ * @see Properties#load
*/
public void load(InputStream in) throws IOException {
isLoading = true;
-
try {
loadProperties(in);
- } finally {
+ }
+ finally {
isLoading = false;
}
}
@@ -304,32 +273,28 @@
Set loadedKeys = new HashSet();
for (PropertyLine l;
- ((l = reader.readPropertyLine()) != null) && source.add(l);) {
+ (l = reader.readPropertyLine()) != null && source.add(l); ) {
String line = l.line.toString();
char c = 0;
int pos = 0;
- while ((pos < line.length()) && isSpace(c = line.charAt(pos)))
+ while (pos < line.length() && isSpace(c = line.charAt(pos)))
pos++;
- if (((line.length() - pos) == 0) || (line.charAt(pos) == '#') ||
- (line.charAt(pos) == '!')) {
+ if ((line.length() - pos) == 0
+ || line.charAt(pos) == '#' || line.charAt(pos) == '!')
continue;
- }
StringBuffer key = new StringBuffer();
-
- while ((pos < line.length()) && !isSpace(c = line.charAt(pos++)) &&
- (c != '=') && (c != ':')) {
+ while (pos < line.length() && !isSpace(c = line.charAt(pos++))
+ && c != '=' && c != ':') {
if (c == '\\') {
- if (pos == line.length()) // end of line: read the next
- {
+ if (pos == line.length()) {
l.append(line = reader.readLine());
pos = 0;
-
- while ((pos < line.length()) &&
- isSpace(c = line.charAt(pos)))
+ while (pos < line.length()
+ && isSpace(c = line.charAt(pos)))
pos++;
} else {
pos = readEscape(line, pos, key);
@@ -339,16 +304,14 @@
}
}
- boolean isDelim = ((c == ':') || (c == '='));
+ boolean isDelim = (c == ':' || c == '=');
- for (; (pos < line.length()) && isSpace(c = line.charAt(pos));
- pos++)
- ;
+ for ( ; pos < line.length()
+ && isSpace(c = line.charAt(pos)); pos++);
- if (!isDelim && ((c == ':') || (c == '='))) {
+ if (!isDelim && (c == ':' || c == '=')) {
pos++;
-
- while ((pos < line.length()) && isSpace(c = line.charAt(pos)))
+ while (pos < line.length() && isSpace(c = line.charAt(pos)))
pos++;
}
@@ -356,36 +319,29 @@
while (pos < line.length()) {
c = line.charAt(pos++);
-
if (c == '\\') {
- if (pos == line.length()) // end of line: read the next
- {
+ if (pos == line.length()) {
l.append(line = reader.readLine());
- if (line == null) {
+ if (line == null)
break;
- }
pos = 0;
-
- while ((pos < line.length()) &&
- isSpace(c = line.charAt(pos)))
+ while (pos < line.length()
+ && isSpace(c = line.charAt(pos)))
pos++;
-
element.ensureCapacity(line.length() - pos +
element.length());
} else {
pos = readEscape(line, pos, element);
}
- } else {
+ } else
element.append(c);
- }
}
- if (!loadedKeys.add(key.toString()) && !allowDuplicates) {
+ if (!loadedKeys.add(key.toString()) && !allowDuplicates)
throw new DuplicateKeyException(key.toString(),
getProperty(key.toString()), element.toString());
- }
l.setPropertyKey(key.toString());
l.setPropertyValue(element.toString());
@@ -394,54 +350,40 @@
}
/**
- * Read the next escaped character: handle newlines, tabs, returns, and
- * form feeds with the appropriate escaped character, then try to
- * decode unicode characters. Finally, just add the character
- * explicitly.
- *
- * @param source the source of the characters
- * @param pos the position at which to start reading
- * @param value the value we are appending to
- * @return the position after the reading is done
+ * Read the next escaped character: handle newlines, tabs, returns, and
+ * form feeds with the appropriate escaped character, then try to
+ * decode unicode characters. Finally, just add the character explicitly.
+ *
+ * @param source the source of the characters
+ * @param pos the position at which to start reading
+ * @param value the value we are appending to
+ * @return the position after the reading is done
*/
private static int readEscape(String source, int pos, StringBuffer value) {
char c = source.charAt(pos++);
-
switch (c) {
case 'n':
value.append('\n');
-
break;
-
case 't':
value.append('\t');
-
break;
-
case 'f':
value.append('\f');
-
break;
-
case 'r':
value.append('\r');
-
break;
-
case 'u':
-
- if ((pos + 4) <= source.length()) {
- char uni = (char) Integer.parseInt(source.substring(pos, pos +
- 4), 16);
+ if (pos + 4 <= source.length()) {
+ char uni = (char)Integer.parseInt
+ (source.substring(pos, pos + 4), 16);
value.append(uni);
pos += 4;
}
-
break;
-
default:
value.append(c);
-
break;
}
@@ -459,29 +401,24 @@
}
}
- public void store(OutputStream out, String header)
- throws IOException {
- boolean endWithNewline = (source != null) && source.endsInNewline;
+ public void store(OutputStream out, String header) throws IOException {
+ boolean endWithNewline = source != null && source.endsInNewline;
boolean firstLine = true;
// Must be ISO-8859-1 ecoding according to Properties.load javadoc
- PrintWriter writer = new PrintWriter(new OutputStreamWriter(out,
- "ISO-8859-1"), false);
+ PrintWriter writer = new PrintWriter
+ (new OutputStreamWriter(out, "ISO-8859-1"), false);
- if (header != null) {
+ if (header != null)
writer.println("#" + header);
- }
- if (insertTimestamp) {
+ if (insertTimestamp)
writer.println("#" + Calendar.getInstance().getTime());
- }
List lines = new LinkedList();
-
// first write all the existing props as they were initially read
- if (source != null) {
+ if (source != null)
lines.addAll(source);
- }
// next write out new keys, then the rest of the keys
ListOrderedSet keys = new ListOrderedSet();
@@ -494,19 +431,17 @@
boolean needsNewline = false;
- for (Iterator i = lines.iterator(); i.hasNext();) {
+ for (Iterator i = lines.iterator(); i.hasNext(); ) {
Object next = i.next();
if (next instanceof PropertyLine) {
- if (((PropertyLine) next).write(writer, keys, needsNewline)) {
+ if (((PropertyLine)next).write(writer, keys, needsNewline))
needsNewline = i.hasNext();
- }
} else if (next instanceof String) {
- String key = (String) next;
-
+ String key = (String)next;
if (keys.remove(key)) {
if (writeProperty(key, writer, needsNewline)) {
- needsNewline = i.hasNext() && (keys.size() > 0);
+ needsNewline = i.hasNext() && keys.size() > 0;
// any new or modified properties will cause
// the file to end with a newline
@@ -517,9 +452,8 @@
}
// make sure we end in a newline if the source ended in it
- if (endWithNewline) {
+ if (endWithNewline)
writer.println();
- }
writer.flush();
}
@@ -528,28 +462,21 @@
boolean needsNewline) {
StringBuffer s = new StringBuffer();
- if (key == null) {
+ if (key == null)
return false;
- }
String val = getProperty(key);
-
- if (val == null) {
+ if (val == null)
return false;
- }
formatValue(key, s, true);
s.append(defaultEntryDelimiter);
-
- if (addWhitespaceAfterDelimiter) {
+ if (addWhitespaceAfterDelimiter)
s.append(' ');
- }
-
formatValue(val, s, false);
- if (needsNewline) {
+ if (needsNewline)
writer.println();
- }
writer.print(s);
@@ -557,13 +484,13 @@
}
/**
- * Format the given string as an encoded value for storage. This will
- * perform any necessary escaping of special characters.
- *
- * @param str the value to encode
- * @param buf the buffer to which to append the encoded value
- * @param isKey if true, then the string is a Property key, otherwise
- * it is a value
+ * Format the given string as an encoded value for storage. This will
+ * perform any necessary escaping of special characters.
+ *
+ * @param str the value to encode
+ * @param buf the buffer to which to append the encoded value
+ * @param isKey if true, then the string is a Property key, otherwise
+ * it is a value
*/
private static void formatValue(String str, StringBuffer buf, boolean isKey) {
if (isKey) {
@@ -579,30 +506,26 @@
for (int i = 0; i < size; i++) {
char c = str.charAt(i);
- if (c == '\n') {
+ if (c == '\n')
buf.append("\\n");
- } else if (c == '\r') {
+ else if (c == '\r')
buf.append("\\r");
- } else if (c == '\t') {
+ else if (c == '\t')
buf.append("\\t");
- } else if (c == '\f') {
+ else if (c == '\f')
buf.append("\\f");
- } else if (c == ' ') {
+ else if (c == ' ')
buf.append(escapeSpace ? "\\ " : " ");
- } else if ((c == '\\') || (c == '!') || (c == '#') || (c == '=') ||
- (c == ':')) {
+ else if (c == '\\' || c == '!' || c == '#' || c == '=' || c == ':')
buf.append('\\').append(c);
- } else if ((c < ' ') || (c > '~')) {
- buf.append("\\u0000".substring(0,
- 6 - Integer.toHexString(c).length()))
- .append(Integer.toHexString(c));
- } else {
+ else if (c < ' ' || c > '~')
+ buf.append("\\u0000".substring(0, 6 - Integer.toHexString(c).
+ length())).append(Integer.toHexString(c));
+ else
buf.append(c);
- }
- if (c != ' ') {
+ if (c != ' ')
escapeSpace = isKey;
- }
}
}
@@ -614,8 +537,8 @@
}
/**
- * Contains the original line of the properties file: can be a
- * proper key/value pair, or a comment, or just whitespace.
+ * Contains the original line of the properties file: can be a
+ * proper key/value pair, or a comment, or just whitespace.
*/
private class PropertyLine implements Serializable {
private final StringBuffer line = new StringBuffer();
@@ -648,36 +571,31 @@
}
/**
- * Write the given line. It will only be written if the line is a
- * comment, or if it is a property and its value is unchanged
- * from the original.
- *
- * @param pw the PrintWriter to which the write
- * @return whether or not this was a known key
+ * Write the given line. It will only be written if the line is a
+ * comment, or if it is a property and its value is unchanged
+ * from the original.
+ *
+ * @param pw the PrintWriter to which the write
+ * @return whether or not this was a known key
*/
public boolean write(PrintWriter pw, Collection keys,
boolean needsNewline) {
// no property? It may be a comment or just whitespace
if (propertyKey == null) {
- if (needsNewline) {
+ if (needsNewline)
pw.println();
- }
-
pw.print(line.toString());
-
return true;
}
// check to see if we are the same value we initially read:
// if so, then just write it back exactly as it was read
- if ((propertyValue != null) && containsKey(propertyKey) &&
- (propertyValue.equals(getProperty(propertyKey)) ||
+ if (propertyValue != null && containsKey(propertyKey) &&
+ (propertyValue.equals(getProperty(propertyKey)) ||
(!newKeys.contains(propertyKey) &&
!modifiedKeys.contains(propertyKey)))) {
- if (needsNewline) {
+ if (needsNewline)
pw.println();
- }
-
pw.print(line.toString());
keys.remove(propertyKey);
@@ -690,11 +608,9 @@
// was originally read, so that it will be in the proximity
// to the comment
if (containsKey(propertyKey) &&
- (modifiedKeys.contains(propertyKey) ||
+ (modifiedKeys.contains(propertyKey) ||
newKeys.contains(propertyKey))) {
- while (keys.remove(propertyKey))
- ;
-
+ while (keys.remove(propertyKey));
return writeProperty(propertyKey, pw, needsNewline);
}
@@ -708,25 +624,22 @@
throws IOException {
// Must be ISO-8859-1 ecoding according to Properties.load javadoc
super(new InputStreamReader(new LineEndingStream(in, source),
- "ISO-8859-1"));
+ "ISO-8859-1"));
}
public PropertyLine readPropertyLine() throws IOException {
String l = readLine();
-
- if (l == null) {
+ if (l == null)
return null;
- }
PropertyLine pl = new PropertyLine(l);
-
return pl;
}
}
/**
- * Simple FilterInputStream that merely remembers if the last
- * character that it read was a newline or not.
+ * Simple FilterInputStream that merely remembers if the last
+ * character that it read was a newline or not.
*/
private static class LineEndingStream extends FilterInputStream {
private final PropertySource source;
@@ -739,25 +652,21 @@
public int read() throws IOException {
int c = super.read();
- source.endsInNewline = ((c == '\n') || (c == '\r'));
-
+ source.endsInNewline = (c == '\n' || c == '\r');
return c;
}
public int read(byte[] b, int off, int len) throws IOException {
int n = super.read(b, off, len);
-
- if (n > 0) {
- source.endsInNewline = ((b[(n + off) - 1] == '\n') ||
- (b[(n + off) - 1] == '\r'));
- }
-
+ if (n > 0)
+ source.endsInNewline =
+ (b[n + off - 1] == '\n' || b[n + off - 1] == '\r');
return n;
}
}
- static class PropertySource extends LinkedList implements Cloneable,
- Serializable {
+ static class PropertySource extends LinkedList
+ implements Cloneable, Serializable {
private boolean endsInNewline = false;
}
}
Modified: incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/JavaVersions.java
URL: http://svn.apache.org/viewvc/incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/JavaVersions.java?rev=418401&r1=418400&r2=418401&view=diff
==============================================================================
--- incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/JavaVersions.java (original)
+++ incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/JavaVersions.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
@@ -16,21 +13,22 @@
package org.apache.openjpa.lib.util;
import java.lang.reflect.*;
-
import java.util.*;
-
/**
- * <p>Utilities for dealing with different Java spec versions.</p>
- *
- * @author Abe White
- * @nojavadoc */
+ * Utilities for dealing with different Java spec versions.
+ *
+ * @author Abe White
+ * @nojavadoc
+ */
public class JavaVersions {
/**
- * Java version; one of 2, 3, 4, 5, 6, or 7.
+ * Java version; one of 2, 3, 4, 5, 6, or 7.
*/
public static final int VERSION;
+
private static final Class[] EMPTY_CLASSES = new Class[0];
+
private static Class PARAM_TYPE = null;
private static Class ENUM_TYPE = null;
private static Class ANNO_TYPE = null;
@@ -41,25 +39,23 @@
static {
String specVersion = System.getProperty("java.specification.version");
-
- if ("1.2".equals(specVersion)) {
+ if ("1.2".equals(specVersion))
VERSION = 2;
- } else if ("1.3".equals(specVersion)) {
+ else if ("1.3".equals(specVersion))
VERSION = 3;
- } else if ("1.4".equals(specVersion)) {
+ else if ("1.4".equals(specVersion))
VERSION = 4;
- } else if ("1.5".equals(specVersion)) {
+ else if ("1.5".equals(specVersion))
VERSION = 5;
- } else if ("1.6".equals(specVersion)) {
+ else if ("1.6".equals(specVersion))
VERSION = 6;
- } else {
+ else
VERSION = 7; // maybe someday...
- }
if (VERSION >= 5) {
try {
- PARAM_TYPE = Class.forName(
- "java.lang.reflect.ParameterizedType");
+ PARAM_TYPE = Class.forName
+ ("java.lang.reflect.ParameterizedType");
ENUM_TYPE = Class.forName("java.lang.Enum");
ANNO_TYPE = Class.forName("java.lang.annotation.Annotation");
} catch (Throwable t) {
@@ -70,24 +66,25 @@
try {
Class stack = Class.forName("[Ljava.lang.StackTraceElement;");
GET_STACK = Throwable.class.getMethod("getStackTrace",
- (Class[]) null);
+ (Class[]) null);
SET_STACK = Throwable.class.getMethod("setStackTrace",
- new Class[] { stack });
- GET_CAUSE = Throwable.class.getMethod("getCause", (Class[]) null);
+ new Class[] { stack });
+ GET_CAUSE = Throwable.class.getMethod("getCause",
+ (Class[]) null);
INIT_CAUSE = Throwable.class.getMethod("initCause",
- new Class[] { Throwable.class });
+ new Class[] { Throwable.class });
} catch (Throwable t) {
}
}
}
/**
- * Returns a version-specific instance of the specified class
- *
- * @see #getVersionSpecificClass(java.lang.String)
- *
- * @param base the base class to check
- * @return the JDK-version-specific version of the class
+ * Returns a version-specific instance of the specified class
+ *
+ * @see #getVersionSpecificClass(java.lang.String)
+ *
+ * @param base the base class to check
+ * @return the JDK-version-specific version of the class
*/
public static Class getVersionSpecificClass(Class base) {
try {
@@ -98,28 +95,27 @@
}
/**
- * Obtains a subclass of the specific base class that is
- * specific to the current version of Java in use. The
- * heuristic for the class name to load will be that OpenJPA
- * first checks for the name of the class with the current
- * setting of the {@link #VERSION} field, then each number in
- * decreasing order, until ending in the unqualified name.
- * <p>
+ * Obtains a subclass of the specific base class that is
+ * specific to the current version of Java in use. The
+ * heuristic for the class name to load will be that OpenJPA
+ * first checks for the name of the class with the current
+ * setting of the {@link #VERSION} field, then each number in
+ * decreasing order, until ending in the unqualified name.
* For example, if we are using JDK 1.5.1, and we want to load
- * "org.apache.openjpa.lib.SomeClass", we will try to load the following
- * classes in order and return the first one that is successfully
- * found and loaded:
- * <ol>
- * <li>org.apache.openjpa.lib.SomeClass5</li>
- * <li>org.apache.openjpa.lib.SomeClass4</li>
- * <li>org.apache.openjpa.lib.SomeClass3</li>
- * <li>org.apache.openjpa.lib.SomeClass2</li>
- * <li>org.apache.openjpa.lib.SomeClass1</li>
- * <li>org.apache.openjpa.lib.SomeClass</li>
- * </ol>
- *
- * @param base the base name of the class to load
- * @return the subclass appropriate for the current Java version
+ * "org.apache.openjpa.lib.SomeClass", we will try to load the following
+ * classes in order and return the first one that is successfully
+ * found and loaded:
+ * <ol>
+ * <li>org.apache.openjpa.lib.SomeClass5</li>
+ * <li>org.apache.openjpa.lib.SomeClass4</li>
+ * <li>org.apache.openjpa.lib.SomeClass3</li>
+ * <li>org.apache.openjpa.lib.SomeClass2</li>
+ * <li>org.apache.openjpa.lib.SomeClass1</li>
+ * <li>org.apache.openjpa.lib.SomeClass</li>
+ * </ol>
+ *
+ * @param base the base name of the class to load
+ * @return the subclass appropriate for the current Java version
*/
public static Class getVersionSpecificClass(String base)
throws ClassNotFoundException {
@@ -131,40 +127,35 @@
// cannot understand
}
}
-
return Class.forName(base);
}
/**
- * Return true if the given type is an annotation.
+ * Return true if the given type is an annotation.
*/
public static boolean isAnnotation(Class cls) {
- return (ANNO_TYPE != null) && ANNO_TYPE.isAssignableFrom(cls);
+ return ANNO_TYPE != null && ANNO_TYPE.isAssignableFrom(cls);
}
/**
- * Return true if the given type is an enumeration.
+ * Return true if the given type is an enumeration.
*/
public static boolean isEnumeration(Class cls) {
- return (ENUM_TYPE != null) && ENUM_TYPE.isAssignableFrom(cls);
+ return ENUM_TYPE != null && ENUM_TYPE.isAssignableFrom(cls);
}
/**
- * Collects the parameterized type declarations for a given field.
+ * Collects the parameterized type declarations for a given field.
*/
public static Class[] getParameterizedTypes(Field f) {
- if (f == null) {
+ if (f == null)
return null;
- }
-
- if (VERSION < 5) {
+ if (VERSION < 5)
return EMPTY_CLASSES;
- }
try {
- Object type = Field.class.getMethod("getGenericType", (Class[]) null)
- .invoke(f, (Object[]) null);
-
+ Object type = Field.class.getMethod("getGenericType",
+ (Class[]) null).invoke(f, (Object[]) null);
return collectParameterizedTypes(type);
} catch (Exception e) {
return EMPTY_CLASSES;
@@ -172,21 +163,17 @@
}
/**
- * Collects the parameterized return type declarations for a given method.
+ * Collects the parameterized return type declarations for a given method.
*/
public static Class[] getParameterizedTypes(Method meth) {
- if (meth == null) {
+ if (meth == null)
return null;
- }
-
- if (VERSION < 5) {
+ if (VERSION < 5)
return EMPTY_CLASSES;
- }
try {
Object type = Method.class.getMethod("getGenericReturnType",
- (Class[]) null).invoke(meth, (Object[]) null);
-
+ (Class[]) null).invoke(meth, (Object[]) null);
return collectParameterizedTypes(type);
} catch (Exception e) {
return EMPTY_CLASSES;
@@ -194,48 +181,40 @@
}
/**
- * Return all parameterized classes for the given type.
+ * Return all parameterized classes for the given type.
*/
private static Class[] collectParameterizedTypes(Object type)
throws Exception {
- if ((PARAM_TYPE == null) || !PARAM_TYPE.isInstance(type)) {
+ if (PARAM_TYPE == null || !PARAM_TYPE.isInstance(type))
return EMPTY_CLASSES;
- }
-
- Object[] args = (Object[]) PARAM_TYPE.getMethod("getActualTypeArguments",
- (Class[]) null).invoke(type, (Object[]) null);
- if (args.length == 0) {
+ Object[] args = (Object[]) PARAM_TYPE.getMethod
+ ("getActualTypeArguments", (Class[]) null).invoke(type,
+ (Object[]) null);
+ if (args.length == 0)
return EMPTY_CLASSES;
- }
Class[] clss = new Class[args.length];
-
for (int i = 0; i < args.length; i++) {
- if (!(args[i] instanceof Class)) {
+ if (!(args[i] instanceof Class))
return EMPTY_CLASSES;
- }
-
clss[i] = (Class) args[i];
}
-
return clss;
}
/**
- * Transfer the stack from one throwable to another, or return
- * false if it cannot be done, possibly due to an unsupported Java version.
+ * Transfer the stack from one throwable to another, or return
+ * false if it cannot be done, possibly due to an unsupported Java version.
*/
public static boolean transferStackTrace(Throwable from, Throwable to) {
- if ((GET_STACK == null) || (SET_STACK == null) || (from == null) ||
- (to == null)) {
+ if (GET_STACK == null || SET_STACK == null || from == null
+ || to == null)
return false;
- }
try {
Object stack = GET_STACK.invoke(from, (Object[]) null);
SET_STACK.invoke(to, new Object[] { stack });
-
return true;
} catch (Throwable t) {
return false;
@@ -243,30 +222,28 @@
}
/**
- * Return the cause of the given throwable.
+ * Return the cause of the given throwable.
*/
public static Throwable getCause(Throwable ex) {
- if ((GET_CAUSE == null) || (ex == null)) {
+ if (GET_CAUSE == null || ex == null)
return null;
- }
try {
- return (Throwable) GET_CAUSE.invoke(ex, (Object[]) null);
+ return(Throwable) GET_CAUSE.invoke(ex, (Object[]) null);
} catch (Throwable t) {
return null;
}
}
/**
- * Set the cause of the given throwable.
+ * Set the cause of the given throwable.
*/
public static Throwable initCause(Throwable ex, Throwable cause) {
- if ((INIT_CAUSE == null) || (ex == null) || (cause == null)) {
+ if (INIT_CAUSE == null || ex == null || cause == null)
return ex;
- }
try {
- return (Throwable) INIT_CAUSE.invoke(ex, new Object[] { cause });
+ return(Throwable) INIT_CAUSE.invoke(ex, new Object[] { cause });
} catch (Throwable t) {
return ex;
}
Modified: incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/LRUMap.java
URL: http://svn.apache.org/viewvc/incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/LRUMap.java?rev=418401&r1=418400&r2=418401&view=diff
==============================================================================
--- incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/LRUMap.java (original)
+++ incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/LRUMap.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
@@ -16,16 +13,15 @@
package org.apache.openjpa.lib.util;
import java.io.*;
-
import java.util.*;
-
/**
- * <p>Extension of the commons <code>LRUMap</code> that can change its
- * maximum size.</p>
- *
- * @author Abe White
- * @nojavadoc */
+ * Extension of the commons <code>LRUMap</code> that can change its
+ * maximum size.
+ *
+ * @author Abe White
+ * @nojavadoc
+ */
public class LRUMap extends org.apache.commons.collections.map.LRUMap
implements SizedMap {
private int _max = -1;
@@ -50,14 +46,11 @@
}
public void setMaxSize(int max) {
- if (max < 0) {
+ if (max < 0)
throw new IllegalArgumentException(String.valueOf(max));
- }
-
_max = max;
Object key;
-
while (size() > _max) {
key = lastKey();
overflowRemoved(key, remove(key));
@@ -68,21 +61,19 @@
}
public int maxSize() {
- return (_max == -1) ? super.maxSize() : _max;
+ return(_max == -1) ? super.maxSize() : _max;
}
public boolean isFull() {
- return (_max == -1) ? super.isFull() : (size() >= _max);
+ return(_max == -1) ? super.isFull() : size() >= _max;
}
protected boolean removeLRU(LinkEntry entry) {
overflowRemoved(entry.getKey(), entry.getValue());
-
return super.removeLRU(entry);
}
- protected void doWriteObject(ObjectOutputStream out)
- throws IOException {
+ protected void doWriteObject(ObjectOutputStream out) throws IOException {
out.writeInt(_max);
super.doWriteObject(out);
}
Modified: incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/Localizer.java
URL: http://svn.apache.org/viewvc/incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/Localizer.java?rev=418401&r1=418400&r2=418401&view=diff
==============================================================================
--- incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/Localizer.java (original)
+++ incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/Localizer.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
@@ -16,230 +13,209 @@
package org.apache.openjpa.lib.util;
import java.text.*;
-
import java.util.*;
import java.util.concurrent.*;
-
/**
- * <p>The Localizer provides convenient access to localized
- * strings. It inlcudes built-in support for parameter substitution through
- * the use of the {@link MessageFormat} utility.</p>
- *
- * <p>Strings are stored in per-package {@link Properties} files.
- * The property file for the default locale must be named
- * <code>localizer.properties</code>. Additional locales can be supported
- * through additional property files using the naming conventions specified
- * in the {@link ResourceBundle} class. For example, the german locale
- * could be supported through a <code>localizer_de_DE.properties</code>
- * file.</p>
- *
- * @author Abe White
+ * The Localizer provides convenient access to localized
+ * strings. It inlcudes built-in support for parameter substitution through
+ * the use of the {@link MessageFormat} utility.
+ * Strings are stored in per-package {@link Properties} files.
+ * The property file for the default locale must be named
+ * <code>localizer.properties</code>. Additional locales can be supported
+ * through additional property files using the naming conventions specified
+ * in the {@link ResourceBundle} class. For example, the german locale
+ * could be supported through a <code>localizer_de_DE.properties</code> file.
+ *
+ * @author Abe White
*/
public class Localizer {
// static cache of package+loc name to localizer mappings
private static final Map _localizers = new ConcurrentHashMap();
// list of resource providers to delegate to when locating resources
- private static final Collection _providers = new CopyOnWriteArraySet(Arrays.asList(
- new Object[] {
- new SimpleResourceBundleProvider(),
- new StreamResourceBundleProvider(),
- new ZipResourceBundleProvider(),
- }));
+ private static final Collection _providers = new CopyOnWriteArraySet
+ (Arrays.asList(new Object[] {
+ new SimpleResourceBundleProvider(),
+ new StreamResourceBundleProvider(),
+ new ZipResourceBundleProvider(), }));
// the local file name and class' classloader
private ResourceBundle _bundle = null;
/**
- * Return a Localizer instance that will access the properties file
- * in the package of the given class using the system default locale.
- *
- * @see #forPackage(Class,Locale)
+ * Return a Localizer instance that will access the properties file
+ * in the package of the given class using the system default locale.
+ *
+ * @see #forPackage(Class,Locale)
*/
public static Localizer forPackage(Class cls) {
return forPackage(cls, null);
}
/**
- * Return a Localizer instance that will access the properties file
- * in the package of the given class using the given locale.
- *
- * @param cls the class whose package to check for the localized
- * properties file; if null, the system will check for
- * a top-level properties file
- * @param locale the locale to which strings should be localized; if
- * null, the system default will be assumed
+ * Return a Localizer instance that will access the properties file
+ * in the package of the given class using the given locale.
+ *
+ * @param cls the class whose package to check for the localized
+ * properties file; if null, the system will check for
+ * a top-level properties file
+ * @param locale the locale to which strings should be localized; if
+ * null, the system default will be assumed
*/
public static Localizer forPackage(Class cls, Locale locale) {
- if (locale == null) {
+ if (locale == null)
locale = Locale.getDefault();
- }
- int dot = (cls == null) ? (-1) : cls.getName().lastIndexOf('.');
+ int dot = (cls == null) ? -1 : cls.getName().lastIndexOf('.');
String file;
-
- if (dot == -1) {
+ if (dot == -1)
file = "localizer";
- } else {
+ else
file = cls.getName().substring(0, dot + 1) + "localizer";
- }
-
String key = file + locale.toString();
// no locking; ok if bundle created multiple times
// check for cached version
Localizer loc = (Localizer) _localizers.get(key);
-
- if (loc != null) {
+ if (loc != null)
return loc;
- }
// find resource bundle
ResourceBundle bundle = null;
ClassLoader loader = (cls == null) ? null : cls.getClassLoader();
-
for (Iterator itr = _providers.iterator(); itr.hasNext();) {
- bundle = ((ResourceBundleProvider) itr.next()).findResource(file,
- locale, loader);
-
- if (bundle != null) {
+ bundle = ((ResourceBundleProvider) itr.next()).findResource
+ (file, locale, loader);
+ if (bundle != null)
break;
- }
}
// cache the localizer
loc = new Localizer();
loc._bundle = bundle;
_localizers.put(key, loc);
-
return loc;
}
/**
- * Register a resource provider.
+ * Register a resource provider.
*/
public static void addProvider(ResourceBundleProvider provider) {
_providers.add(provider);
}
/**
- * Remove a resource provider.
+ * Remove a resource provider.
*/
public static boolean removeProvider(ResourceBundleProvider provider) {
return _providers.remove(provider);
}
/**
- * Return the localized string matching the given key.
+ * Return the localized string matching the given key.
*/
public String get(String key) {
return get(key, false);
}
/**
- * Return the localized string matching the given key.
+ * Return the localized string matching the given key.
*/
public String getFatal(String key) {
return get(key, true);
}
/**
- * Return the localized string matching the given key. The given
- * <code>sub</code> object will be packed into an array and substituted
- * into the found string according to the rules of the
- * {@link MessageFormat} class.
- *
- * @see #get(String)
+ * Return the localized string matching the given key. The given
+ * <code>sub</code> object will be packed into an array and substituted
+ * into the found string according to the rules of the
+ * {@link MessageFormat} class.
+ *
+ * @see #get(String)
*/
public String get(String key, Object sub) {
return get(key, new Object[] { sub });
}
/**
- * Return the localized string matching the given key. The given
- * <code>sub</code> object will be packed into an array and substituted
- * into the found string according to the rules of the
- * {@link MessageFormat} class.
- *
- * @see #getFatal(String)
+ * Return the localized string matching the given key. The given
+ * <code>sub</code> object will be packed into an array and substituted
+ * into the found string according to the rules of the
+ * {@link MessageFormat} class.
+ *
+ * @see #getFatal(String)
*/
public String getFatal(String key, Object sub) {
return getFatal(key, new Object[] { sub });
}
/**
- * Return the localized string for the given key.
- *
- * @see #get(String,Object)
+ * Return the localized string for the given key.
+ *
+ * @see #get(String,Object)
*/
public String get(String key, Object sub1, Object sub2) {
return get(key, new Object[] { sub1, sub2 });
}
/**
- * Return the localized string for the given key.
- *
- * @see #getFatal(String,Object)
+ * Return the localized string for the given key.
+ *
+ * @see #getFatal(String,Object)
*/
public String getFatal(String key, Object sub1, Object sub2) {
return getFatal(key, new Object[] { sub1, sub2 });
}
/**
- * Return the localized string for the given key.
- *
- * @see #get(String,Object)
+ * Return the localized string for the given key.
+ *
+ * @see #get(String,Object)
*/
public String get(String key, Object sub1, Object sub2, Object sub3) {
return get(key, new Object[] { sub1, sub2, sub3 });
}
/**
- * Return the localized string matching the given key. The given
- * <code>subs</code> objects will be substituted
- * into the found string according to the rules of the
- * {@link MessageFormat} class.
- *
- * @see #get(String)
+ * Return the localized string matching the given key. The given
+ * <code>subs</code> objects will be substituted
+ * into the found string according to the rules of the
+ * {@link MessageFormat} class.
+ *
+ * @see #get(String)
*/
public String get(String key, Object[] subs) {
String str = get(key);
-
return MessageFormat.format(str, subs);
}
/**
- * Return the localized string matching the given key. The given
- * <code>subs</code> objects will be substituted
- * into the found string according to the rules of the
- * {@link MessageFormat} class.
- *
- * @see #getFatal(String)
+ * Return the localized string matching the given key. The given
+ * <code>subs</code> objects will be substituted
+ * into the found string according to the rules of the
+ * {@link MessageFormat} class.
+ *
+ * @see #getFatal(String)
*/
public String getFatal(String key, Object[] subs) {
String str = getFatal(key);
-
return MessageFormat.format(str, subs);
}
private String get(String key, boolean fatal) {
if (_bundle == null) {
- if (fatal) {
+ if (fatal)
throw new MissingResourceException(key, key, key);
- }
-
return key;
}
try {
return _bundle.getString(key);
} catch (MissingResourceException mre) {
- if (!fatal) {
+ if (!fatal)
return key;
- }
-
throw mre;
}
}
Modified: incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/MultiClassLoader.java
URL: http://svn.apache.org/viewvc/incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/MultiClassLoader.java?rev=418401&r1=418400&r2=418401&view=diff
==============================================================================
--- incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/MultiClassLoader.java (original)
+++ incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/MultiClassLoader.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
@@ -16,43 +13,41 @@
package org.apache.openjpa.lib.util;
import java.io.*;
-
import java.net.*;
-
import java.util.*;
-
/**
- * <p>Class loader type that can be configured to delegate to multiple
- * internal class loaders.</p>
- *
- * <p>The {@link #THREAD_LOADER} constant is a marker that will be replaced
- * with the context loader of the current thread.</p>
- *
- * @author Abe White
+ * Class loader type that can be configured to delegate to multiple
+ * internal class loaders.
+ * The {@link #THREAD_LOADER} constant is a marker that will be replaced
+ * with the context loader of the current thread.
+ *
+ * @author Abe White
*/
public class MultiClassLoader extends ClassLoader {
/**
- * Marker that will be replaced with the context loader of the current
- * thread whenever it is discovered in the class loader list.
+ * Marker that will be replaced with the context loader of the current
+ * thread whenever it is discovered in the class loader list.
*/
public static final ClassLoader THREAD_LOADER = null;
/**
- * The standard system class loader.
+ * The standard system class loader.
*/
- public static final ClassLoader SYSTEM_LOADER = ClassLoader.getSystemClassLoader();
+ public static final ClassLoader SYSTEM_LOADER =
+ ClassLoader.getSystemClassLoader();
+
private List _loaders = new ArrayList(5);
/**
- * Constructor; initializes the loader with an empty list of delegates.
+ * Constructor; initializes the loader with an empty list of delegates.
*/
public MultiClassLoader() {
super(null);
}
/**
- * Construct with the class loaders of another multi loader.
+ * Construct with the class loaders of another multi loader.
*/
public MultiClassLoader(MultiClassLoader other) {
super(null);
@@ -60,76 +55,63 @@
}
/**
- * Returns true if the list contains the given class loader or marker.
+ * Returns true if the list contains the given class loader or marker.
*/
public boolean containsClassLoader(ClassLoader loader) {
return _loaders.contains(loader);
}
/**
- * Return an array of all contained class loaders.
+ * Return an array of all contained class loaders.
*/
public ClassLoader[] getClassLoaders() {
ClassLoader[] loaders = new ClassLoader[size()];
ClassLoader loader;
Iterator itr = _loaders.iterator();
-
for (int i = 0; i < loaders.length; i++) {
loader = (ClassLoader) itr.next();
-
- if (loader == THREAD_LOADER) {
+ if (loader == THREAD_LOADER)
loader = Thread.currentThread().getContextClassLoader();
- }
-
loaders[i] = loader;
}
-
return loaders;
}
/**
- * Return the class loader at the given index.
+ * Return the class loader at the given index.
*/
public ClassLoader getClassLoader(int index) {
ClassLoader loader = (ClassLoader) _loaders.get(index);
-
- if (loader == THREAD_LOADER) {
+ if (loader == THREAD_LOADER)
loader = Thread.currentThread().getContextClassLoader();
- }
-
return loader;
}
/**
- * Add the given class loader to the set of loaders that will be tried.
- *
- * @return true if the loader was added, false if already in the list
+ * Add the given class loader to the set of loaders that will be tried.
+ *
+ * @return true if the loader was added, false if already in the list
*/
public boolean addClassLoader(ClassLoader loader) {
- if (_loaders.contains(loader)) {
+ if (_loaders.contains(loader))
return false;
- }
-
return _loaders.add(loader);
}
/**
- * Add the given class loader at the specified index.
- *
- * @return true if the loader was added, false if already in the list
+ * Add the given class loader at the specified index.
+ *
+ * @return true if the loader was added, false if already in the list
*/
public boolean addClassLoader(int index, ClassLoader loader) {
- if (_loaders.contains(loader)) {
+ if (_loaders.contains(loader))
return false;
- }
-
_loaders.add(index, loader);
-
return true;
}
/**
- * Set the class loaders of this loader to those of the given loader.
+ * Set the class loaders of this loader to those of the given loader.
*/
public void setClassLoaders(MultiClassLoader multi) {
clear();
@@ -137,73 +119,67 @@
}
/**
- * Adds all class loaders from the given multi loader starting at the
- * given index.
- *
- * @return true if any loaders were added, false if all already in list
+ * Adds all class loaders from the given multi loader starting at the
+ * given index.
+ *
+ * @return true if any loaders were added, false if all already in list
*/
public boolean addClassLoaders(int index, MultiClassLoader multi) {
- if (multi == null) {
+ if (multi == null)
return false;
- }
// use iterator so that the thread loader is not resolved
boolean added = false;
-
for (Iterator itr = multi._loaders.iterator(); itr.hasNext();) {
if (addClassLoader(index, (ClassLoader) itr.next())) {
index++;
added = true;
}
}
-
return added;
}
/**
- * Adds all the class loaders from the given multi loader.
- *
- * @return true if any loaders were added, false if all already in list
+ * Adds all the class loaders from the given multi loader.
+ *
+ * @return true if any loaders were added, false if all already in list
*/
public boolean addClassLoaders(MultiClassLoader multi) {
- if (multi == null) {
+ if (multi == null)
return false;
- }
// use iterator so that the thread loader is not resolved
boolean added = false;
-
for (Iterator itr = multi._loaders.iterator(); itr.hasNext();)
added = addClassLoader((ClassLoader) itr.next()) || added;
-
return added;
}
/**
- * Remove the given loader from the list.
- *
- * @return true if removed, false if not in list
+ * Remove the given loader from the list.
+ *
+ * @return true if removed, false if not in list
*/
public boolean removeClassLoader(ClassLoader loader) {
return _loaders.remove(loader);
}
/**
- * Clear the list of class loaders.
+ * Clear the list of class loaders.
*/
public void clear() {
_loaders.clear();
}
/**
- * Return the number of internal class loaders.
+ * Return the number of internal class loaders.
*/
public int size() {
return _loaders.size();
}
/**
- * Return true if there are no internal class laoders.
+ * Return true if there are no internal class laoders.
*/
public boolean isEmpty() {
return _loaders.isEmpty();
@@ -211,41 +187,30 @@
protected Class findClass(String name) throws ClassNotFoundException {
ClassLoader loader;
-
for (Iterator itr = _loaders.iterator(); itr.hasNext();) {
loader = (ClassLoader) itr.next();
-
- if (loader == THREAD_LOADER) {
+ if (loader == THREAD_LOADER)
loader = Thread.currentThread().getContextClassLoader();
- }
-
try {
return Class.forName(name, false, loader);
} catch (Throwable t) {
}
}
-
throw new ClassNotFoundException(name);
}
protected URL findResource(String name) {
ClassLoader loader;
URL rsrc;
-
for (Iterator itr = _loaders.iterator(); itr.hasNext();) {
loader = (ClassLoader) itr.next();
-
- if (loader == THREAD_LOADER) {
+ if (loader == THREAD_LOADER)
loader = Thread.currentThread().getContextClassLoader();
- }
rsrc = loader.getResource(name);
-
- if (rsrc != null) {
+ if (rsrc != null)
return rsrc;
- }
}
-
return null;
}
@@ -254,38 +219,27 @@
Enumeration rsrcs;
Object rsrc;
Vector all = new Vector();
-
for (Iterator itr = _loaders.iterator(); itr.hasNext();) {
loader = (ClassLoader) itr.next();
-
- if (loader == THREAD_LOADER) {
+ if (loader == THREAD_LOADER)
loader = Thread.currentThread().getContextClassLoader();
- }
rsrcs = loader.getResources(name);
-
while (rsrcs.hasMoreElements()) {
rsrc = rsrcs.nextElement();
-
- if (!all.contains(rsrc)) {
+ if (!all.contains(rsrc))
all.addElement(rsrc);
- }
}
}
-
return all.elements();
}
public boolean equals(Object other) {
- if (other == this) {
+ if (other == this)
return true;
- }
-
- if (!(other instanceof MultiClassLoader)) {
+ if (!(other instanceof MultiClassLoader))
return false;
- }
-
- return ((MultiClassLoader) other)._loaders.equals(_loaders);
+ return((MultiClassLoader) other)._loaders.equals(_loaders);
}
public int hashCode() {