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 [2/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/m...
Modified: incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/ConfigurationImpl.java
URL: http://svn.apache.org/viewvc/incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/ConfigurationImpl.java?rev=418401&r1=418400&r2=418401&view=diff
==============================================================================
--- incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/ConfigurationImpl.java (original)
+++ incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/ConfigurationImpl.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,59 @@
*/
package org.apache.openjpa.lib.conf;
-import org.apache.commons.lang.*;
-
-import org.apache.openjpa.lib.log.*;
-import org.apache.openjpa.lib.util.*;
-import org.apache.openjpa.lib.util.Closeable;
-
-import serp.util.*;
-
import java.awt.*;
-
import java.beans.*;
-
import java.io.*;
-
import java.lang.reflect.*;
-
import java.util.*;
import java.util.List;
-
+import org.apache.commons.lang.*;
+import org.apache.openjpa.lib.log.*;
+import org.apache.openjpa.lib.util.*;
+import org.apache.openjpa.lib.util.Closeable;
+import serp.util.*;
/**
- * <p>Default implementation of the {@link Configuration} interface.
- * Subclasses can choose to obtain configuration
- * information from JNDI, Properties, a Bean-builder, etc. This class
- * provides base configuration functionality, including serialization,
- * the <code>equals</code> and <code>hashCode</code> contracts, and default
- * property loading.</p>
- *
- * <p>Property descriptors for {@link Value} instances are constructed from
- * the {@link Localizer} for the package of the configuration class. The
- * following localized strings will be used for describing a value, where
- * <em>name</em> is the last token of the value's property string:
- * <ul>
- * <li><em>name</em>-name: The name that will be displayed for the
-* option in a user interface; required.</li>
- * <li><em>name</em>-desc: A brief description of the option; required.</li>
- * <li><em>name</em>-type: The type or category name for this option;
- * required.</li>
- * <li><em>name</em>-expert: True if this is an expert option, false
- * otherwise; defaults to false.</li>
- * <li><em>name</em>-values: Set of expected or common values, excluding
- * alias keys; optional.</li>
- * <li><em>name</em>-interface: The class name of an interface whose
- * discoverable implementations should be included in the set of expected
- * or common values; optional.</li>
- * <li><em>name</em>-cat: The hierarchical category for the property
- * name, separated by ".".
- * <li><em>name</em>-displayorder: The order in which the property should
- * be displayer.</li>
- * </ul></p>
- *
- * @author Abe White
+ * Default implementation of the {@link Configuration} interface.
+ * Subclasses can choose to obtain configuration
+ * information from JNDI, Properties, a Bean-builder, etc. This class
+ * provides base configuration functionality, including serialization,
+ * the <code>equals</code> and <code>hashCode</code> contracts, and default
+ * property loading.
+ * Property descriptors for {@link Value} instances are constructed from
+ * the {@link Localizer} for the package of the configuration class. The
+ * following localized strings will be used for describing a value, where
+ * <em>name</em> is the last token of the value's property string:
+ * <ul>
+ * <li><em>name</em>-name: The name that will be displayed for the
+ * option in a user interface; required.</li>
+ * <li><em>name</em>-desc: A brief description of the option; required.</li>
+ * <li><em>name</em>-type: The type or category name for this option;
+ * required.</li>
+ * <li><em>name</em>-expert: True if this is an expert option, false
+ * otherwise; defaults to false.</li>
+ * <li><em>name</em>-values: Set of expected or common values, excluding
+ * alias keys; optional.</li>
+ * <li><em>name</em>-interface: The class name of an interface whose
+ * discoverable implementations should be included in the set of expected
+ * or common values; optional.</li>
+ * <li><em>name</em>-cat: The hierarchical category for the property
+ * name, separated by ".".
+ * <li><em>name</em>-displayorder: The order in which the property should
+ * be displayer.</li>
+ * </ul>
+ *
+ * @author Abe White
*/
-public class ConfigurationImpl implements Configuration, Externalizable,
- ValueListener {
+public class ConfigurationImpl
+ implements Configuration, Externalizable, ValueListener {
private static final String SEP = System.getProperty("line.separator");
- private static final Localizer _loc = Localizer.forPackage(ConfigurationImpl.class);
+
+ private static final Localizer _loc = Localizer.forPackage
+ (ConfigurationImpl.class);
+
public ObjectValue logFactoryPlugin;
+
private boolean _readOnly = false;
private Map _props = null;
private boolean _defaults = false;
@@ -86,50 +78,44 @@
private MethodDescriptor[] _mds = null;
/**
- * Default constructor. Attempts to load default properties through
- * system's configured {@link ConfigurationProvider}s.
+ * Default constructor. Attempts to load default properties through
+ * system's configured {@link ConfigurationProvider}s.
*/
public ConfigurationImpl() {
this(true);
}
/**
- * Constructor.
- *
- * @param loadDefaults whether to attempt to load the default
- * properties
+ * Constructor.
+ *
+ * @param loadDefaults whether to attempt to load the default properties
*/
public ConfigurationImpl(boolean loadDefaults) {
logFactoryPlugin = addPlugin("org.apache.openjpa.lib.Log", true);
-
String[] aliases = new String[] {
- "true", "org.apache.openjpa.lib.log.LogFactoryImpl", "commons",
- "org.apache.openjpa.lib.log.CommonsLogFactory", "log4j",
- "org.apache.openjpa.lib.log.Log4JLogFactory", "none",
- "org.apache.openjpa.lib.log.NoneLogFactory", "false",
- "org.apache.openjpa.lib.log.NoneLogFactory",
- };
+ "true", "org.apache.openjpa.lib.log.LogFactoryImpl",
+ "commons", "org.apache.openjpa.lib.log.CommonsLogFactory",
+ "log4j", "org.apache.openjpa.lib.log.Log4JLogFactory",
+ "none", "org.apache.openjpa.lib.log.NoneLogFactory",
+ "false", "org.apache.openjpa.lib.log.NoneLogFactory", };
logFactoryPlugin.setAliases(aliases);
logFactoryPlugin.setDefault(aliases[0]);
logFactoryPlugin.setString(aliases[0]);
logFactoryPlugin.setInstantiatingGetter("getLogFactory");
- if (loadDefaults) {
+ if (loadDefaults)
loadDefaults();
- }
}
/**
- * Automatically load default values from the system's
- * {@link ConfigurationProvider}s, and from System properties.
+ * Automatically load default values from the system's
+ * {@link ConfigurationProvider}s, and from System properties.
*/
public boolean loadDefaults() {
- ConfigurationProvider provider = Configurations.loadDefaults(getClass()
- .getClassLoader());
-
- if (provider != null) {
+ ConfigurationProvider provider = Configurations.loadDefaults
+ (getClass().getClassLoader());
+ if (provider != null)
provider.setInto(this);
- }
// let system properties override other defaults
try {
@@ -139,17 +125,12 @@
}
_defaults = true;
-
if (provider == null) {
Log log = getConfigurationLog();
-
- if (log.isTraceEnabled()) {
+ if (log.isTraceEnabled())
log.trace(_loc.get("no-providers"));
- }
-
return false;
}
-
return true;
}
@@ -158,11 +139,9 @@
}
public LogFactory getLogFactory() {
- if (logFactoryPlugin.get() == null) {
+ if (logFactoryPlugin.get() == null)
logFactoryPlugin.instantiate(LogFactory.class, this);
- }
-
- return (LogFactory) logFactoryPlugin.get();
+ return(LogFactory) logFactoryPlugin.get();
}
public void setLogFactory(LogFactory logFactory) {
@@ -184,50 +163,45 @@
}
/**
- * Returns the logging channel <code>org.apache.openjpa.lib.Runtime</code> by
- * default.
+ * Returns the logging channel <code>org.apache.openjpa.lib.Runtime</code> by
+ * default.
*/
public Log getConfigurationLog() {
return getLog("org.apache.openjpa.lib.Runtime");
}
/**
- * Returns the logging channel <code>org.apache.openjpa.lib.Manage</code> by
- * default.
+ * Returns the logging channel <code>org.apache.openjpa.lib.Manage</code> by
+ * default.
*/
public Log getManagementLog() {
return getLog("org.apache.openjpa.lib.Manage");
}
/**
- * Returns the logging channel <code>org.apache.openjpa.lib.Profile</code> by
- * default.
+ * Returns the logging channel <code>org.apache.openjpa.lib.Profile</code> by
+ * default.
*/
public Log getProfilingLog() {
return getLog("org.apache.openjpa.lib.Profile");
}
public Value[] getValues() {
- return (Value[]) _vals.toArray(new Value[_vals.size()]);
+ return(Value[]) _vals.toArray(new Value[_vals.size()]);
}
public Value getValue(String property) {
- if (property == null) {
+ if (property == null)
return null;
- }
// search backwards so that custom values added after construction
// are found quickly, since this will be the std way of accessing them
Value val;
-
for (int i = _vals.size() - 1; i >= 0; i--) {
val = (Value) _vals.get(i);
-
- if (val.getProperty().equals(property)) {
+ if (val.getProperty().equals(property))
return val;
- }
}
-
return null;
}
@@ -242,46 +216,37 @@
String getterName;
Method getter;
Object getterTarget;
-
for (int i = 0; i < _vals.size(); i++) {
val = (Value) _vals.get(i);
getterName = val.getInstantiatingGetter();
-
- if (getterName == null) {
+ if (getterName == null)
continue;
- }
getterTarget = this;
-
if (getterName.startsWith("this.")) {
getterName = getterName.substring("this.".length());
getterTarget = val;
}
try {
- getter = getterTarget.getClass()
- .getMethod(getterName, (Class[]) null);
+ getter = getterTarget.getClass().getMethod(getterName,
+ (Class[]) null);
getter.invoke(getterTarget, (Object[]) null);
} catch (Throwable t) {
- if (t instanceof InvocationTargetException) {
+ if (t instanceof InvocationTargetException)
t = ((InvocationTargetException) t).getTargetException();
- }
-
if (errs == null) {
errs = new StringWriter();
stack = new PrintWriter(errs);
- } else {
+ } else
errs.write(SEP);
- }
-
t.printStackTrace(stack);
stack.flush();
}
}
-
- if (errs != null) {
- throw new RuntimeException(_loc.get("get-prop-errs", errs.toString()));
- }
+ if (errs != null)
+ throw new RuntimeException(_loc.get("get-prop-errs",
+ errs.toString()));
}
public boolean isReadOnly() {
@@ -289,55 +254,46 @@
}
public void addPropertyChangeListener(PropertyChangeListener listener) {
- if (_changeSupport == null) {
+ if (_changeSupport == null)
_changeSupport = new PropertyChangeSupport(this);
- }
-
_changeSupport.addPropertyChangeListener(listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
- if (_changeSupport != null) {
+ if (_changeSupport != null)
_changeSupport.removePropertyChangeListener(listener);
- }
}
public void valueChanged(Value val) {
- if ((_changeSupport == null) && (_props == null)) {
+ if (_changeSupport == null && _props == null)
return;
- }
String newString = val.getString();
-
- if (_changeSupport != null) {
- _changeSupport.firePropertyChange(val.getProperty(), null, newString);
- }
+ if (_changeSupport != null)
+ _changeSupport.firePropertyChange(val.getProperty(), null,
+ newString);
// keep cached props up to date
if (_props != null) {
- if (newString == null) {
+ if (newString == null)
_props.remove(val.getProperty());
- } else if (_props.containsKey(val.getProperty()) ||
- (val.getDefault() == null) ||
- !val.getDefault().equals(newString)) {
+ else if (_props.containsKey(val.getProperty())
+ || val.getDefault() == null
+ || !val.getDefault().equals(newString))
_props.put(val.getProperty(), newString);
- }
}
}
/**
- * Closes all closeable plugins.
+ * Closes all closeable plugins.
*/
public void close() {
ObjectValue val;
-
for (int i = 0; i < _vals.size(); i++) {
- if (!(_vals.get(i) instanceof ObjectValue)) {
+ if (!(_vals.get(i) instanceof ObjectValue))
continue;
- }
val = (ObjectValue) _vals.get(i);
-
if (val.get() instanceof Closeable) {
try {
((Closeable) val.get()).close();
@@ -350,6 +306,7 @@
///////////////////////////
// BeanInfo implementation
///////////////////////////
+
public BeanInfo[] getAdditionalBeanInfo() {
return new BeanInfo[0];
}
@@ -375,61 +332,47 @@
}
public synchronized MethodDescriptor[] getMethodDescriptors() {
- if (_mds != null) {
+ if (_mds != null)
return _mds;
- }
-
PropertyDescriptor[] pds = getPropertyDescriptors();
_mds = new MethodDescriptor[pds.length * 2];
-
for (int i = 0; i < pds.length; i++) {
_mds[i * 2] = new MethodDescriptor(pds[i].getWriteMethod());
_mds[(i * 2) + 1] = new MethodDescriptor(pds[i].getReadMethod());
}
-
return _mds;
}
public synchronized PropertyDescriptor[] getPropertyDescriptors() {
- if (_pds != null) {
+ if (_pds != null)
return _pds;
- }
_pds = new PropertyDescriptor[_vals.size()];
-
List failures = null;
Value val;
-
for (int i = 0; i < _vals.size(); i++) {
val = (Value) _vals.get(i);
-
try {
_pds[i] = getPropertyDescriptor(val);
} catch (MissingResourceException mre) {
- if (failures == null) {
+ if (failures == null)
failures = new ArrayList();
- }
-
failures.add(val.getProperty());
} catch (IntrospectionException ie) {
- if (failures == null) {
+ if (failures == null)
failures = new ArrayList();
- }
-
failures.add(val.getProperty());
}
}
-
- if (failures != null) {
+ if (failures != null)
throw new ParseException(_loc.get("invalid-property-descriptors",
- failures));
- }
+ failures));
return _pds;
}
/**
- * Create a property descriptor for the given value.
+ * Create a property descriptor for the given value.
*/
private PropertyDescriptor getPropertyDescriptor(Value val)
throws IntrospectionException {
@@ -438,110 +381,89 @@
// set up property descriptor
PropertyDescriptor pd;
-
try {
- pd = new PropertyDescriptor(Introspector.decapitalize(prop),
- getClass());
+ pd = new PropertyDescriptor
+ (Introspector.decapitalize(prop), getClass());
} catch (IntrospectionException ie) {
- // if there aren't any methods for this value (i.e., if it's a
+ // if there aren't any methods for this value(i.e., if it's a
// dynamically-added value), then an IntrospectionException will
// be thrown. Try to create a PD with no read or write methods.
pd = new PropertyDescriptor(Introspector.decapitalize(prop),
- (Method) null, (Method) null);
+ (Method) null, (Method) null);
}
-
pd.setDisplayName(findLocalized(prop + "-name", true, val.getScope()));
pd.setShortDescription(findLocalized(prop + "-desc", true,
- val.getScope()));
+ val.getScope()));
pd.setExpert("true".equals(findLocalized(prop + "-expert", false,
- val.getScope())));
+ val.getScope())));
try {
- pd.setReadMethod(getClass()
- .getMethod("get" +
- StringUtils.capitalize(prop), (Class[]) null));
- pd.setWriteMethod(getClass()
- .getMethod("set" +
- StringUtils.capitalize(prop),
- new Class[] { pd.getReadMethod().getReturnType() }));
+ pd.setReadMethod(getClass().getMethod("get"
+ + StringUtils.capitalize(prop), (Class[]) null));
+ pd.setWriteMethod(getClass().getMethod("set"
+ + StringUtils.capitalize(prop), new Class[]
+ {pd.getReadMethod().getReturnType()}));
} catch (Throwable t) {
- // if an error occurs, it might be because the value is a
+ // if an error occurs, it might be because the value is a
// dynamic property.
}
String type = findLocalized(prop + "-type", true, val.getScope());
-
- if (type != null) {
+ if (type != null)
pd.setValue(ATTRIBUTE_TYPE, type);
- }
String cat = findLocalized(prop + "-cat", false, val.getScope());
-
- if (cat != null) {
+ if (cat != null)
pd.setValue(ATTRIBUTE_CATEGORY, cat);
- }
String order = findLocalized(prop + "-displayorder", false,
- val.getScope());
-
- if (order != null) {
+ val.getScope());
+ if (order != null)
pd.setValue(ATTRIBUTE_ORDER, order);
- }
// collect allowed values from alias keys, listed values, and
// interface implementors
Collection allowed = new TreeSet();
List aliases = Collections.EMPTY_LIST;
-
if (val.getAliases() != null) {
aliases = Arrays.asList(val.getAliases());
-
for (int i = 0; i < aliases.size(); i += 2)
allowed.add(aliases.get(i));
}
-
- String[] vals = Strings.split(findLocalized(prop + "-values", false,
- val.getScope()), ",", 0);
-
+ String[] vals = Strings.split(findLocalized(prop
+ + "-values", false, val.getScope()), ",", 0);
for (int i = 0; i < vals.length; i++)
- if (!aliases.contains(vals[i])) {
+ if (!aliases.contains(vals[i]))
allowed.add(vals[i]);
- }
-
try {
- Class intf = Class.forName(findLocalized(prop + "-interface", true,
- val.getScope()), false, getClass().getClassLoader());
+ Class intf = Class.forName(findLocalized(prop
+ + "-interface", true, val.getScope()), false,
+ getClass().getClassLoader());
pd.setValue(ATTRIBUTE_INTERFACE, intf.getName());
-
String[] impls = Services.getImplementors(intf);
-
for (int i = 0; i < impls.length; i++)
- if (!aliases.contains(impls[i])) {
+ if (!aliases.contains(impls[i]))
allowed.add(impls[i]);
- }
} catch (Throwable t) {
}
-
- if (!allowed.isEmpty()) {
- pd.setValue(ATTRIBUTE_ALLOWED_VALUES,
- (String[]) allowed.toArray(new String[allowed.size()]));
- }
+ if (!allowed.isEmpty())
+ pd.setValue(ATTRIBUTE_ALLOWED_VALUES, (String[]) allowed.toArray
+ (new String[allowed.size()]));
return pd;
}
/**
- * Find the given localized string, or return null if not found.
+ * Find the given localized string, or return null if not found.
*/
private String findLocalized(String key, boolean fatal, Class scope) {
// find the localizer package that contains this key
Localizer loc = null;
- // check the package that the value claims to be defined in, if
+ // check the package that the value claims to be defined in, if
// available, before we start guessing.
if (scope != null) {
loc = Localizer.forPackage(scope);
-
try {
return loc.getFatal(key);
} catch (MissingResourceException mse) {
@@ -549,75 +471,61 @@
}
for (Class cls = getClass(); cls != Object.class;
- cls = cls.getSuperclass()) {
+ cls = cls.getSuperclass()) {
loc = Localizer.forPackage(cls);
-
try {
return loc.getFatal(key);
} catch (MissingResourceException mse) {
}
}
- if (fatal) {
+ if (fatal)
throw new MissingResourceException(key, getClass().getName(), key);
- }
-
return null;
}
////////////////
// To/from maps
////////////////
+
public Map toProperties(boolean storeDefaults) {
// clone properties before making any modifications; we need to keep
// the internal properties instance consistent to maintain equals and
// hashcode contracts
Map clone;
-
- if (_props == null) {
+ if (_props == null)
clone = new HashMap();
- } else if (_props instanceof Properties) {
+ else if (_props instanceof Properties)
clone = (Map) ((Properties) _props).clone();
- } else {
+ else
clone = new HashMap(_props);
- }
// if no existing properties or the properties should contain entries
// with default values, add values to properties
- if ((_props == null) || storeDefaults) {
+ if (_props == null || storeDefaults) {
Value val;
String str;
-
for (int i = 0; i < _vals.size(); i++) {
- // if key in existing properties, we already know value is up
+ // if key in existing properties, we already know value is up
// to date
val = (Value) _vals.get(i);
-
- if ((_props != null) && _props.containsKey(val.getProperty())) {
+ if (_props != null && _props.containsKey(val.getProperty()))
continue;
- }
str = val.getString();
-
- if ((str != null) &&
- (storeDefaults || !str.equals(val.getDefault()))) {
+ if (str != null && (storeDefaults
+ || !str.equals(val.getDefault())))
clone.put(val.getProperty(), str);
- }
}
-
- if (_props == null) {
+ if (_props == null)
_props = new HashMap(clone);
- }
}
-
return clone;
}
public void fromProperties(Map map) {
- if ((map == null) || map.isEmpty()) {
+ if (map == null || map.isEmpty())
return;
- }
-
assertNotReadOnly();
// if the only previous call was to load defaults, forget them.
@@ -633,19 +541,15 @@
boolean ser = true;
Value val;
Object set;
-
for (int i = 0; i < _vals.size(); i++) {
val = (Value) _vals.get(i);
set = map.get(val.getProperty());
-
- if (set == null) {
+ if (set == null)
continue;
- }
if (set instanceof String) {
- if (!StringUtils.equals((String) set, val.getString())) {
+ if (!StringUtils.equals((String) set, val.getString()))
val.setString((String) set);
- }
} else {
ser = ser && set instanceof Serializable;
val.setObject(set);
@@ -654,7 +558,7 @@
remaining.remove(val.getProperty());
}
- // convention is to point product at a resource with the
+ // convention is to point product at a resource with the
// <product>.properties System property; remove that property so we
// we don't warn about it
remaining.remove(getProductName() + ".properties");
@@ -662,52 +566,42 @@
// now warn if there are any remaining properties that there
// is an unhandled prop
Map.Entry entry;
-
for (Iterator itr = remaining.entrySet().iterator(); itr.hasNext();) {
entry = (Map.Entry) itr.next();
-
- if (entry.getKey() != null) {
+ if (entry.getKey() != null)
warnInvalidProperty((String) entry.getKey());
- }
-
ser = ser && entry.getValue() instanceof Serializable;
}
// cache properties
- if ((_props == null) && ser) {
+ if (_props == null && ser)
_props = map;
- }
}
/**
- * Issue a warning that the specified property is not valid.
+ * Issue a warning that the specified property is not valid.
*/
private void warnInvalidProperty(String propName) {
- if (!isInvalidProperty(propName)) {
+ if (!isInvalidProperty(propName))
return;
- }
-
Log log = getConfigurationLog();
-
- if ((log == null) || !log.isWarnEnabled()) {
+ if (log == null || !log.isWarnEnabled())
return;
- }
// try to find the closest string to the invalid property
// so that we can provide a hint in case of a misspelling
- String closest = StringDistance.getClosestLevenshteinDistance(propName,
- new PropertyList(), 15);
+ String closest = StringDistance.getClosestLevenshteinDistance
+ (propName, new PropertyList(), 15);
- if (closest == null) {
+ if (closest == null)
log.warn(_loc.get("invalid-property", propName));
- } else {
+ else
log.warn(_loc.get("invalid-property-hint", propName, closest));
- }
}
/**
- * Returns true if the specified property name should raise a warning
- * if it is not found in the list of known properties.
+ * Returns true if the specified property name should raise a warning
+ * if it is not found in the list of known properties.
*/
protected boolean isInvalidProperty(String propName) {
// by default, we don't warn on any properties, since we don't
@@ -716,22 +610,22 @@
}
/**
- * This method loads the named resource as a properties file. It is
- * useful for auto-configuration tools so users can specify a
- * <code>properties</code> value with the name of a resource.
+ * This method loads the named resource as a properties file. It is
+ * useful for auto-configuration tools so users can specify a
+ * <code>properties</code> value with the name of a resource.
*/
public void setProperties(String resourceName) throws IOException {
- Configurations.load(resourceName, getClass().getClassLoader())
- .setInto(this);
+ Configurations.load(resourceName, getClass().getClassLoader()).
+ setInto(this);
}
/**
- * This method loads the named file as a properties file. It is
- * useful for auto-configuration tools so users can specify a
- * <code>propertiesFile</code> value with the name of a file.
+ * This method loads the named file as a properties file. It is
+ * useful for auto-configuration tools so users can specify a
+ * <code>propertiesFile</code> value with the name of a file.
*/
public void setPropertiesFile(File file) throws IOException {
- Configurations.load(file, getClass().getClassLoader()).setInto(this);
+ Configurations.load(file, getClass().getClassLoader()). setInto(this);
}
/////////////
@@ -739,56 +633,47 @@
/////////////
/**
- * Checks if the configuration is read only and if so throws an
- * exception, otherwise returns silently.
- * Implementations should call this method before setting any state.
+ * Checks if the configuration is read only and if so throws an
+ * exception, otherwise returns silently.
+ * Implementations should call this method before setting any state.
*/
public void assertNotReadOnly() {
- if (isReadOnly()) {
+ if (isReadOnly())
throw new IllegalStateException(_loc.get("read-only"));
- }
}
/**
- * Performs an equality check based on the properties returned from
- * {@link #toProperties}.
+ * Performs an equality check based on the properties returned from
+ * {@link #toProperties}.
*/
public boolean equals(Object other) {
- if (other == this) {
+ if (other == this)
return true;
- }
-
- if (other == null) {
+ if (other == null)
return false;
- }
-
- if (!getClass().equals(other.getClass())) {
+ if (!getClass().equals(other.getClass()))
return false;
- }
// compare properties
ConfigurationImpl conf = (ConfigurationImpl) other;
Map p1 = (_props == null) ? toProperties(false) : _props;
Map p2 = (conf._props == null) ? conf.toProperties(false) : conf._props;
-
return p1.equals(p2);
}
/**
- * Computes hash code based on the properties returned from
- * {@link #toProperties}.
+ * Computes hash code based on the properties returned from
+ * {@link #toProperties}.
*/
public int hashCode() {
- if (_props != null) {
+ if (_props != null)
return _props.hashCode();
- }
-
return toProperties(false).hashCode();
}
/**
- * Implementation of the {@link Externalizable} interface to read from
- * the properties written by {@link #writeExternal}.
+ * Implementation of the {@link Externalizable} interface to read from
+ * the properties written by {@link #writeExternal}.
*/
public void readExternal(ObjectInput in)
throws IOException, ClassNotFoundException {
@@ -796,30 +681,27 @@
}
/**
- * Implementation of the {@link Externalizable} interface to write
- * the properties returned by {@link #toProperties}.
+ * Implementation of the {@link Externalizable} interface to write
+ * the properties returned by {@link #toProperties}.
*/
public void writeExternal(ObjectOutput out) throws IOException {
- if (_props != null) {
+ if (_props != null)
out.writeObject(_props);
- } else {
+ else
out.writeObject(toProperties(false));
- }
}
/**
- * Uses {@link #toProperties} and {@link #fromProperties} to clone
- * configuration.
+ * Uses {@link #toProperties} and {@link #fromProperties} to clone
+ * configuration.
*/
public Object clone() {
try {
- Constructor cons = getClass()
- .getConstructor(new Class[] { boolean.class });
- Configuration clone = (Configuration) cons.newInstance(new Object[] {
- Boolean.FALSE
- });
+ Constructor cons = getClass().getConstructor
+ (new Class[] { boolean.class });
+ Configuration clone = (Configuration) cons.newInstance
+ (new Object[] { Boolean.FALSE });
clone.fromProperties(toProperties(true));
-
return clone;
} catch (RuntimeException re) {
throw re;
@@ -829,118 +711,105 @@
}
public boolean removeValue(Value val) {
- if (!_vals.remove(val)) {
+ if (!_vals.remove(val))
return false;
- }
-
val.setListener(null);
-
return true;
}
public Value addValue(Value val) {
_vals.add(val);
val.setListener(this);
-
return val;
}
/**
- * Add the given value to the set of configuration properties.
+ * Add the given value to the set of configuration properties.
*/
public StringValue addString(String property) {
StringValue val = new StringValue(property);
addValue(val);
-
return val;
}
/**
- * Add the given value to the set of configuration properties.
+ * Add the given value to the set of configuration properties.
*/
public FileValue addFile(String property) {
FileValue val = new FileValue(property);
addValue(val);
-
return val;
}
/**
- * Add the given value to the set of configuration properties.
+ * Add the given value to the set of configuration properties.
*/
public IntValue addInt(String property) {
IntValue val = new IntValue(property);
addValue(val);
-
return val;
}
/**
- * Add the given value to the set of configuration properties.
+ * Add the given value to the set of configuration properties.
*/
public DoubleValue addDouble(String property) {
DoubleValue val = new DoubleValue(property);
addValue(val);
-
return val;
}
/**
- * Add the given value to the set of configuration properties.
+ * Add the given value to the set of configuration properties.
*/
public BooleanValue addBoolean(String property) {
BooleanValue val = new BooleanValue(property);
addValue(val);
-
return val;
}
/**
- * Add the given value to the set of configuration properties.
+ * Add the given value to the set of configuration properties.
*/
public StringListValue addStringList(String property) {
StringListValue val = new StringListValue(property);
addValue(val);
-
return val;
}
/**
- * Add the given value to the set of configuration properties.
+ * Add the given value to the set of configuration properties.
*/
public ObjectValue addObject(String property) {
ObjectValue val = new ObjectValue(property);
addValue(val);
-
return val;
}
/**
- * Add the given value to the set of configuration properties.
+ * Add the given value to the set of configuration properties.
*/
public PluginValue addPlugin(String property, boolean singleton) {
PluginValue val = new PluginValue(property, singleton);
addValue(val);
-
return val;
}
/**
- * Add the given value to the set of configuration properties.
+ * Add the given value to the set of configuration properties.
*/
public PluginListValue addPluginList(String property) {
PluginListValue val = new PluginListValue(property);
addValue(val);
-
return val;
}
/**
- * Exposes our values list as a list of property names.
+ * Exposes our values list as a list of property names.
*/
private class PropertyList extends AbstractList {
public Object get(int i) {
- return ((Value) _vals.get(i)).getProperty();
+ return((Value) _vals.get(i)).getProperty();
}
public int size() {
Modified: incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/ConfigurationProvider.java
URL: http://svn.apache.org/viewvc/incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/ConfigurationProvider.java?rev=418401&r1=418400&r2=418401&view=diff
==============================================================================
--- incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/ConfigurationProvider.java (original)
+++ incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/ConfigurationProvider.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,56 +13,54 @@
package org.apache.openjpa.lib.conf;
import java.io.*;
-
import java.util.*;
-
/**
- * Implementations of this interface can populate {@link Configuration}s in
- * some environment-specific way. Implementations must implement the
- * <code>equals</code> and <code>hashCode</code> methods so that equivalent
- * configurations compare equal.
- *
-* @since 4.0.0
- * @nojavadoc */
+ * Implementations of this interface can populate {@link Configuration}s in
+ * some environment-specific way. Implementations must implement the
+ * <code>equals</code> and <code>hashCode</code> methods so that equivalent
+ * configurations compare equal.
+ *
+ * @since 4.0.0
+ * @nojavadoc
+ */
public interface ConfigurationProvider {
/**
- * Load defaults, or return false if no defaults for this provider found.
+ * Load defaults, or return false if no defaults for this provider found.
*/
public boolean loadDefaults(ClassLoader loader) throws Exception;
/**
- * Load the given given resource, or return false if it is not a resource
- * this provider understands. The given class loader may be null.
+ * Load the given given resource, or return false if it is not a resource
+ * this provider understands. The given class loader may be null.
*/
- public boolean load(String resource, ClassLoader loader)
- throws Exception;
+ public boolean load(String resource, ClassLoader loader) throws Exception;
/**
- * Load given file, or return false if it is not a file this provider
- * understands.
+ * Load given file, or return false if it is not a file this provider
+ * understands.
*/
public boolean load(File file) throws Exception;
/**
- * Return properties loaded thus far, or empty map if none.
+ * Return properties loaded thus far, or empty map if none.
*/
public Map getProperties();
/**
- * Add the given properties to those in this provider, overwriting
- * any exisitng properties under the same keys.
+ * Add the given properties to those in this provider, overwriting
+ * any exisitng properties under the same keys.
*/
public void addProperties(Map props);
/**
- * Add a single property, overwriting any existing property under the
- * same key.
+ * Add a single property, overwriting any existing property under the
+ * same key.
*/
public Object addProperty(String key, Object value);
/**
- * Set loaded information into the given configuration.
+ * Set loaded information into the given configuration.
*/
public void setInto(Configuration conf);
}
Modified: incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/Configurations.java
URL: http://svn.apache.org/viewvc/incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/Configurations.java?rev=418401&r1=418400&r2=418401&view=diff
==============================================================================
--- incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/Configurations.java (original)
+++ incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/Configurations.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,175 +12,137 @@
*/
package org.apache.openjpa.lib.conf;
+import java.io.*;
+import java.util.*;
+import javax.naming.*;
import org.apache.commons.lang.exception.*;
-
import org.apache.openjpa.lib.log.*;
import org.apache.openjpa.lib.util.*;
-
import serp.util.*;
-import java.io.*;
-
-import java.util.*;
-
-import javax.naming.*;
-
-
/**
- * <p>Utility methods dealing with configuration.</p>
- *
- * @author Abe White
- * @nojavadoc */
+ * Utility methods dealing with configuration.
+ *
+ * @author Abe White
+ * @nojavadoc
+ */
public class Configurations {
- private static final Localizer _loc = Localizer.forPackage(Configurations.class);
+ private static final Localizer _loc = Localizer.forPackage
+ (Configurations.class);
/**
- * Return the class name from the given plugin string, or null if none.
- */
+ * Return the class name from the given plugin string, or null if none.
+ */
public static String getClassName(String plugin) {
return getPluginComponent(plugin, true);
}
/**
- * Return the properties part of the given plugin string, or null if none.
+ * Return the properties part of the given plugin string, or null if none.
*/
public static String getProperties(String plugin) {
return getPluginComponent(plugin, false);
}
/**
- * Return either the class name or properties string from a plugin string.
+ * Return either the class name or properties string from a plugin string.
*/
private static String getPluginComponent(String plugin, boolean clsName) {
- if (plugin != null) {
+ if (plugin != null)
plugin = plugin.trim();
- }
-
- if ((plugin == null) || (plugin.length() == 0)) {
+ if (plugin == null || plugin.length() == 0)
return null;
- }
int openParen = -1;
-
- if (plugin.charAt(plugin.length() - 1) == ')') {
+ if (plugin.charAt(plugin.length() - 1) == ')')
openParen = plugin.indexOf('(');
- }
-
if (openParen == -1) {
int eq = plugin.indexOf('=');
-
- if (eq == -1) {
- return (clsName) ? plugin : null;
- }
-
- return (clsName) ? null : plugin;
+ if (eq == -1)
+ return(clsName) ? plugin : null;
+ return(clsName) ? null : plugin;
}
// clsName(props) form
- if (clsName) {
+ if (clsName)
return plugin.substring(0, openParen).trim();
- }
-
- String prop = plugin.substring(openParen + 1, plugin.length() - 1).trim();
-
- return (prop.length() == 0) ? null : prop;
+ String prop = plugin.substring(openParen + 1,
+ plugin.length() - 1).trim();
+ return(prop.length() == 0) ? null : prop;
}
/**
- * Combine the given class name and properties into a plugin string.
+ * Combine the given class name and properties into a plugin string.
*/
public static String getPlugin(String clsName, String props) {
- if ((clsName == null) || (clsName.length() == 0)) {
+ if (clsName == null || clsName.length() == 0)
return props;
- }
-
- if ((props == null) || (props.length() == 0)) {
+ if (props == null || props.length() == 0)
return clsName;
- }
-
return clsName + "(" + props + ")";
}
/**
- * Create the instance with the given class name, using the given
- * class loader. No configuration of the instance is performed by
- * this method.
+ * Create the instance with the given class name, using the given
+ * class loader. No configuration of the instance is performed by
+ * this method.
*/
public static Object newInstance(String clsName, ClassLoader loader) {
return newInstance(clsName, null, null, loader, true);
}
/**
- * Create and configure an instance with the given class name and
- * properties.
+ * Create and configure an instance with the given class name and
+ * properties.
*/
public static Object newInstance(String clsName, Configuration conf,
String props, ClassLoader loader) {
Object obj = newInstance(clsName, null, conf, loader, true);
configureInstance(obj, conf, props);
-
return obj;
}
/**
- * Helper method used by members of this package to instantiate plugin
- * values.
+ * Helper method used by members of this package to instantiate plugin
+ * values.
*/
static Object newInstance(String clsName, Value val, Configuration conf,
ClassLoader loader, boolean fatal) {
- if ((clsName == null) || (clsName.length() == 0)) {
+ if (clsName == null || clsName.length() == 0)
return null;
- }
-
- if ((loader == null) && (conf != null)) {
+ if (loader == null && conf != null)
loader = conf.getClass().getClassLoader();
- }
Class cls = null;
-
try {
cls = Strings.toClass(clsName, loader);
} catch (RuntimeException re) {
- if (val != null) {
+ if (val != null)
re = getCreateException(clsName, val, re);
- }
-
- if (fatal) {
+ if (fatal)
throw re;
- }
-
Log log = (conf == null) ? null : conf.getConfigurationLog();
-
- if ((log != null) && log.isErrorEnabled()) {
+ if (log != null && log.isErrorEnabled())
log.error(re);
- }
-
return null;
}
try {
return cls.newInstance();
} catch (Exception e) {
- RuntimeException re = new NestableRuntimeException(_loc.get(
- "obj-create", cls), e);
-
- if (fatal) {
+ RuntimeException re = new NestableRuntimeException(_loc.get
+ ("obj-create", cls), e);
+ if (fatal)
throw re;
- }
-
Log log = (conf == null) ? null : conf.getConfigurationLog();
-
- if ((log != null) && log.isErrorEnabled()) {
+ if (log != null && log.isErrorEnabled())
log.error(re);
- }
-
return null;
}
}
/**
- * Helper method to throw an informative description on instantiation
- * error.
+ * Helper method to throw an informative description on instantiation error.
*/
private static RuntimeException getCreateException(String clsName,
Value val, Exception e) {
@@ -194,47 +153,41 @@
String alias = val.alias(clsName);
String[] aliases = val.getAliases();
String[] keys;
-
- if (aliases.length == 0) {
+ if (aliases.length == 0)
keys = aliases;
- } else {
+ else {
keys = new String[aliases.length / 2];
-
for (int i = 0; i < aliases.length; i += 2)
keys[i / 2] = aliases[i];
}
String closest;
-
if (keys.length == 0) {
msg = "invalid-plugin";
params = new Object[] { val.getProperty(), alias, e.toString(), };
- } else if ((closest = StringDistance.getClosestLevenshteinDistance(
- alias, keys, 0.5f)) == null) {
+ } else if ((closest = StringDistance.getClosestLevenshteinDistance
+ (alias, keys, 0.5f)) == null) {
msg = "invalid-plugin-aliases";
params = new Object[] {
- val.getProperty(), alias, e.toString(),
- new TreeSet(Arrays.asList(keys)),
- };
+ val.getProperty(), alias, e.toString(),
+ new TreeSet(Arrays.asList(keys)), };
} else {
msg = "invalid-plugin-aliases-hint";
params = new Object[] {
- val.getProperty(), alias, e.toString(),
- new TreeSet(Arrays.asList(keys)), closest,
- };
+ val.getProperty(), alias, e.toString(),
+ new TreeSet(Arrays.asList(keys)), closest, };
}
-
return new ParseException(_loc.get(msg, params), e);
}
/**
- * Configures the given object with the given properties by
- * matching the properties string to the object's setter
- * methods. The properties string should be in the form
- * "prop1=val1, prop2=val2 ...". Does not validate that setter
- * methods exist for the properties.
- *
- * @throws RuntimeException on configuration error
+ * Configures the given object with the given properties by
+ * matching the properties string to the object's setter
+ * methods. The properties string should be in the form
+ * "prop1=val1, prop2=val2 ...". Does not validate that setter
+ * methods exist for the properties.
+ *
+ * @throws RuntimeException on configuration error
*/
public static void configureInstance(Object obj, Configuration conf,
String properties) {
@@ -242,36 +195,31 @@
}
/**
- * Configures the given object with the given properties by
- * matching the properties string to the object's setter
- * methods. The properties string should be in the form
- * "prop1=val1, prop2=val2 ...". Validates that setter methods
- * exist for the properties.
- *
- * @throws RuntimeException on configuration error
+ * Configures the given object with the given properties by
+ * matching the properties string to the object's setter
+ * methods. The properties string should be in the form
+ * "prop1=val1, prop2=val2 ...". Validates that setter methods
+ * exist for the properties.
+ *
+ * @throws RuntimeException on configuration error
*/
public static void configureInstance(Object obj, Configuration conf,
String properties, String configurationName) {
- if (obj == null) {
+ if (obj == null)
return;
- }
Properties props = null;
-
- if ((properties != null) && (properties.length() > 0)) {
+ if (properties != null && properties.length() > 0)
props = parseProperties(properties);
- }
-
configureInstance(obj, conf, props, configurationName);
}
/**
- * Configures the given object with the given properties by
- * matching the properties string to the object's setter
- * methods. Does not validate that setter methods exist for the
- * properties.
- *
- * @throws RuntimeException on configuration error
+ * Configures the given object with the given properties by
+ * matching the properties string to the object's setter
+ * methods. Does not validate that setter methods exist for the properties.
+ *
+ * @throws RuntimeException on configuration error
*/
public static void configureInstance(Object obj, Configuration conf,
Properties properties) {
@@ -279,133 +227,105 @@
}
/**
- * Configures the given object with the given properties by
- * matching the properties string to the object's setter
- * methods. If <code>configurationName</code> is
- * non-<code>null</code>, validates that setter methods exist for
- * the properties.
- *
- * @throws RuntimeException on configuration error
+ * Configures the given object with the given properties by
+ * matching the properties string to the object's setter
+ * methods. If <code>configurationName</code> is
+ * non-<code>null</code>, validates that setter methods exist for
+ * the properties.
+ *
+ * @throws RuntimeException on configuration error
*/
public static void configureInstance(Object obj, Configuration conf,
Properties properties, String configurationName) {
- if (obj == null) {
+ if (obj == null)
return;
- }
Options opts = null;
-
- if (properties instanceof Options) {
+ if (properties instanceof Options)
opts = (Options) properties;
- } else if (properties != null) {
+ else if (properties != null) {
opts = new Options();
opts.putAll(properties);
}
Configurable configurable = null;
-
- if ((conf != null) && obj instanceof Configurable) {
+ if (conf != null && obj instanceof Configurable)
configurable = (Configurable) obj;
- }
if (configurable != null) {
configurable.setConfiguration(conf);
configurable.startConfiguration();
}
-
if (opts != null) {
Map invalidEntries = opts.setInto(obj);
-
- if (obj instanceof GenericConfigurable) {
+ if (obj instanceof GenericConfigurable)
((GenericConfigurable) obj).setInto(invalidEntries);
- }
- if (!invalidEntries.isEmpty() && (configurationName != null)) {
+ if (!invalidEntries.isEmpty() && configurationName != null) {
String msg = null;
- String first = (String) invalidEntries.keySet().iterator().next();
-
- if ((invalidEntries.keySet().size() == 1) &&
- (first.indexOf('.') == -1)) {
+ String first = (String) invalidEntries.keySet().iterator()
+ .next();
+ if (invalidEntries.keySet().size() == 1 &&
+ first.indexOf('.') == -1) {
// if there's just one misspelling and this is not a
// path traversal, check for near misses.
Collection options = Options.findOptionsFor(obj.getClass());
- String close = StringDistance.getClosestLevenshteinDistance(first,
- options, 0.75f);
-
- if (close != null) {
+ String close = StringDistance.getClosestLevenshteinDistance
+ (first, options, 0.75f);
+ if (close != null)
msg = _loc.get("invalid-config-param-hint",
- new Object[] {
- configurationName, obj.getClass(), first,
- close, options,
- });
- }
+ new Object[] {
+ configurationName, obj.getClass(), first, close,
+ options, });
}
if (msg == null) {
- msg = _loc.get("invalid-config-params",
- new String[] {
- configurationName, obj.getClass().getName(),
- invalidEntries.keySet().toString(),
- Options.findOptionsFor(obj.getClass()).toString(),
- });
+ msg = _loc.get("invalid-config-params", new String[] {
+ configurationName, obj.getClass().getName(),
+ invalidEntries.keySet().toString(),
+ Options.findOptionsFor(obj.getClass()).toString(), });
}
-
throw new ParseException(msg);
}
}
-
- if (configurable != null) {
+ if (configurable != null)
configurable.endConfiguration();
- }
}
/**
- * Turn a set of properties into a comma-separated string.
+ * Turn a set of properties into a comma-separated string.
*/
public static String serializeProperties(Map map) {
- if ((map == null) || map.isEmpty()) {
+ if (map == null || map.isEmpty())
return null;
- }
StringBuffer buf = new StringBuffer();
Map.Entry entry;
String val;
-
for (Iterator itr = map.entrySet().iterator(); itr.hasNext();) {
entry = (Map.Entry) itr.next();
-
- if (buf.length() > 0) {
+ if (buf.length() > 0)
buf.append(", ");
- }
-
buf.append(entry.getKey()).append('=');
val = String.valueOf(entry.getValue());
-
- if (val.indexOf(',') != -1) {
+ if (val.indexOf(',') != -1)
buf.append('"').append(val).append('"');
- } else {
+ else
buf.append(val);
- }
}
-
return buf.toString();
}
/**
- * Parse a set of properties from a comma-separated string.
+ * Parse a set of properties from a comma-separated string.
*/
public static Options parseProperties(String properties) {
Options opts = new Options();
-
- if (properties == null) {
+ if (properties == null)
return opts;
- }
-
properties = properties.trim();
-
- if (properties.length() == 0) {
+ if (properties.length() == 0)
return opts;
- }
try {
String[] props = Strings.split(properties, ",", 0);
@@ -413,10 +333,8 @@
char quote;
String prop;
String val;
-
for (int i = 0; i < props.length; i++) {
idx = props[i].indexOf('=');
-
if (idx == -1) {
// if the key is not assigned to any value, set the
// value to the same thing as the key, and continue.
@@ -434,32 +352,25 @@
}
// if the value is quoted, read until the end quote
- if (((val.startsWith("\"") && val.endsWith("\"")) ||
- (val.startsWith("'") && val.endsWith("'"))) &&
- (val.length() > 1)) {
+ if (((val.startsWith("\"") && val.endsWith("\""))
+ || (val.startsWith("'") && val.endsWith("'")))
+ && val.length() > 1)
val = val.substring(1, val.length() - 1);
- } else if (val.startsWith("\"") || val.startsWith("'")) {
+ else if (val.startsWith("\"") || val.startsWith("'")) {
quote = val.charAt(0);
-
StringBuffer buf = new StringBuffer(val.substring(1));
int quotIdx;
-
while (++i < props.length) {
buf.append(",");
quotIdx = props[i].indexOf(quote);
-
if (quotIdx != -1) {
buf.append(props[i].substring(0, quotIdx));
-
- if ((quotIdx + 1) < props[i].length()) {
+ if (quotIdx + 1 < props[i].length())
buf.append(props[i].substring(quotIdx + 1));
- }
-
break;
- } else {
+ } else
buf.append(props[i]);
- }
}
val = buf.toString();
@@ -467,7 +378,6 @@
opts.put(prop, val);
}
-
return opts;
} catch (RuntimeException re) {
throw new ParseException(_loc.get("prop-parse", properties), re);
@@ -475,203 +385,164 @@
}
/**
- * Set the given {@link Configuration} instance from the command line
- * options provided. All property names of the given configuration are
- * recognized; additionally, if a <code>properties</code> or
- * <code>p</code> argument exists, the resource it
- * points to will be loaded and set into the given configuration instance.
- * It can point to either a file or a resource name.
+ * Set the given {@link Configuration} instance from the command line
+ * options provided. All property names of the given configuration are
+ * recognized; additionally, if a <code>properties</code> or
+ * <code>p</code> argument exists, the resource it
+ * points to will be loaded and set into the given configuration instance.
+ * It can point to either a file or a resource name.
*/
public static void populateConfiguration(Configuration conf, Options opts) {
String props = opts.removeProperty("properties", "p", null);
-
- if ((props != null) && (props.length() > 0)) {
+ if (props != null && props.length() > 0) {
File file = new File(props);
ConfigurationProvider provider;
-
- if (file.isFile()) {
+ if (file.isFile())
provider = load(file, null);
- } else {
+ else {
file = new File("META-INF" + File.separatorChar + props);
-
- if (file.isFile()) {
+ if (file.isFile())
provider = load(file, null);
- } else {
+ else
provider = load(props, null);
- }
}
-
provider.setInto(conf);
}
-
opts.setInto(conf);
}
/**
- * Return a {@link ConfigurationProvider} that has parsed system defaults.
+ * Return a {@link ConfigurationProvider} that has parsed system defaults.
*/
public static ConfigurationProvider loadDefaults(ClassLoader loader) {
- if (loader == null) {
+ if (loader == null)
loader = Thread.currentThread().getContextClassLoader();
- }
-
- Class[] impls = Services.getImplementorClasses(ConfigurationProvider.class,
- loader);
+ Class[] impls = Services.getImplementorClasses
+ (ConfigurationProvider.class, loader);
ConfigurationProvider provider = null;
StringBuffer errs = null;
-
for (int i = 0; i < impls.length; i++) {
provider = newProvider(impls[i]);
-
try {
- if ((provider != null) && provider.loadDefaults(loader)) {
+ if (provider != null && provider.loadDefaults(loader))
return provider;
- }
} catch (MissingResourceException mre) {
throw mre;
} catch (Exception e) {
- if (errs == null) {
+ if (errs == null)
errs = new StringBuffer();
- } else {
+ else
errs.append(", ");
- }
-
errs.append(e.toString());
}
}
-
- if (errs != null) {
+ if (errs != null)
throw new MissingResourceException(errs.toString(),
Configurations.class.getName(), "defaults");
- }
return null;
}
/**
- * Return a new new configuration provider instance of the given class,
- * or null if the class cannot be instantiated.
+ * Return a new new configuration provider instance of the given class,
+ * or null if the class cannot be instantiated.
*/
private static ConfigurationProvider newProvider(Class cls) {
try {
- return (ConfigurationProvider) cls.newInstance();
+ return(ConfigurationProvider) cls.newInstance();
} catch (Throwable e) {
return null;
}
}
/**
- * Return a {@link ConfigurationProvider} that has parsed the given
- * resource. Throws {@link MissingResourceException} if resource does
- * not exist.
- */
- public static ConfigurationProvider load(String resource, ClassLoader loader) {
- if ((resource == null) || (resource.length() == 0)) {
+ * Return a {@link ConfigurationProvider} that has parsed the given
+ * resource. Throws {@link MissingResourceException} if resource does
+ * not exist.
+ */
+ public static ConfigurationProvider load(String resource,
+ ClassLoader loader) {
+ if (resource == null || resource.length() == 0)
return null;
- }
- if (loader == null) {
+ if (loader == null)
loader = Thread.currentThread().getContextClassLoader();
- }
-
- Class[] impls = Services.getImplementorClasses(ConfigurationProvider.class,
- loader);
+ Class[] impls = Services.getImplementorClasses
+ (ConfigurationProvider.class, loader);
ConfigurationProvider provider = null;
StringBuffer errs = null;
-
for (int i = 0; i < impls.length; i++) {
provider = newProvider(impls[i]);
-
try {
- if ((provider != null) && provider.load(resource, loader)) {
+ if (provider != null && provider.load(resource, loader))
return provider;
- }
} catch (MissingResourceException mre) {
throw mre;
} catch (Exception e) {
- if (errs == null) {
+ if (errs == null)
errs = new StringBuffer();
- } else {
+ else
errs.append(", ");
- }
-
errs.append(e.toString());
}
}
-
String msg = (errs == null) ? resource : errs.toString();
- throw new MissingResourceException(msg, Configurations.class.getName(),
- resource);
+ throw new MissingResourceException(msg,
+ Configurations.class.getName(), resource);
}
/**
- * Return a {@link ConfigurationProvider} that has parsed the given
- * file. Throws {@link MissingResourceException} if file does
- * not exist.
+ * Return a {@link ConfigurationProvider} that has parsed the given
+ * file. Throws {@link MissingResourceException} if file does not exist.
*/
public static ConfigurationProvider load(File file, ClassLoader loader) {
- if (file == null) {
+ if (file == null)
return null;
- }
- if (loader == null) {
+ if (loader == null)
loader = Thread.currentThread().getContextClassLoader();
- }
-
- Class[] impls = Services.getImplementorClasses(ConfigurationProvider.class,
- loader);
+ Class[] impls = Services.getImplementorClasses
+ (ConfigurationProvider.class, loader);
ConfigurationProvider provider = null;
StringBuffer errs = null;
-
for (int i = 0; i < impls.length; i++) {
provider = newProvider(impls[i]);
-
try {
- if ((provider != null) && provider.load(file)) {
+ if (provider != null && provider.load(file))
return provider;
- }
} catch (MissingResourceException mre) {
throw mre;
} catch (Exception e) {
- if (errs == null) {
+ if (errs == null)
errs = new StringBuffer();
- } else {
+ else
errs.append(", ");
- }
-
errs.append(e.toString());
}
}
-
String msg = (errs == null) ? file.toString() : errs.toString();
- throw new MissingResourceException(msg, Configurations.class.getName(),
- file.toString());
+ throw new MissingResourceException(msg,
+ Configurations.class.getName(), file.toString());
}
/**
- * Looks up the given name in JNDI. If the name is null, null is
- * returned.
+ * Looks up the given name in JNDI. If the name is null, null is returned.
*/
public static Object lookup(String name) {
- if ((name == null) || (name.length() == 0)) {
+ if (name == null || name.length() == 0)
return null;
- }
Context ctx = null;
-
try {
ctx = new InitialContext();
-
return ctx.lookup(name);
} catch (NamingException ne) {
- throw new NestableRuntimeException(_loc.get("naming-err", name), ne);
- } finally {
- if (ctx != null) {
- try {
- ctx.close();
- } catch (Exception e) {
- }
- }
+ throw new NestableRuntimeException(_loc.get("naming-err", name),
+ ne);
+ }
+ finally {
+ if (ctx != null)
+ try { ctx.close(); } catch (Exception e) {}
}
}
}
Modified: incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/DoubleValue.java
URL: http://svn.apache.org/viewvc/incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/DoubleValue.java?rev=418401&r1=418400&r2=418401&view=diff
==============================================================================
--- incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/DoubleValue.java (original)
+++ incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/DoubleValue.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,11 +12,10 @@
*/
package org.apache.openjpa.lib.conf;
-
/**
- * A double {@link Value}.
- *
- * @author Marc Prud'hommeaux
+ * A double {@link Value}.
+ *
+ * @author Marc Prud'hommeaux
*/
public class DoubleValue extends Value {
private double value;
@@ -33,19 +29,17 @@
}
/**
- * The internal value.
+ * The internal value.
*/
public void set(double value) {
double oldValue = this.value;
this.value = value;
-
- if (oldValue != value) {
+ if (oldValue != value)
valueChanged();
- }
}
/**
- * The internal value.
+ * The internal value.
*/
public double get() {
return value;
@@ -56,18 +50,16 @@
}
protected void setInternalString(String val) {
- if ((val == null) || (val.length() == 0)) {
+ if (val == null || val.length() == 0)
set(0D);
- } else {
+ else
set(Double.parseDouble(val));
- }
}
protected void setInternalObject(Object obj) {
- if (obj == null) {
+ if (obj == null)
set(0D);
- } else {
+ else
set(((Number) obj).doubleValue());
- }
}
}
Modified: incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/FileValue.java
URL: http://svn.apache.org/viewvc/incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/FileValue.java?rev=418401&r1=418400&r2=418401&view=diff
==============================================================================
--- incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/FileValue.java (original)
+++ incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/FileValue.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,15 +12,13 @@
*/
package org.apache.openjpa.lib.conf;
-import org.apache.commons.lang.*;
-
import java.io.*;
-
+import org.apache.commons.lang.*;
/**
- * A {@link File} {@link Value}.
- *
- * @author Marc Prud'hommeaux
+ * A {@link File} {@link Value}.
+ *
+ * @author Marc Prud'hommeaux
*/
public class FileValue extends Value {
private File value;
@@ -37,26 +32,24 @@
}
/**
- * The internal value.
+ * The internal value.
*/
public void set(File value) {
File oldValue = this.value;
this.value = value;
-
- if (!ObjectUtils.equals(oldValue, value)) {
+ if (!ObjectUtils.equals(oldValue, value))
valueChanged();
- }
}
/**
- * The internal value.
+ * The internal value.
*/
public File get() {
return value;
}
protected String getInternalString() {
- return (value == null) ? null : value.getAbsolutePath();
+ return(value == null) ? null : value.getAbsolutePath();
}
protected void setInternalString(String val) {
@@ -67,3 +60,4 @@
set((File) obj);
}
}
+
Modified: incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/GenericConfigurable.java
URL: http://svn.apache.org/viewvc/incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/GenericConfigurable.java?rev=418401&r1=418400&r2=418401&view=diff
==============================================================================
--- incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/GenericConfigurable.java (original)
+++ incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/GenericConfigurable.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,21 @@
import java.util.*;
-
/**
- * <p>Implementations of this interface may perform additional
- * generic configuration with any key-value pairs that cannot be set
- * into the object via the normal {@link org.apache.openjpa.lib.util.Options#setInto}
- * means.</p>
- *
- * @author Patrick Linskey
+ * Implementations of this interface may perform additional
+ * generic configuration with any key-value pairs that cannot be set
+ * into the object via the normal {@link org.apache.openjpa.lib.util.Options#setInto}
+ * means.
+ *
+ * @author Patrick Linskey
*/
public interface GenericConfigurable {
/**
- * Perform any generic configuration based on the data in
- * <code>m</code>. This method should remove any values in
- * <code>m</code> that have been successfully processed; if any
- * values remain in <code>m</code> after this method is executed,
- * an exception will be thrown identifying those key-value pairs
- * as invalid.
+ * Perform any generic configuration based on the data in
+ * <code>m</code>. This method should remove any values in
+ * <code>m</code> that have been successfully processed; if any
+ * values remain in <code>m</code> after this method is executed,
+ * an exception will be thrown identifying those key-value pairs as invalid.
*/
public void setInto(Map m);
}
Modified: incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/IntValue.java
URL: http://svn.apache.org/viewvc/incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/IntValue.java?rev=418401&r1=418400&r2=418401&view=diff
==============================================================================
--- incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/IntValue.java (original)
+++ incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/IntValue.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,11 +14,10 @@
import serp.util.*;
-
/**
- * An int {@link Value}.
- *
- * @author Marc Prud'hommeaux
+ * An int {@link Value}.
+ *
+ * @author Marc Prud'hommeaux
*/
public class IntValue extends Value {
private int value;
@@ -35,19 +31,17 @@
}
/**
- * The internal value.
+ * The internal value.
*/
public void set(int value) {
int oldValue = this.value;
this.value = value;
-
- if (value != oldValue) {
+ if (value != oldValue)
valueChanged();
- }
}
/**
- * The internal value.
+ * The internal value.
*/
public int get() {
return this.value;
@@ -58,18 +52,16 @@
}
protected void setInternalString(String val) {
- if ((val == null) || (val.length() == 0)) {
+ if (val == null || val.length() == 0)
set(0);
- } else {
+ else
set(Integer.parseInt(val));
- }
}
protected void setInternalObject(Object obj) {
- if (obj == null) {
+ if (obj == null)
set(0);
- } else {
+ else
set(((Number) obj).intValue());
- }
}
}
Modified: incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/MapConfigurationProvider.java
URL: http://svn.apache.org/viewvc/incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/MapConfigurationProvider.java?rev=418401&r1=418400&r2=418401&view=diff
==============================================================================
--- incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/MapConfigurationProvider.java (original)
+++ incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/MapConfigurationProvider.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,34 +12,33 @@
*/
package org.apache.openjpa.lib.conf;
+import java.io.*;
+import java.util.*;
import org.apache.commons.collections.*;
-
import org.apache.openjpa.lib.log.*;
import org.apache.openjpa.lib.util.*;
-import java.io.*;
-
-import java.util.*;
-
-
/**
- * <p>Simple configuration provider that sets configuration based on a
- * provided map.</p>
- *
- * @author Abe White
- * @nojavadoc */
+ * Simple configuration provider that sets configuration based on a
+ * provided map.
+ *
+ * @author Abe White
+ * @nojavadoc
+ */
public class MapConfigurationProvider implements ConfigurationProvider {
- private static final Localizer _loc = Localizer.forPackage(MapConfigurationProvider.class);
+ private static final Localizer _loc = Localizer.forPackage
+ (MapConfigurationProvider.class);
+
private Map _props = null;
/**
- * Construct with null properties.
+ * Construct with null properties.
*/
public MapConfigurationProvider() {
}
/**
- * Constructor; supply properties map.
+ * Constructor; supply properties map.
*/
public MapConfigurationProvider(Map props) {
addProperties(props);
@@ -52,8 +48,7 @@
return false;
}
- public boolean load(String resource, ClassLoader loader)
- throws Exception {
+ public boolean load(String resource, ClassLoader loader) throws Exception {
return false;
}
@@ -62,26 +57,20 @@
}
public Map getProperties() {
- return (_props == null) ? Collections.EMPTY_MAP : _props;
+ return(_props == null) ? Collections.EMPTY_MAP : _props;
}
public void addProperties(Map props) {
- if ((props == null) || props.isEmpty()) {
+ if (props == null || props.isEmpty())
return;
- }
-
- if (_props == null) {
+ if (_props == null)
_props = new HashMap();
- }
-
_props.putAll(props);
}
public Object addProperty(String key, Object value) {
- if (_props == null) {
+ if (_props == null)
_props = new HashMap();
- }
-
return _props.put(key, value);
}
@@ -90,16 +79,13 @@
}
/**
- * Set properties into configuration. If the log is non-null, will log
- * a TRACE message about the set.
+ * Set properties into configuration. If the log is non-null, will log
+ * a TRACE message about the set.
*/
protected void setInto(Configuration conf, Log log) {
- if ((log != null) && log.isTraceEnabled()) {
+ if (log != null && log.isTraceEnabled())
log.trace(_loc.get("conf-load", getProperties()));
- }
-
- if (_props != null) {
+ if (_props != null)
conf.fromProperties(_props);
- }
}
}