OPENJPA-2057: Reverting previous commits.

git-svn-id: https://svn.apache.org/repos/asf/openjpa/trunk@1197994 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Richard G. Curtis 2011-11-05 17:17:26 +00:00
parent 8a72661ea0
commit 3d5b44956d
247 changed files with 3312 additions and 2480 deletions

View File

@ -31,7 +31,6 @@ import org.apache.openjpa.lib.conf.ConfigurationImpl;
import org.apache.openjpa.lib.util.Files;
import org.apache.openjpa.lib.util.J2DoPrivHelper;
import org.apache.openjpa.lib.util.Localizer;
import org.apache.openjpa.lib.util.MultiClassLoader;
import org.apache.openjpa.util.MultiLoaderClassResolver;
/**
@ -187,15 +186,19 @@ public class MappingToolTask
throws Exception {
if (MappingTool.ACTION_IMPORT.equals(flags.action))
assertFiles(files);
MultiClassLoader loader = new MultiClassLoader();
ClassLoader toolLoader = AccessController.doPrivileged(J2DoPrivHelper
ClassLoader toolLoader = AccessController
.doPrivileged(J2DoPrivHelper
.getClassLoaderAction(MappingTool.class));
loader.addClassLoader(toolLoader);
ClassLoader loader = toolLoader;
MultiLoaderClassResolver resolver = new MultiLoaderClassResolver();
if (tmpClassLoader) {
loader.addClassLoader(AccessController.doPrivileged(J2DoPrivHelper
.newTemporaryClassLoaderAction(getClassLoader())));
loader = AccessController.doPrivileged(J2DoPrivHelper
.newTemporaryClassLoaderAction(getClassLoader()));
resolver.addClassLoader(loader);
}
resolver.addClassLoader(toolLoader);
if (flags.meta && MappingTool.ACTION_ADD.equals(flags.action))
flags.metaDataFile = Files.getFile(file, loader);
@ -206,11 +209,11 @@ public class MappingToolTask
flags.sqlWriter = Files.getWriter(sqlFile, loader, sqlEncode);
JDBCConfiguration conf = (JDBCConfiguration) getConfiguration();
conf.addClassLoader(loader);
conf.setClassResolver(resolver);
if (!MappingTool.run(conf, files, flags, loader)) {
throw new BuildException(_loc.get("bad-conf", "MappingToolTask").getMessage());
}
if (!MappingTool.run(conf, files, flags, loader))
throw new BuildException(_loc.get("bad-conf", "MappingToolTask")
.getMessage());
}
public static class Action
@ -226,7 +229,8 @@ public class MappingToolTask
public String[] getValues() {
String[] actions = new String[SchemaTool.ACTIONS.length + 1];
System.arraycopy(SchemaTool.ACTIONS, 0, actions, 0, SchemaTool.ACTIONS.length);
System.arraycopy(SchemaTool.ACTIONS, 0, actions, 0,
SchemaTool.ACTIONS.length);
actions[actions.length - 1] = "none";
return actions;
}

View File

@ -276,7 +276,11 @@ public class ReverseMappingToolTask
// create and configure customizer
JDBCConfiguration conf = (JDBCConfiguration) getConfiguration();
flags.customizer = (ReverseCustomizer) Configurations.newInstance(customizerClass, conf, (String)null);
flags.customizer = (ReverseCustomizer) Configurations.
newInstance(customizerClass, conf, (String)null,
AccessController.doPrivileged(
J2DoPrivHelper.getClassLoaderAction(
ReverseCustomizer.class)));
if (flags.customizer != null)
flags.customizer.setConfiguration(customProps);

View File

@ -131,8 +131,7 @@ public class SchemaToolTask
this.file = file;
}
@Override
protected JDBCConfigurationImpl newConfiguration() {
protected ConfigurationImpl newConfiguration() {
return new JDBCConfigurationImpl();
}

View File

@ -42,12 +42,9 @@ import org.apache.openjpa.jdbc.sql.DBDictionaryFactory;
import org.apache.openjpa.jdbc.sql.MaxDBDictionary;
import org.apache.openjpa.jdbc.sql.SQLFactory;
import org.apache.openjpa.kernel.BrokerImpl;
import org.apache.openjpa.kernel.FinderCache;
import org.apache.openjpa.kernel.PreparedQueryCache;
import org.apache.openjpa.kernel.StoreContext;
import org.apache.openjpa.lib.conf.IntValue;
import org.apache.openjpa.lib.conf.ObjectValue;
import org.apache.openjpa.lib.conf.PluginListValue;
import org.apache.openjpa.lib.conf.PluginValue;
import org.apache.openjpa.lib.conf.ProductDerivations;
import org.apache.openjpa.lib.conf.StringListValue;
@ -80,16 +77,16 @@ public class JDBCConfigurationImpl
public FetchModeValue subclassFetchMode;
public IntValue lrsSize;
public StringValue synchronizeMappings;
public PluginListValue<JDBCListener> jdbcListenerPlugins;
public PluginListValue<ConnectionDecorator> connectionDecoratorPlugins;
public PluginValue<DBDictionary> dbdictionaryPlugin;
public ObjectValue<UpdateManager> updateManagerPlugin;
public ObjectValue<SchemaFactory> schemaFactoryPlugin;
public ObjectValue<SQLFactory> sqlFactoryPlugin;
public ObjectValue<MappingDefaults> mappingDefaultsPlugin;
public PluginValue<DriverDataSource> driverDataSourcePlugin;
public ObjectValue jdbcListenerPlugins;
public ObjectValue connectionDecoratorPlugins;
public PluginValue dbdictionaryPlugin;
public ObjectValue updateManagerPlugin;
public ObjectValue schemaFactoryPlugin;
public ObjectValue sqlFactoryPlugin;
public ObjectValue mappingDefaultsPlugin;
public PluginValue driverDataSourcePlugin;
public MappingFactoryValue mappingFactoryPlugin;
public ObjectValue<DBIdentifierUtil> identifierUtilPlugin;
public ObjectValue identifierUtilPlugin;
// used internally
private String firstUser = null;
@ -195,15 +192,15 @@ public class JDBCConfigurationImpl
synchronizeMappings.setAliases(aliases);
synchronizeMappings.setDefault(aliases[0]);
jdbcListenerPlugins = addPluginList(JDBCListener[].class, "jdbc.JDBCListeners");
jdbcListenerPlugins = addPluginList("jdbc.JDBCListeners");
jdbcListenerPlugins.setInstantiatingGetter("getJDBCListenerInstances");
connectionDecoratorPlugins = addPluginList(ConnectionDecorator[].class,
"jdbc.ConnectionDecorators");
connectionDecoratorPlugins = addPluginList
("jdbc.ConnectionDecorators");
connectionDecoratorPlugins.setInstantiatingGetter
("getConnectionDecoratorInstances");
dbdictionaryPlugin = addPlugin(DBDictionary.class, "jdbc.DBDictionary", true);
dbdictionaryPlugin = addPlugin("jdbc.DBDictionary", true);
aliases = new String[]{
"access", "org.apache.openjpa.jdbc.sql.AccessDictionary",
"db2", "org.apache.openjpa.jdbc.sql.DB2Dictionary",
@ -227,7 +224,7 @@ public class JDBCConfigurationImpl
dbdictionaryPlugin.setAliases(aliases);
dbdictionaryPlugin.setInstantiatingGetter("getDBDictionaryInstance");
updateManagerPlugin = addPlugin(UpdateManager.class, "jdbc.UpdateManager", true);
updateManagerPlugin = addPlugin("jdbc.UpdateManager", true);
aliases = new String[]{
"default",
BatchingConstraintUpdateManager.class.getName(),
@ -245,7 +242,7 @@ public class JDBCConfigurationImpl
updateManagerPlugin.setString(aliases[0]);
updateManagerPlugin.setInstantiatingGetter("getUpdateManagerInstance");
driverDataSourcePlugin = addPlugin(DriverDataSource.class, "jdbc.DriverDataSource", false);
driverDataSourcePlugin = addPlugin("jdbc.DriverDataSource", false);
aliases = new String[]{
"auto", "org.apache.openjpa.jdbc.schema.AutoDriverDataSource",
"simple", "org.apache.openjpa.jdbc.schema.SimpleDriverDataSource",
@ -255,7 +252,7 @@ public class JDBCConfigurationImpl
driverDataSourcePlugin.setDefault(aliases[0]);
driverDataSourcePlugin.setString(aliases[0]);
schemaFactoryPlugin = addPlugin(SchemaFactory.class, "jdbc.SchemaFactory", true);
schemaFactoryPlugin = addPlugin("jdbc.SchemaFactory", true);
aliases = new String[]{
"dynamic", "org.apache.openjpa.jdbc.schema.DynamicSchemaFactory",
"native", "org.apache.openjpa.jdbc.schema.LazySchemaFactory",
@ -269,7 +266,7 @@ public class JDBCConfigurationImpl
schemaFactoryPlugin.setString(aliases[0]);
schemaFactoryPlugin.setInstantiatingGetter("getSchemaFactoryInstance");
sqlFactoryPlugin = addPlugin(SQLFactory.class, "jdbc.SQLFactory", true);
sqlFactoryPlugin = addPlugin("jdbc.SQLFactory", true);
aliases = new String[]{
"default", "org.apache.openjpa.jdbc.sql.SQLFactoryImpl",
};
@ -281,14 +278,15 @@ public class JDBCConfigurationImpl
mappingFactoryPlugin = new MappingFactoryValue("jdbc.MappingFactory");
addValue(mappingFactoryPlugin);
mappingDefaultsPlugin = addPlugin(MappingDefaults.class, "jdbc.MappingDefaults", true);
mappingDefaultsPlugin = addPlugin("jdbc.MappingDefaults", true);
aliases = new String[]{
"default", "org.apache.openjpa.jdbc.meta.MappingDefaultsImpl",
};
mappingDefaultsPlugin.setAliases(aliases);
mappingDefaultsPlugin.setDefault(aliases[0]);
mappingDefaultsPlugin.setString(aliases[0]);
mappingDefaultsPlugin.setInstantiatingGetter("getMappingDefaultsInstance");
mappingDefaultsPlugin.setInstantiatingGetter
("getMappingDefaultsInstance");
// set up broker factory defaults
brokerFactoryPlugin.setAlias("jdbc", JDBCBrokerFactory.class.getName());
@ -319,7 +317,7 @@ public class JDBCConfigurationImpl
// This plug-in is declared in superclass but defined here
// because PreparedQueryCache is currently available for JDBC
// backend only
preparedQueryCachePlugin = addPlugin(PreparedQueryCache.class, "jdbc.QuerySQLCache", true);
preparedQueryCachePlugin = addPlugin("jdbc.QuerySQLCache", true);
aliases = new String[] {
"true", "org.apache.openjpa.jdbc.kernel.PreparedQueryCacheImpl",
"false", null
@ -332,7 +330,7 @@ public class JDBCConfigurationImpl
preparedQueryCachePlugin.setInstantiatingGetter(
"getQuerySQLCacheInstance");
finderCachePlugin = addPlugin(FinderCache.class, "jdbc.FinderCache", true);
finderCachePlugin = addPlugin("jdbc.FinderCache", true);
aliases = new String[] {
"true", "org.apache.openjpa.jdbc.kernel.FinderCacheImpl",
"false", null
@ -344,7 +342,7 @@ public class JDBCConfigurationImpl
finderCachePlugin.setDynamic(true);
finderCachePlugin.setInstantiatingGetter("getFinderCacheInstance");
identifierUtilPlugin = addPlugin(DBIdentifierUtil.class, "jdbc.IdentifierUtil", true);
identifierUtilPlugin = addPlugin("jdbc.IdentifierUtil", true);
aliases = new String[] {
"default", "org.apache.openjpa.jdbc.identifier.DBIdentifierUtilImpl" };
identifierUtilPlugin.setAliases(aliases);
@ -527,8 +525,8 @@ public class JDBCConfigurationImpl
public JDBCListener[] getJDBCListenerInstances() {
if (jdbcListenerPlugins.get() == null)
jdbcListenerPlugins.instantiate(this);
return jdbcListenerPlugins.get();
jdbcListenerPlugins.instantiate(JDBCListener.class, this);
return (JDBCListener[]) jdbcListenerPlugins.get();
}
public void setConnectionDecorators(String connectionDecorators) {
@ -545,9 +543,10 @@ public class JDBCConfigurationImpl
public ConnectionDecorator[] getConnectionDecoratorInstances() {
if (connectionDecoratorPlugins.get() == null) {
connectionDecoratorPlugins.instantiate(this);
connectionDecoratorPlugins.instantiate
(ConnectionDecorator.class, this);
}
return connectionDecoratorPlugins.get();
return (ConnectionDecorator[]) connectionDecoratorPlugins.get();
}
public void setDBDictionary(String dbdictionary) {
@ -624,8 +623,8 @@ public class JDBCConfigurationImpl
public UpdateManager getUpdateManagerInstance() {
if (updateManagerPlugin.get() == null)
updateManagerPlugin.instantiate(this);
return updateManagerPlugin.get();
updateManagerPlugin.instantiate(UpdateManager.class, this);
return (UpdateManager) updateManagerPlugin.get();
}
public void setDriverDataSource(String driverDataSource) {
@ -637,7 +636,8 @@ public class JDBCConfigurationImpl
}
public DriverDataSource newDriverDataSourceInstance() {
return driverDataSourcePlugin.instantiate(this);
return (DriverDataSource) driverDataSourcePlugin.
instantiate(DriverDataSource.class, this);
}
public void setSchemaFactory(String schemaFactory) {
@ -654,8 +654,8 @@ public class JDBCConfigurationImpl
public SchemaFactory getSchemaFactoryInstance() {
if (schemaFactoryPlugin.get() == null)
schemaFactoryPlugin.instantiate(this);
return schemaFactoryPlugin.get();
schemaFactoryPlugin.instantiate(SchemaFactory.class, this);
return (SchemaFactory) schemaFactoryPlugin.get();
}
public void setSQLFactory(String sqlFactory) {
@ -672,8 +672,8 @@ public class JDBCConfigurationImpl
public SQLFactory getSQLFactoryInstance() {
if (sqlFactoryPlugin.get() == null)
sqlFactoryPlugin.instantiate(this);
return sqlFactoryPlugin.get();
sqlFactoryPlugin.instantiate(SQLFactory.class, this);
return (SQLFactory) sqlFactoryPlugin.get();
}
public String getMappingFactory() {
@ -703,8 +703,8 @@ public class JDBCConfigurationImpl
public MappingDefaults getMappingDefaultsInstance() {
if (mappingDefaultsPlugin.get() == null)
mappingDefaultsPlugin.instantiate(this);
return mappingDefaultsPlugin.get();
mappingDefaultsPlugin.instantiate(MappingDefaults.class, this);
return (MappingDefaults) mappingDefaultsPlugin.get();
}
public MappingRepository getMappingRepositoryInstance() {
@ -989,8 +989,8 @@ public class JDBCConfigurationImpl
public DBIdentifierUtil getIdentifierUtilInstance() {
if (identifierUtilPlugin.get() == null)
identifierUtilPlugin.instantiate(this);
return identifierUtilPlugin.get();
identifierUtilPlugin.instantiate(DBIdentifierUtil.class, this);
return (DBIdentifierUtil) identifierUtilPlugin.get();
}
public void setIdentifierUtil(DBIdentifierUtil util) {

View File

@ -36,15 +36,16 @@ import org.apache.openjpa.meta.MetaDataFactory;
* @nojavadoc
*/
public class MappingFactoryValue
extends PluginValue<MetaDataFactory> {
extends PluginValue {
private static final Localizer _loc = Localizer.forPackage(MappingFactoryValue.class);
private static final Localizer _loc = Localizer.forPackage
(MappingFactoryValue.class);
private String[] _metaFactoryDefaults = null;
private String[] _mappedMetaFactoryDefaults = null;
public MappingFactoryValue(String prop) {
super(MetaDataFactory.class, prop, false);
super(prop, false);
}
/**
@ -56,7 +57,8 @@ public class MappingFactoryValue
*/
public void setMetaDataFactoryDefault(String metaAlias,
String mappingAlias) {
_metaFactoryDefaults = setAlias(metaAlias, mappingAlias, _metaFactoryDefaults);
_metaFactoryDefaults = setAlias(metaAlias, mappingAlias,
_metaFactoryDefaults);
}
/**
@ -70,20 +72,20 @@ public class MappingFactoryValue
}
/**
* Instantiate a {@link MetaDataFactory} responsible for both metadata and
* Intantiate a {@link MetaDataFactory} responsible for both metadata and
* mapping.
*/
public MetaDataFactory instantiateMetaDataFactory(Configuration conf,
PluginValue<MetaDataFactory> metaPlugin, String mapping) {
PluginValue metaPlugin, String mapping) {
return instantiateMetaDataFactory(conf, metaPlugin, mapping, true);
}
/**
* Instantiate a {@link MetaDataFactory} responsible for both metadata and
* Intantiate a {@link MetaDataFactory} responsible for both metadata and
* mapping.
*/
public MetaDataFactory instantiateMetaDataFactory(Configuration conf,
PluginValue<MetaDataFactory> metaPlugin, String mapping, boolean fatal) {
PluginValue metaPlugin, String mapping, boolean fatal) {
String clsName = getClassName();
String props = getProperties();
String metaClsName = metaPlugin.getClassName();
@ -93,13 +95,14 @@ public class MappingFactoryValue
if (StringUtils.isEmpty(clsName)) {
String def;
if (!StringUtils.isEmpty(mapping)) {
def = unalias(metaPlugin.alias(metaClsName), _mappedMetaFactoryDefaults, true);
if (def != null) {
def = unalias(metaPlugin.alias(metaClsName),
_mappedMetaFactoryDefaults, true);
if (def != null)
clsName = unalias(def);
}
}
if (StringUtils.isEmpty(clsName)) {
def = unalias(metaPlugin.alias(metaClsName), _metaFactoryDefaults, true);
def = unalias(metaPlugin.alias(metaClsName),
_metaFactoryDefaults, true);
if (def != null)
clsName = unalias(def);
}
@ -108,16 +111,17 @@ public class MappingFactoryValue
// if mapping factory and metadata factory the same, combine
// into metadata factory
if (clsName != null && clsName.equals(metaClsName)) {
if (props != null && metaProps == null) {
if (props != null && metaProps == null)
metaProps = props;
} else if (props != null)
else if (props != null)
metaProps += "," + props;
clsName = null;
props = null;
}
// instantiate factories
MetaDataFactory map = newInstance(clsName, conf, fatal);
MetaDataFactory map = (MetaDataFactory) newInstance(clsName,
MetaDataFactory.class, conf, fatal);
MetaDataFactory meta;
if (map != null
&& map.getClass().getName().indexOf("Deprecated") != -1) {
@ -126,7 +130,8 @@ public class MappingFactoryValue
meta = map;
map = null;
} else {
meta = metaPlugin.newInstance(metaClsName, conf, fatal);
meta = (MetaDataFactory) metaPlugin.newInstance
(metaClsName, MetaDataFactory.class, conf, fatal);
}
// configure factories. if only meta factory, allow user to specify
@ -137,8 +142,10 @@ public class MappingFactoryValue
else
metaProps += ", " + props;
}
Configurations.configureInstance(map, conf, props, (fatal) ? getProperty() : null);
Configurations.configureInstance(meta, conf, metaProps, (fatal) ? metaPlugin.getProperty() : null);
Configurations.configureInstance(map, conf, props,
(fatal) ? getProperty() : null);
Configurations.configureInstance(meta, conf, metaProps,
(fatal) ? metaPlugin.getProperty() : null);
Log log = conf.getLog(JDBCConfiguration.LOG_METADATA);
if (log.isTraceEnabled()) {
@ -149,12 +156,20 @@ public class MappingFactoryValue
// if no mapping setting, return meta factory alone, assuming it handles
// both metadata and mapping
if (map == null) {
return meta;
} else {
boolean strict = (conf instanceof OpenJPAConfiguration)
&& ((OpenJPAConfiguration)conf).getCompatibilityInstance().getMetaFactoriesAreStrict();
return new MetaDataPlusMappingFactory(meta, map, strict);
MetaDataFactory ret = null;
if(map == null ) {
ret = meta;
}
else {
if( conf instanceof OpenJPAConfiguration) {
ret = new MetaDataPlusMappingFactory(meta, map, (OpenJPAConfiguration) conf);
}
else {
ret = new MetaDataPlusMappingFactory(meta, map);
}
}
return ret;
}
}

View File

@ -36,19 +36,20 @@ import serp.util.Strings;
* @nojavadoc
*/
public class MappingRepositoryValue
extends PluginValue<MappingRepository> {
extends PluginValue {
public MappingRepositoryValue(String prop) {
super(MappingRepository.class, prop, true);
super(prop, true);
}
public MappingRepository newInstance(String clsName, Configuration conf, boolean fatal) {
public Object newInstance(String clsName, Class type,
Configuration conf, boolean fatal) {
// since the MappingRepository takes a JDBConfiguration constructor,
// we need to manually perform the instantiation
try {
Class<MappingRepository> cls = Strings.toClass(clsName,
Class cls = Strings.toClass(clsName,
AccessController.doPrivileged(
J2DoPrivHelper.getClassLoaderAction(getValueType())));
J2DoPrivHelper.getClassLoaderAction(type)));
return cls.getConstructor(new Class[]{ JDBCConfiguration.class }).
newInstance(new Object[]{ conf });
} catch (RuntimeException e) {
@ -58,10 +59,10 @@ public class MappingRepositoryValue
throw(RuntimeException) e.getTargetException();
// fall back to default behavior for better error reporting
return super.newInstance(clsName, conf, fatal);
return super.newInstance(clsName, type, conf, fatal);
} catch (Exception e) {
// fall back to default behavior for better error reporting
return super.newInstance(clsName, conf, fatal);
return super.newInstance(clsName, type, conf, fatal);
}
}
}

View File

@ -187,16 +187,18 @@ public class ClassTableJDBCSeq
/**
* Run the tool. Returns false if invalid options were given.
*/
public static boolean run(JDBCConfiguration conf, String[] args, Options opts) throws Exception {
public static boolean run(JDBCConfiguration conf, String[] args,
Options opts) throws Exception {
String action = opts.removeProperty("action", "a", null);
Configurations.populateConfiguration(conf, opts);
return run(conf, args, action, null);
return run(conf, args, action, null, null);
}
/**
* Run the tool. Return false if an invalid option was given.
*/
public static boolean run(JDBCConfiguration conf, String[] args, String action, MappingRepository repos)
public static boolean run(JDBCConfiguration conf, String[] args,
String action, MappingRepository repos, ClassLoader loader)
throws Exception {
ClassTableJDBCSeq seq = new ClassTableJDBCSeq();
String props = Configurations.getProperties(conf.getSequence());
@ -214,14 +216,18 @@ public class ClassTableJDBCSeq
if (args.length == 0)
return false;
if (loader == null)
loader = conf.getClassResolverInstance().getClassLoader(
ClassTableJDBCSeq.class, null);
ClassArgParser cap = conf.getMetaDataRepositoryInstance()
.getMetaDataFactory().newClassArgParser();
cap.setClassLoader(conf.getClassLoader());
cap.setClassLoader(loader);
Class<?> cls = cap.parseTypes(args[0])[0];
if (repos == null)
repos = conf.getMappingRepositoryInstance();
ClassMapping mapping = repos.getMapping(cls, true);
ClassMapping mapping = repos.getMapping(cls, null, true);
Connection conn = conf.getDataSource2(null).getConnection();
try {

View File

@ -49,8 +49,11 @@ public class GenericResultObjectProvider
* @param fetch the fetch configuration, or null for default
* @param res the result containing the data
*/
public GenericResultObjectProvider(Class<?> pcClass, JDBCStore store, JDBCFetchConfiguration fetch, Result res) {
this(store.getConfiguration().getMappingRepositoryInstance().getMapping(pcClass, true), store, fetch, res);
public GenericResultObjectProvider(Class<?> pcClass,
JDBCStore store, JDBCFetchConfiguration fetch, Result res) {
this(store.getConfiguration().getMappingRepositoryInstance().getMapping
(pcClass, store.getContext().getClassLoader(), true),
store, fetch, res);
}
/**

View File

@ -65,7 +65,7 @@ public class JDBCBrokerFactory
* Factory method for obtaining a possibly-pooled factory from properties.
* Invoked from {@link Bootstrap#getBrokerFactory}.
*/
public static JDBCBrokerFactory getInstance(ConfigurationProvider cp) {
public static JDBCBrokerFactory getInstance(ConfigurationProvider cp, ClassLoader loader) {
Map<String, Object> props = cp.getProperties();
Object key = toPoolKey(props);
JDBCBrokerFactory factory = (JDBCBrokerFactory) getPooledFactoryForKey(key);
@ -73,7 +73,7 @@ public class JDBCBrokerFactory
return factory;
// The creation of all BrokerFactories should be driven through Bootstrap.
factory = (JDBCBrokerFactory) Bootstrap.newBrokerFactory(cp);
factory = (JDBCBrokerFactory) Bootstrap.newBrokerFactory(cp, loader);
pool(key, factory);
return factory;
}
@ -119,7 +119,7 @@ public class JDBCBrokerFactory
// global login is given
if (!_synchronizedMappings) {
_synchronizedMappings = true;
synchronizeMappings();
synchronizeMappings(broker.getClassLoader());
}
return broker;
@ -131,13 +131,14 @@ public class JDBCBrokerFactory
/**
* Synchronize the mappings of the classes listed in the configuration.
*/
protected void synchronizeMappings(JDBCConfiguration conf) {
protected void synchronizeMappings(ClassLoader loader,
JDBCConfiguration conf) {
String action = conf.getSynchronizeMappings();
if (StringUtils.isEmpty(action))
return;
MappingRepository repo = conf.getMappingRepositoryInstance();
Collection<Class<?>> classes = repo.loadPersistentTypes(false);
Collection<Class<?>> classes = repo.loadPersistentTypes(false, loader);
if (classes.isEmpty())
return;
@ -159,7 +160,7 @@ public class JDBCBrokerFactory
tool.record();
}
protected void synchronizeMappings() {
synchronizeMappings((JDBCConfiguration) getConfiguration());
protected void synchronizeMappings(ClassLoader loader) {
synchronizeMappings(loader, (JDBCConfiguration) getConfiguration());
}
}

View File

@ -1504,7 +1504,8 @@ public class JDBCStoreManager implements StoreManager, JDBCStore {
return;
// if the subclass list is set, no need to load subs
if (mapping.getRepository().getPersistentTypeNames(false) != null) {
if (mapping.getRepository().getPersistentTypeNames(false,
_ctx.getClassLoader()) != null) {
dsc.setSubclassesLoaded(true);
return;
}

View File

@ -367,7 +367,8 @@ public class PreparedQueryImpl implements PreparedQuery {
.getInnermostDelegate();
MappingRepository repos = store.getConfiguration()
.getMappingRepositoryInstance();
ClassMapping mapping = repos.getMapping(pc.getClass(), true);
ClassMapping mapping = repos.getMapping(pc.getClass(),
broker.getClassLoader(), true);
Column[] pks = mapping.getPrimaryKeyColumns();
Object cols = mapping.toDataStoreValue(pc, pks, store);
if (cols instanceof Object[]) {

View File

@ -294,11 +294,11 @@ public class PreparedStatementManagerImpl
* log any SQL warnings that result from the execution of a SQL statement.
*/
protected void logSQLWarnings(PreparedStatement stmt) {
if (stmt != null && _log != null && _log.isWarnEnabled()) {
if (stmt != null && _log != null && _log.isTraceEnabled()) {
try {
SQLWarning warn = stmt.getWarnings();
while (warn != null) {
_log.warn(_loc.get("sql-warning", warn.getMessage()));
_log.trace(_loc.get("sql-warning", warn.getMessage()));
warn = warn.getNextWarning();
}
} catch (SQLException e) {}

View File

@ -112,8 +112,12 @@ public class SQLStoreQuery
if (resultMapping == null)
_resultMapping = null;
else {
MappingRepository repos = q.getStore().getConfiguration().getMappingRepositoryInstance();
_resultMapping = repos.getQueryResultMapping(ctx.getResultMappingScope(), resultMapping, true);
ClassLoader envLoader = ctx.getStoreContext().getClassLoader();
MappingRepository repos = q.getStore().getConfiguration().
getMappingRepositoryInstance();
_resultMapping = repos.getQueryResultMapping
(ctx.getResultMappingScope(), resultMapping, envLoader,
true);
}
_meta = candidate;

View File

@ -138,33 +138,41 @@ public class CollectionParam
}
}
public void calculateValue(Select sel, ExpContext ctx, ExpState state, Val other, ExpState otherState) {
public void calculateValue(Select sel, ExpContext ctx, ExpState state,
Val other, ExpState otherState) {
super.calculateValue(sel, ctx, state, other, otherState);
ParamExpState pstate = (ParamExpState) state;
Object value = getValue(ctx.params);
if (!(value instanceof Collection))
throw new IllegalArgumentException(_loc.get("not-collection-parm", _key).toString());
throw new IllegalArgumentException(_loc.get(
"not-collection-parm", _key).toString());
if (((Collection) value).isEmpty())
throw new IllegalArgumentException(_loc.get("empty-collection-parm", _key).toString());
throw new IllegalArgumentException(_loc.get(
"empty-collection-parm", _key).toString());
Iterator itr = ((Collection) value).iterator();
for (int i = 0; i < pstate.size && itr.hasNext(); i++) {
Object val = itr.next();
if (other != null && !_container) {
pstate.sqlValue[i] = other.toDataStoreValue(sel, ctx, otherState, val);
pstate.sqlValue[i] = other.toDataStoreValue(sel, ctx,
otherState, val);
pstate.otherLength[i] = other.length(sel, ctx, otherState);
if (other instanceof Type) {
pstate.mapping[i] = ctx.store.getConfiguration().
getMappingRepositoryInstance().getMapping((Class) val, true);
getMappingRepositoryInstance().getMapping((Class) val,
ctx.store.getContext().getClassLoader(), true);
pstate.disc[i] = pstate.mapping[i].getDiscriminator();
pstate.discValue[i] = pstate.disc[i] != null ? pstate.disc[i].getValue() : null;
pstate.discValue[i] = pstate.disc[i] != null ?
pstate.disc[i].getValue() : null;
}
} else if (ImplHelper.isManageable(val)) {
ClassMapping mapping = ctx.store.getConfiguration().
getMappingRepositoryInstance().getMapping(val.getClass(), true);
pstate.sqlValue[i] = mapping.toDataStoreValue(val, mapping.getPrimaryKeyColumns(), ctx.store);
getMappingRepositoryInstance().getMapping(val.getClass(),
ctx.store.getContext().getClassLoader(), true);
pstate.sqlValue[i] = mapping.toDataStoreValue(val,
mapping.getPrimaryKeyColumns(), ctx.store);
pstate.otherLength[i] = mapping.getPrimaryKeyColumns().length;
} else
pstate.sqlValue[i] = val;
@ -176,13 +184,16 @@ public class CollectionParam
ParamExpState pstate = (ParamExpState) state;
for (int i = 0; i < pstate.size; i++) {
if (pstate.otherLength[i] > 1)
sql.appendValue(((Object[]) pstate.sqlValue[i])[index], pstate.getColumn(index), this);
sql.appendValue(((Object[]) pstate.sqlValue[i])[index],
pstate.getColumn(index), this);
else if (pstate.cols != null)
sql.appendValue(pstate.sqlValue[i], pstate.getColumn(index), this);
sql.appendValue(pstate.sqlValue[i], pstate.getColumn(index),
this);
else if (pstate.discValue[i] != null)
sql.appendValue(pstate.discValue[i]);
else
sql.appendValue(pstate.sqlValue[i], pstate.getColumn(index), this);
sql.appendValue(pstate.sqlValue[i], pstate.getColumn(index),
this);
}
}
}

View File

@ -86,7 +86,8 @@ class InstanceofExpression
// cache mapping for cast
MappingRepository repos = ctx.store.getConfiguration().
getMappingRepositoryInstance();
mapping = repos.getMapping(_cls, false);
mapping = repos.getMapping(_cls, ctx.store.getContext().
getClassLoader(), false);
// if not looking for a PC, don't bother with indicator
if (mapping == null || !discrim.hasClassConditions(mapping, true))

View File

@ -81,7 +81,7 @@ public class Param
Object[] params = ctx.params;
if (params[_idx] != null && params[_idx] instanceof Class)
return (ClassMapping) ctx.store.getConfiguration().getMetaDataRepositoryInstance().
getMetaData((Class) params[_idx], true);
getMetaData((Class) params[_idx], getClass().getClassLoader(), true);
return null;
}
@ -126,14 +126,17 @@ public class Param
pstate.otherLength = other.length(sel, ctx, otherState);
if (other instanceof Type) {
pstate.mapping = ctx.store.getConfiguration().
getMappingRepositoryInstance().getMapping((Class) val, true);
getMappingRepositoryInstance().getMapping((Class) val,
ctx.store.getContext().getClassLoader(), true);
pstate.disc = pstate.mapping.getDiscriminator();
pstate.discValue = pstate.disc.getValue() != null ? pstate.disc.getValue() : "1";
}
} else if (ImplHelper.isManageable(val)) {
ClassMapping mapping = ctx.store.getConfiguration().
getMappingRepositoryInstance().getMapping(val.getClass(), true);
pstate.sqlValue = mapping.toDataStoreValue(val, mapping.getPrimaryKeyColumns(), ctx.store);
getMappingRepositoryInstance().getMapping(val.getClass(),
ctx.store.getContext().getClassLoader(), true);
pstate.sqlValue = mapping.toDataStoreValue(val,
mapping.getPrimaryKeyColumns(), ctx.store);
pstate.otherLength = mapping.getPrimaryKeyColumns().length;
} else
pstate.sqlValue = val;

View File

@ -209,7 +209,8 @@ public class ClassMapping
try {
Class dtype = cls.getDiscriminator().getClass(store, cls, res);
if (dtype != cls.getDescribedType())
dcls = cls.getMappingRepository().getMapping(dtype, true);
dcls = cls.getMappingRepository().getMapping(dtype,
store.getContext().getClassLoader(), true);
} catch (Exception e) {
// intentionally ignored
}

View File

@ -473,7 +473,8 @@ public class FieldMapping
// copy embedded template mapping info
ClassMapping cls = getDefiningMapping();
if (cls.getEmbeddingMapping() != null) {
ClassMapping orig = repos.getMapping(cls.getDescribedType(), true);
ClassMapping orig = repos.getMapping(cls.getDescribedType(),
cls.getEnvClassLoader(), true);
FieldMapping tmplate = orig.getFieldMapping(getName());
if (tmplate != null)
copyMappingInfo(tmplate);

View File

@ -210,14 +210,14 @@ public class MappingRepository extends MetaDataRepository {
/**
* Return the query result mapping for the given name.
*/
public QueryResultMapping getQueryResultMapping(Class<?> cls, String name, boolean mustExist) {
public QueryResultMapping getQueryResultMapping(Class<?> cls, String name, ClassLoader loader, boolean mustExist) {
QueryResultMapping res = null;
if (_locking) {
synchronized (this) {
res = getQueryResultMappingInternal(cls, name);
res = getQueryResultMappingInternal(cls, name, loader);
}
} else {
res = getQueryResultMappingInternal(cls, name);
res = getQueryResultMappingInternal(cls, name, loader);
}
if (res == null && mustExist)
throw new MetaDataException(_loc.get("no-query-res", cls, name));
@ -227,7 +227,7 @@ public class MappingRepository extends MetaDataRepository {
/**
* Returned the query result mapping with the given name.
*/
private QueryResultMapping getQueryResultMappingInternal(Class<?> cls, String name) {
private QueryResultMapping getQueryResultMappingInternal(Class<?> cls, String name, ClassLoader envLoader) {
if (name == null)
return null;
@ -238,7 +238,7 @@ public class MappingRepository extends MetaDataRepository {
return res;
// get metadata for class, which will find results in metadata file
if (cls != null && getMetaData(cls, false) != null) {
if (cls != null && getMetaData(cls, envLoader, false) != null) {
res = (QueryResultMapping) _results.get(key);
if (res != null)
return res;
@ -247,9 +247,10 @@ public class MappingRepository extends MetaDataRepository {
return null;
if (cls == null)
cls = getMetaDataFactory().getResultSetMappingScope(name);
cls = getMetaDataFactory()
.getResultSetMappingScope(name, envLoader);
// not in cache; load
getMetaDataFactory().load(cls, MODE_META | MODE_MAPPING);
getMetaDataFactory().load(cls, MODE_META | MODE_MAPPING, envLoader);
return (QueryResultMapping) _results.get(key);
}
@ -349,20 +350,24 @@ public class MappingRepository extends MetaDataRepository {
return getQueryKey(cls, name);
}
public ClassMapping getMapping(Class<?> cls, boolean mustExist) {
return (ClassMapping) super.getMetaData(cls, mustExist);
public ClassMapping getMapping(Class<?> cls, ClassLoader envLoader,
boolean mustExist) {
return (ClassMapping) super.getMetaData(cls, envLoader, mustExist);
}
public ClassMapping[] getMappings() {
return (ClassMapping[]) super.getMetaDatas();
}
public ClassMapping getMapping(Object oid, boolean mustExist) {
return (ClassMapping) super.getMetaData(oid, mustExist);
public ClassMapping getMapping(Object oid, ClassLoader envLoader,
boolean mustExist) {
return (ClassMapping) super.getMetaData(oid, envLoader, mustExist);
}
public ClassMapping[] getImplementorMappings(Class<?> cls, boolean mustExist) {
return (ClassMapping[]) super.getImplementorMetaDatas(cls, mustExist);
public ClassMapping[] getImplementorMappings(Class<?> cls,
ClassLoader envLoader, boolean mustExist) {
return (ClassMapping[]) super.getImplementorMetaDatas(cls, envLoader,
mustExist);
}
public void clear() {
@ -518,7 +523,8 @@ public class MappingRepository extends MetaDataRepository {
/**
* Return the strategy for the given name.
*/
protected ClassStrategy instantiateClassStrategy(String name, ClassMapping cls) {
protected ClassStrategy instantiateClassStrategy(String name,
ClassMapping cls) {
if (name == null)
return null;
if (NoneClassStrategy.ALIAS.equals(name))
@ -536,17 +542,22 @@ public class MappingRepository extends MetaDataRepository {
else if (VerticalClassStrategy.ALIAS.equals(name))
strat = VerticalClassStrategy.class;
try {
if (strat == null) {
strat = JavaTypes.classForName(name, cls, getConfiguration().getClassLoader());
}
if (strat == null)
strat = JavaTypes.classForName(name, cls,
AccessController.doPrivileged(
J2DoPrivHelper.getClassLoaderAction(
ClassStrategy.class)));
ClassStrategy strategy =
(ClassStrategy) AccessController.doPrivileged(J2DoPrivHelper.newInstanceAction(strat));
Configurations.configureInstance(strategy, getConfiguration(), props);
(ClassStrategy) AccessController.doPrivileged(
J2DoPrivHelper.newInstanceAction(strat));
Configurations.configureInstance(strategy, getConfiguration(),
props);
return strategy;
} catch (Exception e) {
if (e instanceof PrivilegedActionException)
e = ((PrivilegedActionException) e).getException();
throw new MetaDataException(_loc.get("bad-cls-strategy", cls, name), e);
throw new MetaDataException(_loc.get("bad-cls-strategy",
cls, name), e);
}
}
@ -565,13 +576,16 @@ public class MappingRepository extends MetaDataRepository {
String props = Configurations.getProperties(name);
name = Configurations.getClassName(name);
OpenJPAConfiguration conf = getConfiguration();
try {
Class<?> c = JavaTypes.classForName(name, field, conf.getClassLoader());
Class<?> c = JavaTypes.classForName(name, field,
AccessController.doPrivileged(
J2DoPrivHelper.getClassLoaderAction(FieldStrategy.class)));
if (FieldStrategy.class.isAssignableFrom(c)) {
FieldStrategy strat = (FieldStrategy)AccessController.doPrivileged(
FieldStrategy strat = (FieldStrategy)
AccessController.doPrivileged(
J2DoPrivHelper.newInstanceAction(c));
Configurations.configureInstance(strat, conf, props);
Configurations.configureInstance(strat, getConfiguration(),
props);
return strat;
}
@ -579,7 +593,8 @@ public class MappingRepository extends MetaDataRepository {
if (installHandlers) {
ValueHandler vh = (ValueHandler) AccessController.doPrivileged(
J2DoPrivHelper.newInstanceAction(c));
Configurations.configureInstance(vh, conf, props);
Configurations.configureInstance(vh, getConfiguration(),
props);
field.setHandler(vh);
}
return new HandlerFieldStrategy();
@ -631,19 +646,25 @@ public class MappingRepository extends MetaDataRepository {
strat = ValueMapDiscriminatorStrategy.class;
else if (SubclassJoinDiscriminatorStrategy.ALIAS.equals(name))
strat = SubclassJoinDiscriminatorStrategy.class;
OpenJPAConfiguration conf = getConfiguration();
try {
if (strat == null)
strat = JavaTypes.classForName(name, discrim.getClassMapping(), conf.getClassLoader());
strat = JavaTypes.classForName(name,
discrim.getClassMapping(),
AccessController.doPrivileged(
J2DoPrivHelper.getClassLoaderAction(
DiscriminatorStrategy.class)));
DiscriminatorStrategy strategy = (DiscriminatorStrategy)
AccessController.doPrivileged(
J2DoPrivHelper.newInstanceAction(strat));
Configurations.configureInstance(strategy, conf, props);
Configurations.configureInstance(strategy, getConfiguration(),
props);
return strategy;
} catch (Exception e) {
if (e instanceof PrivilegedActionException)
e = ((PrivilegedActionException) e).getException();
throw new MetaDataException(_loc.get("bad-discrim-strategy", discrim.getClassMapping(), name), e);
throw new MetaDataException(_loc.get("bad-discrim-strategy",
discrim.getClassMapping(), name), e);
}
}
@ -694,7 +715,11 @@ public class MappingRepository extends MetaDataRepository {
try {
if (strat == null)
strat = JavaTypes.classForName(name, version.getClassMapping(), getConfiguration().getClassLoader());
strat = JavaTypes.classForName(name,
version.getClassMapping(),
AccessController.doPrivileged(
J2DoPrivHelper.getClassLoaderAction(
VersionStrategy.class)));
} catch (Exception e) {
throw new MetaDataException(_loc.get("bad-version-strategy",
version.getClassMapping(), name), e);
@ -1180,7 +1205,8 @@ public class MappingRepository extends MetaDataRepository {
/**
* Check the given value against mapped strategies.
*/
private Object mappedStrategy(ValueMapping val, Class<?> type, boolean adapting) {
private Object mappedStrategy(ValueMapping val, Class<?> type,
boolean adapting) {
if (type == null || type == Object.class)
return null;
@ -1200,7 +1226,13 @@ public class MappingRepository extends MetaDataRepository {
String props = Configurations.getProperties(name);
name = Configurations.getClassName(name);
try {
return Configurations.newInstance(name, getConfiguration(), props);
Class<?> c = JavaTypes.classForName(name, val,
AccessController.doPrivileged(
J2DoPrivHelper.getClassLoaderAction(FieldStrategy.class)),false);
Object o = AccessController.doPrivileged(
J2DoPrivHelper.newInstanceAction(c));
Configurations.configureInstance(o, getConfiguration(), props);
return o;
} catch (Exception e) {
if (e instanceof PrivilegedActionException)
e = ((PrivilegedActionException) e).getException();
@ -1221,9 +1253,15 @@ public class MappingRepository extends MetaDataRepository {
String props = Configurations.getProperties(name);
name = Configurations.getClassName(name);
try {
Object vh = Configurations.newInstance(name, getConfiguration(), props);
if (vh instanceof ValueHandler) {
return (ValueHandler) vh;
Class<?> c = JavaTypes.classForName(name, val,
AccessController.doPrivileged(
J2DoPrivHelper.getClassLoaderAction(ValueHandler.class)),false);
if (ValueHandler.class.isAssignableFrom(c)) {
ValueHandler vh = (ValueHandler) AccessController.doPrivileged(
J2DoPrivHelper.newInstanceAction(c));
Configurations.configureInstance(vh, getConfiguration(),
props);
return vh;
}
return null; // named field strategy
} catch (Exception e) {
@ -1496,7 +1534,8 @@ public class MappingRepository extends MetaDataRepository {
// persistent subclasses may not have been resolved yet.
// run through the persistent types to see if any of them
// or their superclass is a subclass of this class.
Collection<Class<?>> classes = loadPersistentTypes(false);
Collection<Class<?>> classes = loadPersistentTypes(false,
mapping.getEnvClassLoader());
Class<?> cls;
for (Iterator<Class<?>> itr = classes.iterator(); itr.hasNext();) {
cls = itr.next();

View File

@ -473,7 +473,7 @@ public class MappingTool
if (_dropCls != null && !_dropCls.isEmpty()) {
Class<?>[] cls = (Class[]) _dropCls.toArray
(new Class[_dropCls.size()]);
if (!io.drop(cls, _mode))
if (!io.drop(cls, _mode, null))
_log.warn(_loc.get("bad-drop", _dropCls));
}
@ -608,7 +608,7 @@ public class MappingTool
SequenceMetaData smd = mapping.getIdentitySequenceMetaData();
Seq seq = null;
if (smd != null)
seq = smd.getInstance();
seq = smd.getInstance(null);
else if (mapping.getIdentityStrategy() == ValueStrategies.NATIVE
|| (mapping.getIdentityStrategy() == ValueStrategies.NONE
&& mapping.getIdentityType() == ClassMapping.ID_DATASTORE))
@ -625,7 +625,7 @@ public class MappingTool
for (int i = 0; i < fmds.length; i++) {
smd = fmds[i].getValueSequenceMetaData();
if (smd != null) {
seq = smd.getInstance();
seq = smd.getInstance(null);
if (seq instanceof JDBCSeq)
((JDBCSeq) seq).addSchema(mapping, group);
} else if (fmds[i].getEmbeddedMapping() != null)
@ -679,7 +679,7 @@ public class MappingTool
boolean validate) {
// this will parse all possible metadata rsrcs looking for cls, so
// will detect if p-aware
ClassMapping mapping = repos.getMapping(cls, false);
ClassMapping mapping = repos.getMapping(cls, null, false);
if (mapping != null)
return mapping;
if (!validate || cls.isInterface()
@ -790,7 +790,7 @@ public class MappingTool
repos.setStrategyInstaller(new RuntimeStrategyInstaller(repos));
ClassMapping mapping = null;
try {
mapping = repos.getMapping(cls, false);
mapping = repos.getMapping(cls, null, false);
} catch (Exception e) {
}
@ -985,7 +985,8 @@ public class MappingTool
opts.setProperty("schemas", schemas);
Configurations.populateConfiguration(conf, opts);
ClassLoader loader = conf.getClassLoader();
ClassLoader loader = conf.getClassResolverInstance().
getClassLoader(MappingTool.class, null);
if (flags.meta && ACTION_ADD.equals(flags.action))
flags.metaDataFile = Files.getFile(fileName, loader);
else
@ -1021,12 +1022,13 @@ public class MappingTool
if (ACTION_IMPORT.equals(flags.action))
return false;
log.info(_loc.get("running-all-classes"));
classes = conf.getMappingRepositoryInstance().loadPersistentTypes(true);
classes = conf.getMappingRepositoryInstance().
loadPersistentTypes(true, loader);
} else {
classes = new HashSet<Class<?>>();
ClassArgParser classParser = conf.getMetaDataRepositoryInstance().
getMetaDataFactory().newClassArgParser();
classParser.setClassLoader(conf.getClassLoader());
classParser.setClassLoader(loader);
Class<?>[] parsed;
for (int i = 0; i < args.length; i++) {
parsed = classParser.parseTypes(args[i]);

View File

@ -44,6 +44,14 @@ public class MetaDataPlusMappingFactory
private final MetaDataFactory _map;
/**
* Constructor; supply delegates.
*/
public MetaDataPlusMappingFactory(MetaDataFactory meta, MetaDataFactory map) {
this(meta, map, null);
}
/**
* Constructor, supply delegates and Configuration.
*
@ -51,11 +59,14 @@ public class MetaDataPlusMappingFactory
* @param map MappingFactory delegate, should not be null.
* @param conf Configuration in use. Used to determine whether delegates should use strict mode.
*/
public MetaDataPlusMappingFactory(MetaDataFactory meta, MetaDataFactory map, boolean strict) {
public MetaDataPlusMappingFactory(MetaDataFactory meta, MetaDataFactory map, OpenJPAConfiguration conf) {
super(meta);
_map = map;
meta.setStrict(strict);
map.setStrict(strict);
if(conf.getCompatibilityInstance().getMetaFactoriesAreStrict()) {
meta.setStrict(true);
map.setStrict(true);
}
}
/**
@ -93,37 +104,40 @@ public class MetaDataPlusMappingFactory
// always in strict mode
}
public void load(Class cls, int mode) {
public void load(Class cls, int mode, ClassLoader envLoader) {
if ((mode & ~MODE_MAPPING) != MODE_NONE)
super.load(cls, mode & ~MODE_MAPPING);
super.load(cls, mode & ~MODE_MAPPING, envLoader);
if (cls != null && (mode & MODE_MAPPING) != 0)
_map.load(cls, mode & ~MODE_META);
_map.load(cls, mode & ~MODE_META, envLoader);
}
public boolean store(ClassMetaData[] metas, QueryMetaData[] queries,
SequenceMetaData[] seqs, int mode, Map output) {
boolean store = true;
if ((mode & ~MODE_MAPPING) != MODE_NONE)
store &= super.store(metas, queries, seqs, mode & ~MODE_MAPPING, output);
store &= super.store(metas, queries, seqs, mode & ~MODE_MAPPING,
output);
if ((mode & MODE_MAPPING) != 0)
store &= _map.store(metas, queries, seqs, mode & ~MODE_META, output);
store &= _map.store(metas, queries, seqs, mode & ~MODE_META,
output);
return store;
}
public boolean drop(Class[] cls, int mode) {
public boolean drop(Class[] cls, int mode, ClassLoader envLoader) {
boolean drop = true;
if ((mode & ~MODE_MAPPING) != MODE_NONE)
drop &= super.drop(cls, mode & ~MODE_MAPPING);
drop &= super.drop(cls, mode & ~MODE_MAPPING, envLoader);
if ((mode & MODE_MAPPING) != 0)
drop &= _map.drop(cls, mode & ~MODE_META);
drop &= _map.drop(cls, mode & ~MODE_META, envLoader);
return drop;
}
public Set getPersistentTypeNames(boolean classpath) {
Set names = super.getPersistentTypeNames(classpath);
public Set getPersistentTypeNames(boolean classpath,
ClassLoader envLoader) {
Set names = super.getPersistentTypeNames(classpath, envLoader);
if (names != null && !names.isEmpty())
return names;
return _map.getPersistentTypeNames(classpath);
return _map.getPersistentTypeNames(classpath, envLoader);
}
public void clear() {

View File

@ -282,7 +282,7 @@ public class QueryResultMapping
*/
public ClassMapping getCandidateTypeMapping() {
if (_candidateMap == null)
_candidateMap = _repos.getMapping(_candidate, true);
_candidateMap = _repos.getMapping(_candidate, null, true);
return _candidateMap;
}

View File

@ -1652,7 +1652,9 @@ public class ReverseMappingTool
propNames[propNames.length - 1]));
if (typeSpec != null)
type = Strings.toClass(typeSpec, _conf.getClassLoader());
type = Strings.toClass(typeSpec, _conf.
getClassResolverInstance().getClassLoader
(ReverseMappingTool.class, null));
}
if (type == null)
@ -1941,12 +1943,15 @@ public class ReverseMappingTool
// setup a configuration instance with cmd-line info
Configurations.populateConfiguration(conf, opts);
ClassLoader loader = conf.getClassLoader();
ClassLoader loader = conf.getClassResolverInstance().
getClassLoader(ReverseMappingTool.class, null);
// customizer
flags.customizer = (ReverseCustomizer) Configurations.newInstance(customCls, conf, customOpts);
flags.customizer = (ReverseCustomizer) Configurations.
newInstance(customCls, loader);
if (flags.customizer != null) {
Configurations.configureInstance(flags.customizer, conf, customOpts);
Configurations.configureInstance(flags.customizer, conf,
customOpts);
flags.customizer.setConfiguration(customProps);
}

View File

@ -62,7 +62,7 @@ public class ClassNameDiscriminatorStrategy
protected Class getClass(Object val, JDBCStore store)
throws ClassNotFoundException {
ClassLoader loader = store.getConfiguration().getClassLoader();
ClassLoader loader = getClassLoader(store);
return Class.forName((String) val, true, loader);
}
@ -84,7 +84,7 @@ public class ClassNameDiscriminatorStrategy
if (log.isTraceEnabled())
log.trace(_loc.get("load-subs", col.getTable().getFullName()));
ClassLoader loader = store.getConfiguration().getClassLoader();
ClassLoader loader = getClassLoader(store);
Connection conn = store.getConnection();
PreparedStatement stmnt = null;
ResultSet rs = null;
@ -119,4 +119,12 @@ public class ClassNameDiscriminatorStrategy
}
}
/**
* Return the class loader to use for loading class names.
*/
private ClassLoader getClassLoader(JDBCStore store) {
return store.getConfiguration().getClassResolverInstance().
getClassLoader(disc.getClassMapping().getDescribedType(),
store.getContext().getClassLoader());
}
}

View File

@ -87,7 +87,8 @@ public class RelationStrategies {
} else if (val.getClass() == vm.getType())
rel = vm.getTypeMapping(); // common case
else {
rel = vm.getMappingRepository().getMapping(val.getClass(), true);
rel = vm.getMappingRepository().getMapping(val.getClass(),
store.getContext().getClassLoader(), true);
}
if (!rel.isMapped())
throw new UserException(_loc.get("unmapped-datastore-value",

View File

@ -113,7 +113,9 @@ public class UntypedPCValueHandler
String oidStr = str.substring(idx + 1);
StoreContext ctx = store.getContext();
ClassLoader loader = store.getConfiguration().getClassLoader();
ClassLoader loader = store.getConfiguration().
getClassResolverInstance().getClassLoader(vm.getType(),
ctx.getClassLoader());
Class cls = null;
try {
cls = Class.forName(clsName, true, loader);

View File

@ -99,7 +99,8 @@ extends SimpleDriverDataSource implements Configurable, Closeable {
if (_ds == null) {
try {
Properties dbcpProps = updateDBCPProperties(props);
_ds = (DataSource) Configurations.newInstance(DBCPBASICDATASOURCENAME, conf, dbcpProps);
_ds = (DataSource) Configurations.newInstance(DBCPBASICDATASOURCENAME, conf,
dbcpProps, getClassLoader());
} catch (Exception e) {
_dbcpEx = new RuntimeException(_eloc.get("driver-null", DBCPBASICDATASOURCENAME).getMessage(), e);
}

View File

@ -66,13 +66,18 @@ public class DataSourceFactory {
/**
* Create a datasource using the given configuration.
*/
public static DataSource newDataSource(JDBCConfiguration conf, boolean factory2) {
String driver = (factory2) ? conf.getConnection2DriverName() : conf.getConnectionDriverName();
if (StringUtils.isEmpty(driver)) {
throw new UserException(_loc.get("no-driver", conf)).setFatal(true);
}
ClassLoader loader = conf.getClassLoader();
String props = (factory2) ? conf.getConnection2Properties() : conf.getConnectionProperties();
public static DataSource newDataSource(JDBCConfiguration conf,
boolean factory2) {
String driver = (factory2) ? conf.getConnection2DriverName()
: conf.getConnectionDriverName();
if (StringUtils.isEmpty(driver))
throw new UserException(_loc.get("no-driver", conf)).
setFatal(true);
ClassLoader loader = conf.getClassResolverInstance().
getClassLoader(DataSourceFactory.class, null);
String props = (factory2) ? conf.getConnection2Properties()
: conf.getConnectionProperties();
try {
Class<?> driverClass;
try {
@ -108,7 +113,10 @@ public class DataSourceFactory {
// see if their driver name is actually a data source
if (DataSource.class.isAssignableFrom(driverClass)) {
return (DataSource) Configurations.newInstance(driver, conf, props);
return (DataSource) Configurations.newInstance(driver,
conf, props, AccessController.doPrivileged(
J2DoPrivHelper.getClassLoaderAction(
DataSource.class)));
}
}
catch (OpenJPAException ke) {

View File

@ -21,12 +21,13 @@ package org.apache.openjpa.jdbc.schema;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.security.AccessController;
import org.apache.openjpa.jdbc.conf.JDBCConfiguration;
import org.apache.openjpa.lib.conf.Configurable;
import org.apache.openjpa.lib.conf.Configuration;
import org.apache.openjpa.lib.meta.MetaDataSerializer;
import org.apache.openjpa.lib.util.Files;
import org.apache.openjpa.lib.util.J2DoPrivHelper;
import org.apache.openjpa.util.GeneralException;
/**
@ -39,6 +40,7 @@ public class FileSchemaFactory
private JDBCConfiguration _conf = null;
private String _fileName = "package.schema";
private ClassLoader _loader = null;
/**
* Return the XML resource defining this schema. Defaults to
@ -66,6 +68,8 @@ public class FileSchemaFactory
public void setConfiguration(Configuration conf) {
_conf = (JDBCConfiguration) conf;
_loader = _conf.getClassResolverInstance().
getClassLoader(getClass(), null);
}
public void startConfiguration() {
@ -75,7 +79,8 @@ public class FileSchemaFactory
}
public SchemaGroup readSchema() {
URL url = _conf.getClassLoader().getResource(_fileName);
URL url = AccessController.doPrivileged(
J2DoPrivHelper.getResourceAction(_loader, _fileName));
if (url == null)
return new SchemaGroup();
@ -89,11 +94,11 @@ public class FileSchemaFactory
}
public void storeSchema(SchemaGroup schema) {
File file = Files.getFile(_fileName, _conf.getClassLoader());
File file = Files.getFile(_fileName, _loader);
XMLSchemaSerializer ser = new XMLSchemaSerializer(_conf);
ser.addAll(schema);
try {
ser.serialize(file, MetaDataSerializer.PRETTY);
ser.serialize(file, ser.PRETTY);
} catch (IOException ioe) {
throw new GeneralException(ioe);
}

View File

@ -1423,7 +1423,8 @@ public class SchemaTool {
Configurations.populateConfiguration(conf, opts);
// create script writer
ClassLoader loader = conf.getClassLoader();
ClassLoader loader = conf.getClassResolverInstance().
getClassLoader(SchemaTool.class, null);
flags.writer = Files.getWriter(fileName, loader);
boolean returnValue = true;

View File

@ -124,7 +124,6 @@ public class XMLSchemaParser
* Constructor. Supply configuration.
*/
public XMLSchemaParser(JDBCConfiguration conf) {
super(conf.getClassLoader());
_dict = conf.getDBDictionaryInstance();
setLog(conf.getLog(JDBCConfiguration.LOG_SCHEMA));
setParseText(false);

View File

@ -1223,7 +1223,9 @@ public class OracleDictionary
if (EMPTY_CLOB != null)
return EMPTY_CLOB;
try {
return EMPTY_CLOB = (Clob) Class.forName("oracle.sql.CLOB",true, conf.getClassLoader()).
return EMPTY_CLOB = (Clob) Class.forName("oracle.sql.CLOB",true,
AccessController.doPrivileged(J2DoPrivHelper
.getContextClassLoaderAction())).
getMethod("empty_lob", new Class[0]).
invoke(null, new Object[0]);
} catch (Exception e) {
@ -1236,7 +1238,9 @@ public class OracleDictionary
if (EMPTY_BLOB != null)
return EMPTY_BLOB;
try {
return EMPTY_BLOB = (Blob) Class.forName("oracle.sql.BLOB",true, conf.getClassLoader()).
return EMPTY_BLOB = (Blob) Class.forName("oracle.sql.BLOB",true,
AccessController.doPrivileged(J2DoPrivHelper
.getContextClassLoaderAction())).
getMethod("empty_lob", new Class[0]).
invoke(null, new Object[0]);
} catch (Exception e) {

View File

@ -920,9 +920,12 @@ public class PostgresDictionary
try {
if (dbcpGetDelegate == null) {
Class<?> dbcpConnectionClass =
Class.forName("org.apache.commons.dbcp.DelegatingConnection", true, conf.getClassLoader());
Class.forName("org.apache.commons.dbcp.DelegatingConnection", true, AccessController
.doPrivileged(J2DoPrivHelper.getContextClassLoaderAction()));
Class<?> poolingDataSource = Class.forName(
"org.apache.commons.dbcp.PoolingDataSource", true, conf.getClassLoader());
"org.apache.commons.dbcp.PoolingDataSource", true,
AccessController.doPrivileged(J2DoPrivHelper
.getContextClassLoaderAction()));
Method setAccessToUnderlyingConnectionAllowed = poolingDataSource
.getMethod("setAccessToUnderlyingConnectionAllowed",
boolean.class);

View File

@ -213,7 +213,7 @@ public class JESTContext implements JPAServletContext {
public ClassMetaData resolve(String alias) {
ClassLoader loader = Thread.currentThread().getContextClassLoader();
return _repos.getMetaData(alias, true);
return _repos.getMetaData(alias, loader, true);
}
/**

View File

@ -18,18 +18,19 @@
*/
package org.apache.openjpa.abstractstore;
import java.security.AccessController;
import java.util.Map;
import java.util.Properties;
import org.apache.openjpa.conf.OpenJPAConfiguration;
import org.apache.openjpa.conf.OpenJPAConfigurationImpl;
import org.apache.openjpa.kernel.AbstractBrokerFactory;
import org.apache.openjpa.kernel.Bootstrap;
import org.apache.openjpa.kernel.BrokerFactory;
import org.apache.openjpa.kernel.StoreManager;
import org.apache.openjpa.lib.conf.Configuration;
import org.apache.openjpa.lib.conf.ConfigurationProvider;
import org.apache.openjpa.lib.conf.Configurations;
import org.apache.openjpa.lib.conf.ProductDerivations;
import org.apache.openjpa.lib.util.J2DoPrivHelper;
import org.apache.openjpa.lib.util.Localizer;
import org.apache.openjpa.util.UserException;
@ -49,7 +50,6 @@ import org.apache.openjpa.util.UserException;
* and bootstrapping from a {@link Map} object (the strategy used by
* {@link Bootstrap} to create a factory in a vendor-neutral manner).
*/
@SuppressWarnings("serial")
public class AbstractStoreBrokerFactory
extends AbstractBrokerFactory {
@ -57,9 +57,11 @@ public class AbstractStoreBrokerFactory
* The property name under which to name the concrete store manager
* class for this runtime.
*/
private static final String PROP_ABSTRACT_STORE = "abstractstore.AbstractStoreManager";
private static final String PROP_ABSTRACT_STORE =
"abstractstore.AbstractStoreManager";
private static final Localizer s_loc = Localizer.forPackage(AbstractStoreBrokerFactory.class);
private static final Localizer s_loc = Localizer.forPackage
(AbstractStoreBrokerFactory.class);
private String _storeCls = null;
private String _storeProps = null;
@ -69,9 +71,11 @@ public class AbstractStoreBrokerFactory
* Factory method for obtaining a possibly-pooled {@link BrokerFactory}
* from properties. Invoked from {@link Bootstrap#getBrokerFactory()}.
*/
public static AbstractStoreBrokerFactory getInstance(ConfigurationProvider cp) {
public static AbstractStoreBrokerFactory getInstance(
ConfigurationProvider cp) {
Object key = toPoolKey(cp.getProperties());
AbstractStoreBrokerFactory factory = (AbstractStoreBrokerFactory)getPooledFactoryForKey(key);
AbstractStoreBrokerFactory factory = (AbstractStoreBrokerFactory)
getPooledFactoryForKey(key);
if (factory != null)
return factory;
@ -84,16 +88,17 @@ public class AbstractStoreBrokerFactory
* Factory method for constructing a {@link BrokerFactory}
* from properties. Invoked from {@link Bootstrap#newBrokerFactory()}.
*/
public static AbstractStoreBrokerFactory newInstance(ConfigurationProvider cp) {
public static AbstractStoreBrokerFactory newInstance
(ConfigurationProvider cp) {
// use a tmp store manager to get metadata about the capabilities of
// this runtime
Map map = cp.getProperties();
OpenJPAConfiguration tmp = new OpenJPAConfigurationImpl();
cp.setInto(tmp);
String storePlugin = (String) map.get(ProductDerivations.getConfigurationKey(PROP_ABSTRACT_STORE, map));
String storePlugin = (String) map.get(ProductDerivations
.getConfigurationKey(PROP_ABSTRACT_STORE, map));
String storeCls = Configurations.getClassName(storePlugin);
String storeProps = Configurations.getProperties(storePlugin);
AbstractStoreManager store = createStoreManager(storeCls, tmp, storeProps);
AbstractStoreManager store = createStoreManager(storeCls,
storeProps);
// populate configuration
OpenJPAConfiguration conf = store.newConfiguration();
@ -101,7 +106,8 @@ public class AbstractStoreBrokerFactory
conf.supportedOptions().removeAll(store.getUnsupportedOptions());
// create and pool a new factory
return new AbstractStoreBrokerFactory(conf, storeCls, storeProps, store.getPlatform());
return new AbstractStoreBrokerFactory(conf, storeCls, storeProps,
store.getPlatform());
}
/**
@ -122,13 +128,17 @@ public class AbstractStoreBrokerFactory
}
protected StoreManager newStoreManager() {
return createStoreManager(_storeCls, new OpenJPAConfigurationImpl(), _storeProps);
return createStoreManager(_storeCls, _storeProps);
}
private static AbstractStoreManager createStoreManager(String cls, OpenJPAConfiguration conf, String props) {
private static AbstractStoreManager createStoreManager(String cls,
String props) {
AbstractStoreManager store =
(AbstractStoreManager) Configurations.newInstance(cls, conf, props);
Configurations.configureInstance(store, null, props, PROP_ABSTRACT_STORE);
(AbstractStoreManager) Configurations.newInstance(cls,
AccessController.doPrivileged(J2DoPrivHelper
.getClassLoaderAction(AbstractStoreManager.class)));
Configurations.configureInstance(store, null, props,
PROP_ABSTRACT_STORE);
if (store == null)
throw new UserException(s_loc.get("no-store-manager",
PROP_ABSTRACT_STORE)).setFatal(true);

View File

@ -244,7 +244,7 @@ public abstract class AbstractStoreManager
* states, and delegates to
* {@link #flush(Collection,Collection,Collection,Collection,Collection)}.
*/
public Collection<Exception> flush(Collection<? extends OpenJPAStateManager> sms) {
public Collection<Exception> flush(Collection<OpenJPAStateManager> sms) {
// break down state managers by state; initialize as empty lists;
// use constants for efficiency
Collection<OpenJPAStateManager> pNew = new LinkedList<OpenJPAStateManager>();

View File

@ -104,7 +104,9 @@ public class ApplicationIdToolTask
protected void executeOn(String[] files)
throws IOException, ClassNotFoundException {
flags.directory = (dirName == null) ? null : Files.getFile(dirName, getClassLoader());
ApplicationIdTool.run((OpenJPAConfiguration) getConfiguration(), files, flags);
flags.directory = (dirName == null) ? null
: Files.getFile(dirName, getClassLoader());
ApplicationIdTool.run((OpenJPAConfiguration) getConfiguration(), files,
flags, getClassLoader ());
}
}

View File

@ -86,6 +86,6 @@ public class PCEnhancerTask
: Files.getFile(dirName, getClassLoader());
OpenJPAConfiguration conf = (OpenJPAConfiguration) getConfiguration();
MetaDataRepository repos = conf.newMetaDataRepositoryInstance();
PCEnhancer.run(conf, files, flags, repos, null);
PCEnhancer.run(conf, files, flags, repos, null, getClassLoader ());
}
}

View File

@ -58,6 +58,10 @@ class AutoDetachValue
setAliasListComprehensive(true);
}
public Class getValueType() {
return String[].class;
}
public void setConstant(int flags) {
_flags = flags;
}

View File

@ -23,7 +23,6 @@ import java.util.Map;
import java.util.Iterator;
import org.apache.openjpa.abstractstore.AbstractStoreBrokerFactory;
import org.apache.openjpa.kernel.Broker;
import org.apache.openjpa.kernel.BrokerFactory;
import org.apache.openjpa.lib.conf.ConfigurationProvider;
import org.apache.openjpa.lib.conf.PluginValue;
@ -39,7 +38,7 @@ import org.apache.openjpa.lib.conf.ProductDerivation;
* @nojavadoc
*/
public class BrokerFactoryValue
extends PluginValue<BrokerFactory> {
extends PluginValue {
public static final String KEY = "BrokerFactory";
@ -79,7 +78,7 @@ public class BrokerFactoryValue
}
public BrokerFactoryValue() {
super(BrokerFactory.class, KEY, false);
super(KEY, false);
setAliases(_aliases);
}
}

View File

@ -18,10 +18,10 @@
*/
package org.apache.openjpa.conf;
import org.apache.openjpa.lib.conf.PluginValue;
import org.apache.openjpa.lib.conf.Configuration;
import org.apache.openjpa.kernel.BrokerImpl;
import org.apache.openjpa.kernel.FinalizingBrokerImpl;
import org.apache.openjpa.lib.conf.Configuration;
import org.apache.openjpa.lib.conf.PluginValue;
import org.apache.openjpa.util.InternalException;
/**
@ -31,7 +31,7 @@ import org.apache.openjpa.util.InternalException;
* @since 0.9.7
*/
public class BrokerValue
extends PluginValue<BrokerImpl> {
extends PluginValue {
public static final String KEY = "BrokerImpl";
public static final String NON_FINALIZING_ALIAS = "non-finalizing";
@ -40,7 +40,7 @@ public class BrokerValue
private BrokerImpl _templateBroker;
public BrokerValue() {
super(BrokerImpl.class, KEY, false);
super(KEY, false);
String[] aliases = new String[] {
DEFAULT_ALIAS, FinalizingBrokerImpl.class.getName(),
NON_FINALIZING_ALIAS, BrokerImpl.class.getName(),
@ -50,29 +50,34 @@ public class BrokerValue
setString(aliases[0]);
}
public BrokerImpl newInstance(String clsName, Configuration conf, boolean fatal) {
getTemplateBroker(clsName, conf, fatal);
public Object newInstance(String clsName, Class type, Configuration conf,
boolean fatal) {
getTemplateBroker(clsName, type, conf, fatal);
try {
return (BrokerImpl)_templateBroker.clone();
return _templateBroker.clone();
} catch (CloneNotSupportedException e) {
throw new InternalException(e);
}
}
public Class<? extends BrokerImpl> getTemplateBrokerType(Configuration c) {
return getTemplateBroker(getClassName(), c, true).getClass();
return getTemplateBroker(getClassName(), BrokerImpl.class, c, true)
.getClass();
}
private BrokerImpl getTemplateBroker(String clsName, Configuration conf, boolean fatal) {
private BrokerImpl getTemplateBroker(String clsName, Class type,
Configuration conf, boolean fatal) {
if (clsName == null || !clsName.equals(getClassName()))
throw new IllegalArgumentException("clsName != configured value '" + getClassName() + "'");
throw new IllegalArgumentException("clsName != configured value '"
+ getClassName() + "'");
// This is not synchronized. If there are concurrent invocations
// while _templateBroker is null, we'll just end up with extra
// template brokers, which will get safely garbage collected.
if (_templateBroker == null)
_templateBroker = super.newInstance(clsName, conf, fatal);
_templateBroker = (BrokerImpl) super.newInstance(clsName, type,
conf, fatal);
return _templateBroker;
}
}

View File

@ -182,7 +182,8 @@ public class CacheMarshallerImpl
throws InstantiationException, IllegalAccessException {
String name = Configurations.getClassName(policy);
String props = Configurations.getProperties(policy);
_validationPolicy = (ValidationPolicy) Configurations.newInstance(name, _conf, props);
_validationPolicy = (ValidationPolicy)
Configurations.newInstance(name, _conf, props, null);
}
public ValidationPolicy getValidationPolicy() {
@ -217,7 +218,8 @@ public class CacheMarshallerImpl
private void setInputUrlFromResourceLocation() {
try {
ClassLoader cl = _conf.getClassLoader();
ClassLoader cl = _conf.getClassResolverInstance()
.getClassLoader(getClass(), null);
List list = new ArrayList();
for (Enumeration e = cl.getResources(_inputResourceLocation);
e.hasMoreElements(); )

View File

@ -32,28 +32,33 @@ import org.apache.openjpa.lib.conf.Configuration;
*
* @since 1.1.0
*/
public class CacheMarshallersValue extends PluginListValue<CacheMarshaller> {
public class CacheMarshallersValue
extends PluginListValue {
private static final String KEY = "CacheMarshallers";
private static final CacheMarshaller NO_OP_CACHE_MARSHALLER = new NoOpCacheMarshaller();
private static final Localizer _loc = Localizer.forPackage(CacheMarshallersValue.class);
private static final CacheMarshaller NO_OP_CACHE_MARSHALLER
= new NoOpCacheMarshaller();
private static final Localizer _loc =
Localizer.forPackage(CacheMarshallersValue.class);
private Configuration _conf;
private Map<String,CacheMarshaller> _marshallers;
private boolean _initialized;
public CacheMarshallersValue(Configuration conf) {
super(CacheMarshaller[].class, KEY);
super(KEY);
_conf = conf;
setAlias("default", CacheMarshallerImpl.class.getName());
setAlias("none", (String)null);
setAlias("none", null);
setDefault("none");
setString("none");
setScope(getClass());
}
public CacheMarshaller[] instantiate(Configuration conf, boolean fatal) {
CacheMarshaller[] ms = super.instantiate(conf, fatal);
public Object instantiate(Class<?> elemType, Configuration conf,
boolean fatal) {
CacheMarshaller[] ms = (CacheMarshaller[])
super.instantiate(elemType, conf, fatal);
if (ms != null) {
_marshallers = new HashMap<String,CacheMarshaller>();
for (int i = 0; i < ms.length; i++) {
@ -109,7 +114,7 @@ public class CacheMarshallersValue extends PluginListValue<CacheMarshaller> {
protected synchronized void initialize() {
if (!_initialized) {
instantiate(_conf);
instantiate(CacheMarshaller.class, _conf);
_initialized = true;
}
}

View File

@ -18,7 +18,6 @@
*/
package org.apache.openjpa.conf;
import java.security.AccessController;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
@ -27,7 +26,6 @@ import org.apache.openjpa.kernel.Bootstrap;
import org.apache.openjpa.kernel.Broker;
import org.apache.openjpa.kernel.BrokerFactory;
import org.apache.openjpa.kernel.Query;
import org.apache.openjpa.lib.util.J2DoPrivHelper;
import org.apache.openjpa.lib.util.Options;
import org.apache.openjpa.lib.log.Log;
import org.apache.openjpa.lib.conf.MapConfigurationProvider;
@ -53,11 +51,14 @@ public class MetaDataCacheMaintenance {
public static void main(String[] args) {
Options opts = new Options();
args = opts.setFromCmdLine(args);
boolean devpath = opts.getBooleanProperty("scanDevPath", "ScanDevPath", true);
boolean devpath = opts.getBooleanProperty("scanDevPath", "ScanDevPath",
true);
ConfigurationProvider cp = new MapConfigurationProvider(opts);
BrokerFactory factory = Bootstrap.newBrokerFactory(cp);
BrokerFactory factory = Bootstrap.newBrokerFactory(cp, null);
try {
MetaDataCacheMaintenance maint = new MetaDataCacheMaintenance(factory, devpath);
MetaDataCacheMaintenance maint = new MetaDataCacheMaintenance(
factory, devpath);
if (args.length != 1) {
usage();
@ -114,9 +115,9 @@ public class MetaDataCacheMaintenance {
public void store() {
MetaDataRepository repos = conf.getMetaDataRepositoryInstance();
repos.setSourceMode(MetaDataRepository.MODE_ALL);
Collection types = repos.loadPersistentTypes(devpath);
Collection types = repos.loadPersistentTypes(devpath, null);
for (Iterator iter = types.iterator(); iter.hasNext(); )
repos.getMetaData((Class) iter.next(), true);
repos.getMetaData((Class) iter.next(), null, true);
loadQueries();

View File

@ -32,12 +32,12 @@ import org.apache.openjpa.meta.MetaDataRepository;
* @since 1.1.0
*/
public class MetaDataRepositoryValue
extends PluginValue<MetaDataRepository> {
extends PluginValue {
private static final String KEY = "MetaDataRepository";
public MetaDataRepositoryValue() {
super(MetaDataRepository.class, KEY, false);
super(KEY, false);
String[] aliases = new String[] {
"default",
MetaDataRepository.class.getName()
@ -47,7 +47,7 @@ public class MetaDataRepositoryValue
setString(aliases[0]);
}
public MetaDataRepository instantiate(Configuration c, boolean fatal) {
public Object instantiate(Class type, Configuration c, boolean fatal) {
MetaDataRepository repos = null;
OpenJPAConfiguration conf = (OpenJPAConfiguration) c;
@ -64,7 +64,10 @@ public class MetaDataRepositoryValue
conf.getQueryCompilationCacheInstance().putAll((Map) os[1]);
}
return (repos == null) ? super.instantiate(c, fatal) : repos;
if (repos == null)
return super.instantiate(type, c, fatal);
else
return repos;
}

View File

@ -21,6 +21,7 @@ package org.apache.openjpa.conf;
import java.util.Collection;
import java.util.Map;
import org.apache.openjpa.kernel.AuditManager;
import org.apache.openjpa.audit.Auditor;
import org.apache.openjpa.datacache.CacheDistributionPolicy;
import org.apache.openjpa.datacache.DataCache;
@ -57,7 +58,6 @@ import org.apache.openjpa.meta.MetaDataRepository;
import org.apache.openjpa.util.ClassResolver;
import org.apache.openjpa.util.ProxyManager;
import org.apache.openjpa.util.StoreFacadeTypeRegistry;
import org.apache.openjpa.validation.Validator;
/**
* Defines the properties necessary to configure runtime properties and
@ -270,23 +270,23 @@ public interface OpenJPAConfiguration
* The plugin string for the {@link ClassResolver} to use for custom
* class loading.
*/
// public String getClassResolver();
public String getClassResolver();
/**
* The plugin string for the {@link ClassResolver} to use for custom
* class loading.
*/
// public void setClassResolver(String classResolver);
public void setClassResolver(String classResolver);
/**
* The {@link ClassResolver} to use.
*/
// public ClassResolver getClassResolverInstance();
public ClassResolver getClassResolverInstance();
/**
* The {@link ClassResolver} to use.
*/
// public void setClassResolver(ClassResolver classResolver);
public void setClassResolver(ClassResolver classResolver);
/**
* The {@link BrokerFactory} class to use.
@ -1701,7 +1701,7 @@ public interface OpenJPAConfiguration
*
* @since 2.0.0
*/
public Validator getValidatorInstance();
public Object getValidatorInstance();
/**
* Set the container or application provided Validator instance.
@ -1709,7 +1709,7 @@ public interface OpenJPAConfiguration
*
* @since 2.0.0
*/
public void setValidatorInstance(Validator val);
public void setValidatorInstance(Object val);
/**
* Gets the lifecycle event manager instance classname.
@ -1786,7 +1786,7 @@ public interface OpenJPAConfiguration
*
* @return EncryptionProvider
*/
public EncryptionProvider getEncryptionProviderInstance();
public EncryptionProvider getEncryptionProvider();
/**

View File

@ -28,23 +28,13 @@ import org.apache.openjpa.audit.Auditor;
import org.apache.openjpa.datacache.CacheDistributionPolicy;
import org.apache.openjpa.datacache.ConcurrentDataCache;
import org.apache.openjpa.datacache.ConcurrentQueryCache;
import org.apache.openjpa.datacache.DataCache;
import org.apache.openjpa.datacache.DataCacheManager;
import org.apache.openjpa.datacache.DataCacheManagerImpl;
import org.apache.openjpa.datacache.DefaultCacheDistributionPolicy;
import org.apache.openjpa.datacache.PartitionedDataCache;
import org.apache.openjpa.datacache.QueryCache;
import org.apache.openjpa.datacache.TypeBasedCacheDistributionPolicy;
import org.apache.openjpa.ee.AutomaticManagedRuntime;
import org.apache.openjpa.ee.InvocationManagedRuntime;
import org.apache.openjpa.ee.JNDIManagedRuntime;
import org.apache.openjpa.ee.ManagedRuntime;
import org.apache.openjpa.enhance.RuntimeUnenhancedClassesModes;
import org.apache.openjpa.event.BrokerFactoryEventManager;
import org.apache.openjpa.event.ExceptionOrphanedKeyAction;
import org.apache.openjpa.event.LifecycleEventManager;
import org.apache.openjpa.event.LogOrphanedKeyAction;
import org.apache.openjpa.event.NoneOrphanedKeyAction;
import org.apache.openjpa.event.OrphanedKeyAction;
import org.apache.openjpa.event.RemoteCommitEventManager;
import org.apache.openjpa.event.RemoteCommitProvider;
@ -53,25 +43,20 @@ import org.apache.openjpa.instrumentation.InstrumentationManagerImpl;
import org.apache.openjpa.kernel.AutoClear;
import org.apache.openjpa.kernel.BrokerImpl;
import org.apache.openjpa.kernel.ConnectionRetainModes;
import org.apache.openjpa.kernel.DetachState;
import org.apache.openjpa.kernel.FinderCache;
import org.apache.openjpa.kernel.InMemorySavepointManager;
import org.apache.openjpa.kernel.InverseManager;
import org.apache.openjpa.kernel.LockLevels;
import org.apache.openjpa.kernel.LockManager;
import org.apache.openjpa.kernel.NoneLockManager;
import org.apache.openjpa.kernel.PreparedQueryCache;
import org.apache.openjpa.kernel.QueryFlushModes;
import org.apache.openjpa.kernel.RestoreState;
import org.apache.openjpa.kernel.SavepointManager;
import org.apache.openjpa.kernel.Seq;
import org.apache.openjpa.kernel.VersionLockManager;
import org.apache.openjpa.kernel.exps.AggregateListener;
import org.apache.openjpa.kernel.exps.FilterListener;
import org.apache.openjpa.lib.conf.BooleanValue;
import org.apache.openjpa.lib.conf.ConfigurationImpl;
import org.apache.openjpa.lib.conf.Configurations;
import org.apache.openjpa.lib.conf.EnumValue;
import org.apache.openjpa.lib.conf.IntValue;
import org.apache.openjpa.lib.conf.ObjectValue;
import org.apache.openjpa.lib.conf.PluginListValue;
@ -87,13 +72,10 @@ import org.apache.openjpa.lib.util.Localizer;
import org.apache.openjpa.meta.MetaDataFactory;
import org.apache.openjpa.meta.MetaDataRepository;
import org.apache.openjpa.util.ClassResolver;
import org.apache.openjpa.util.ClassResolverImpl;
import org.apache.openjpa.util.ImplHelper;
import org.apache.openjpa.util.ProxyManager;
import org.apache.openjpa.util.ProxyManagerImpl;
import org.apache.openjpa.util.StoreFacadeTypeRegistry;
import org.apache.openjpa.validation.ValidatingLifecycleEventManager;
import org.apache.openjpa.validation.Validator;
/**
* Implementation of the {@link OpenJPAConfiguration} interface.
@ -114,16 +96,16 @@ public class OpenJPAConfigurationImpl
protected RemoteCommitEventManager remoteEventManager = null;
// openjpa properties
public ObjectValue<ClassResolver> classResolverPlugin;
public ObjectValue classResolverPlugin;
public BrokerValue brokerPlugin;
public ObjectValue<DataCache> dataCachePlugin;
public ObjectValue<DataCacheManager> dataCacheManagerPlugin;
public ObjectValue<Auditor> auditorPlugin;
public ObjectValue<CacheDistributionPolicy> cacheDistributionPolicyPlugin;
public ObjectValue dataCachePlugin;
public ObjectValue dataCacheManagerPlugin;
public ObjectValue auditorPlugin;
public ObjectValue cacheDistributionPolicyPlugin;
public IntValue dataCacheTimeout;
public ObjectValue<QueryCache> queryCachePlugin;
public ObjectValue queryCachePlugin;
public BooleanValue dynamicDataStructs;
public ObjectValue<ManagedRuntime> managedRuntimePlugin;
public ObjectValue managedRuntimePlugin;
public BooleanValue transactionMode;
public IntValue connectionRetainMode;
public IntValue fetchBatchSize;
@ -134,17 +116,17 @@ public class OpenJPAConfigurationImpl
public IntValue queryTimeout;
public IntValue readLockLevel;
public IntValue writeLockLevel;
public ObjectValue<Seq> seqPlugin;
public PluginListValue<FilterListener> filterListenerPlugins;
public PluginListValue<AggregateListener> aggregateListenerPlugins;
public ObjectValue seqPlugin;
public PluginListValue filterListenerPlugins;
public PluginListValue aggregateListenerPlugins;
public BooleanValue retryClassRegistration;
public ObjectValue<ProxyManager> proxyManagerPlugin;
public ObjectValue proxyManagerPlugin;
public StringValue connectionUserName;
public StringValue connectionPassword;
public PluginValue<EncryptionProvider> encryptionProvider;
public PluginValue encryptionProvider;
public StringValue connectionURL;
public StringValue connectionDriverName;
public ObjectValue<Object> connectionFactory;
public ObjectValue connectionFactory;
public StringValue connectionFactoryName;
public StringValue connectionProperties;
public StringValue connectionFactoryProperties;
@ -154,46 +136,46 @@ public class OpenJPAConfigurationImpl
public StringValue connection2URL;
public StringValue connection2DriverName;
public StringValue connection2Properties;
public ObjectValue<Object> connectionFactory2;
public ObjectValue connectionFactory2;
public StringValue connectionFactory2Name;
public StringValue connectionFactory2Properties;
public BooleanValue optimistic;
public IntValue autoClear;
public BooleanValue retainState;
public IntValue restoreState;
public ObjectValue<DetachOptions> detachStatePlugin;
public ObjectValue detachStatePlugin;
public BooleanValue ignoreChanges;
public BooleanValue nontransactionalRead;
public BooleanValue nontransactionalWrite;
public BooleanValue refreshFromDataCache;
public BooleanValue multithreaded;
public StringValue mapping;
public PluginValue<MetaDataFactory> metaFactoryPlugin;
public PluginValue metaFactoryPlugin;
public MetaDataRepositoryValue metaRepositoryPlugin;
public ObjectValue<LockManager> lockManagerPlugin;
public ObjectValue<InverseManager> inverseManagerPlugin;
public ObjectValue<SavepointManager> savepointManagerPlugin;
public ObjectValue<OrphanedKeyAction> orphanedKeyPlugin;
public ObjectValue<Compatibility> compatibilityPlugin;
public ObjectValue<CallbackOptions> callbackPlugin;
public ObjectValue lockManagerPlugin;
public ObjectValue inverseManagerPlugin;
public ObjectValue savepointManagerPlugin;
public ObjectValue orphanedKeyPlugin;
public ObjectValue compatibilityPlugin;
public ObjectValue callbackPlugin;
public QueryCompilationCacheValue queryCompilationCachePlugin;
public IntValue runtimeUnenhancedClasses;
public CacheMarshallersValue cacheMarshallerPlugins;
public BooleanValue eagerInitialization;
public PluginValue<PreparedQueryCache> preparedQueryCachePlugin;
public PluginValue<FinderCache> finderCachePlugin;
public ObjectValue<Specification> specification;
public PluginValue preparedQueryCachePlugin;
public PluginValue finderCachePlugin;
public ObjectValue specification;
public StringValue validationMode;
public ObjectValue<Object> validationFactory;
public ObjectValue<Validator> validator;
public ObjectValue<LifecycleEventManager> lifecycleEventManager;
public ObjectValue validationFactory;
public ObjectValue validator;
public ObjectValue lifecycleEventManager;
public StringValue validationGroupPrePersist;
public StringValue validationGroupPreUpdate;
public StringValue validationGroupPreRemove;
public StringValue dataCacheMode;
public BooleanValue dynamicEnhancementAgent;
public ObjectValue<InstrumentationManager> instrumentationManager;
public PluginListValue<InstrumentationProvider> instrumentationProviders;
public ObjectValue instrumentationManager;
public PluginListValue instrumentationProviders;
// custom values
public BrokerFactoryValue brokerFactoryPlugin;
@ -231,87 +213,145 @@ public class OpenJPAConfigurationImpl
super(false);
String[] aliases;
classResolverPlugin = addPlugin(ClassResolver.class, true);
classResolverPlugin.setDefaultAlias(ClassResolverImpl.class);
// deprecated alias
classResolverPlugin.setAlias("spec", ClassResolverImpl.class);
classResolverPlugin = addPlugin("ClassResolver", true);
aliases = new String[] {
"default", "org.apache.openjpa.util.ClassResolverImpl",
// deprecated alias
"spec", "org.apache.openjpa.util.ClassResolverImpl", };
classResolverPlugin.setAliases(aliases);
classResolverPlugin.setDefault(aliases[0]);
classResolverPlugin.setString(aliases[0]);
classResolverPlugin.setInstantiatingGetter("getClassResolverInstance");
addValue(brokerFactoryPlugin = new BrokerFactoryValue());
brokerFactoryPlugin = new BrokerFactoryValue();
addValue(brokerFactoryPlugin);
addValue(brokerPlugin = new BrokerValue());
brokerPlugin = new BrokerValue();
addValue(brokerPlugin);
dataCacheManagerPlugin = addPlugin(DataCacheManager.class, true);
dataCacheManagerPlugin.setDefaultAlias(DataCacheManagerImpl.class);
dataCacheManagerPlugin = addPlugin("DataCacheManager", true);
aliases =
new String[] { "default", DataCacheManagerImpl.class.getName(), };
dataCacheManagerPlugin.setAliases(aliases);
dataCacheManagerPlugin.setDefault(aliases[0]);
dataCacheManagerPlugin.setString(aliases[0]);
dataCacheManagerPlugin.setInstantiatingGetter("getDataCacheManager");
cacheDistributionPolicyPlugin = addPlugin(CacheDistributionPolicy.class, true);
cacheDistributionPolicyPlugin.setDefaultAlias(DefaultCacheDistributionPolicy.class);
cacheDistributionPolicyPlugin.setAlias("type-based", TypeBasedCacheDistributionPolicy.class);
cacheDistributionPolicyPlugin = addPlugin("CacheDistributionPolicy", true);
aliases = new String[] {
"default", "org.apache.openjpa.datacache.DefaultCacheDistributionPolicy",
"type-based", "org.apache.openjpa.datacache.TypeBasedCacheDistributionPolicy"};
cacheDistributionPolicyPlugin.setAliases(aliases);
cacheDistributionPolicyPlugin.setDefault(aliases[0]);
cacheDistributionPolicyPlugin.setString(aliases[0]);
cacheDistributionPolicyPlugin.setInstantiatingGetter("getCacheDistributionPolicy");
dataCachePlugin = addPlugin(DataCache.class);
dataCachePlugin.setDefaultAlias("false", null);
dataCachePlugin.setAlias("true", ConcurrentDataCache.class);
dataCachePlugin.setAlias("concurrent", ConcurrentDataCache.class);
dataCachePlugin.setAlias("partitioned", PartitionedDataCache.class);
dataCachePlugin = addPlugin("DataCache", false);
aliases = new String[] {
"false", null,
"true", ConcurrentDataCache.class.getName(),
"concurrent", ConcurrentDataCache.class.getName(),
"partitioned", PartitionedDataCache.class.getName(),
};
dataCachePlugin.setAliases(aliases);
dataCachePlugin.setDefault(aliases[0]);
dataCachePlugin.setString(aliases[0]);
dataCacheTimeout = addInt("DataCacheTimeout");
dataCacheTimeout.setDefault("-1");
dataCacheTimeout.set(-1);
dataCacheTimeout.setDynamic(true);
queryCachePlugin = addPlugin(QueryCache.class);
queryCachePlugin.setDefaultAlias("false", null);
queryCachePlugin.setAlias("true", ConcurrentQueryCache.class);
queryCachePlugin.setAlias("concurrent", ConcurrentQueryCache.class);
queryCachePlugin = addPlugin("QueryCache", false);
aliases = new String[] {
"false", null,
"true", ConcurrentQueryCache.class.getName(),
"concurrent", ConcurrentQueryCache.class.getName(),
};
queryCachePlugin.setAliases(aliases);
queryCachePlugin.setDefault(aliases[0]);
queryCachePlugin.setString(aliases[0]);
refreshFromDataCache = addBoolean("RefreshFromDataCache");
refreshFromDataCache.setDefault("false");
refreshFromDataCache.set(false);
refreshFromDataCache.setDynamic(true);
dynamicDataStructs = addBoolean("DynamicDataStructs");
dynamicDataStructs.setDefault("false");
dynamicDataStructs.set(false);
lockManagerPlugin = addPlugin(LockManager.class);
lockManagerPlugin.setDefaultAlias("none", NoneLockManager.class);
lockManagerPlugin.setAlias("version", VersionLockManager.class);
lockManagerPlugin = addPlugin("LockManager", false);
aliases =
new String[] {
"none", "org.apache.openjpa.kernel.NoneLockManager",
"version", "org.apache.openjpa.kernel.VersionLockManager", };
lockManagerPlugin.setAliases(aliases);
lockManagerPlugin.setDefault(aliases[0]);
lockManagerPlugin.setString(aliases[0]);
inverseManagerPlugin = addPlugin(InverseManager.class);
inverseManagerPlugin.setDefaultAlias("false", null);
inverseManagerPlugin.setAlias("true", InverseManager.class);
inverseManagerPlugin = addPlugin("InverseManager", false);
aliases = new String[] {
"false", null,
"true", "org.apache.openjpa.kernel.InverseManager", };
inverseManagerPlugin.setAliases(aliases);
inverseManagerPlugin.setDefault(aliases[0]);
inverseManagerPlugin.setString(aliases[0]);
savepointManagerPlugin = addPlugin(SavepointManager.class, true);
savepointManagerPlugin.setDefaultAlias("in-mem", InMemorySavepointManager.class);
savepointManagerPlugin = addPlugin("SavepointManager", true);
aliases = new String[] {
"in-mem", "org.apache.openjpa.kernel.InMemorySavepointManager", };
savepointManagerPlugin.setAliases(aliases);
savepointManagerPlugin.setDefault(aliases[0]);
savepointManagerPlugin.setString(aliases[0]);
savepointManagerPlugin.setInstantiatingGetter("getSavepointManagerInstance");
orphanedKeyPlugin = addPlugin(OrphanedKeyAction.class, true);
orphanedKeyPlugin.setDefaultAlias("log", LogOrphanedKeyAction.class);
orphanedKeyPlugin.setAlias("exception", ExceptionOrphanedKeyAction.class);
orphanedKeyPlugin.setAlias("none", NoneOrphanedKeyAction.class);
orphanedKeyPlugin = addPlugin("OrphanedKeyAction", true);
aliases = new String[] {
"log", "org.apache.openjpa.event.LogOrphanedKeyAction",
"exception", "org.apache.openjpa.event.ExceptionOrphanedKeyAction",
"none", "org.apache.openjpa.event.NoneOrphanedKeyAction", };
orphanedKeyPlugin.setAliases(aliases);
orphanedKeyPlugin.setDefault(aliases[0]);
orphanedKeyPlugin.setString(aliases[0]);
orphanedKeyPlugin.setInstantiatingGetter("getOrphanedKeyActionInstance");
addValue(remoteProviderPlugin = new RemoteCommitProviderValue());
remoteProviderPlugin = new RemoteCommitProviderValue();
addValue(remoteProviderPlugin);
transactionMode = addBoolean("TransactionMode");
aliases = new String[] { "local", "false", "managed", "true", };
transactionMode.setAliases(aliases);
transactionMode.setDefault(aliases[0]);
managedRuntimePlugin = addPlugin(ManagedRuntime.class, true);
managedRuntimePlugin.setDefaultAlias("auto", AutomaticManagedRuntime.class);
managedRuntimePlugin.setAlias("jndi", JNDIManagedRuntime.class);
managedRuntimePlugin.setAlias("invocation", InvocationManagedRuntime.class);
managedRuntimePlugin = addPlugin("ManagedRuntime", true);
aliases = new String[] {
"auto", "org.apache.openjpa.ee.AutomaticManagedRuntime",
"jndi", "org.apache.openjpa.ee.JNDIManagedRuntime",
"invocation", "org.apache.openjpa.ee.InvocationManagedRuntime", };
managedRuntimePlugin.setAliases(aliases);
managedRuntimePlugin.setDefault(aliases[0]);
managedRuntimePlugin.setString(aliases[0]);
managedRuntimePlugin
.setInstantiatingGetter("getManagedRuntimeInstance");
proxyManagerPlugin = addPlugin(ProxyManager.class, true);
proxyManagerPlugin.setDefaultAlias(ProxyManagerImpl.class);
proxyManagerPlugin = addPlugin("ProxyManager", true);
aliases = new String[] {
"default", "org.apache.openjpa.util.ProxyManagerImpl" };
proxyManagerPlugin.setAliases(aliases);
proxyManagerPlugin.setDefault(aliases[0]);
proxyManagerPlugin.setString(aliases[0]);
proxyManagerPlugin.setInstantiatingGetter("getProxyManagerInstance");
mapping = addString("Mapping");
metaFactoryPlugin = addPlugin(MetaDataFactory.class);
metaFactoryPlugin = addPlugin("MetaDataFactory", false);
metaRepositoryPlugin = new MetaDataRepositoryValue();
addValue(metaRepositoryPlugin);
metaRepositoryPlugin = (MetaDataRepositoryValue) addValue(new MetaDataRepositoryValue());
connectionFactory = addObject(Object.class, "ConnectionFactory");
connectionFactory = addObject("ConnectionFactory");
connectionFactory.setInstantiatingGetter("getConnectionFactory");
connectionFactory2 = addObject(Object.class, "ConnectionFactory2");
connectionFactory2 = addObject("ConnectionFactory2");
connectionFactory2.setInstantiatingGetter("getConnectionFactory2");
// This is done because this plug-in may get initialized very lazily
// when the runtime needs it for flush or a sequence. To keep it
@ -327,7 +367,7 @@ public class OpenJPAConfigurationImpl
connectionPassword.addEquivalentKey("javax.persistence.jdbc.password");
connectionPassword.hide();
encryptionProvider = addPlugin(EncryptionProvider.class, true);
encryptionProvider = addPlugin("EncryptionProvider",true);
connectionURL = addString("ConnectionURL");
connectionURL.addEquivalentKey("javax.persistence.jdbc.url");
@ -359,8 +399,9 @@ public class OpenJPAConfigurationImpl
autoClear = addInt("AutoClear");
aliases =
new String[] { "datastore", String.valueOf(AutoClear.CLEAR_DATASTORE),
"all", String.valueOf(AutoClear.CLEAR_ALL), };
new String[] { "datastore",
String.valueOf(AutoClear.CLEAR_DATASTORE), "all",
String.valueOf(AutoClear.CLEAR_ALL), };
autoClear.setAliases(aliases);
autoClear.setDefault(aliases[0]);
autoClear.set(AutoClear.CLEAR_DATASTORE);
@ -386,11 +427,16 @@ public class OpenJPAConfigurationImpl
autoDetach = new AutoDetachValue();
addValue(autoDetach);
detachStatePlugin = addPlugin(DetachOptions.class, "DetachState", true);
detachStatePlugin.setDefaultAlias("loaded", DetachOptions.Loaded.class);
detachStatePlugin.setAlias("fgs", DetachOptions.FetchGroups.class);
detachStatePlugin.setAlias("fetch-groups", DetachOptions.FetchGroups.class);
detachStatePlugin.setAlias("all", DetachOptions.All.class);
detachStatePlugin = addPlugin("DetachState", true);
aliases = new String[] {
"loaded", DetachOptions.Loaded.class.getName(),
"fgs", DetachOptions.FetchGroups.class.getName(),
"fetch-groups", DetachOptions.FetchGroups.class.getName(),
"all", DetachOptions.All.class.getName(),
};
detachStatePlugin.setAliases(aliases);
detachStatePlugin.setDefault(aliases[0]);
detachStatePlugin.setString(aliases[0]);
detachStatePlugin.setInstantiatingGetter("getDetachStateInstance");
ignoreChanges = addBoolean("IgnoreChanges");
@ -470,21 +516,28 @@ public class OpenJPAConfigurationImpl
connectionRetainMode.setAliasListComprehensive(true);
connectionRetainMode.set(ConnectionRetainModes.CONN_RETAIN_DEMAND);
filterListenerPlugins = addPluginList(FilterListener[].class, "FilterListeners");
filterListenerPlugins = addPluginList("FilterListeners");
filterListenerPlugins.setInstantiatingGetter("getFilterListenerInstances");
aggregateListenerPlugins = addPluginList(AggregateListener[].class, "AggregateListeners");
aggregateListenerPlugins = addPluginList("AggregateListeners");
aggregateListenerPlugins.setInstantiatingGetter("getAggregateListenerInstances");
retryClassRegistration = addBoolean("RetryClassRegistration");
compatibilityPlugin = addPlugin(Compatibility.class, "Compatibility", true);
compatibilityPlugin.setDefaultAlias(Compatibility.class);
compatibilityPlugin = addPlugin("Compatibility", true);
aliases = new String[] { "default", Compatibility.class.getName() };
compatibilityPlugin.setAliases(aliases);
compatibilityPlugin.setDefault(aliases[0]);
compatibilityPlugin.setString(aliases[0]);
compatibilityPlugin.setInstantiatingGetter("getCompatibilityInstance");
callbackPlugin = addPlugin(CallbackOptions.class, "Callbacks", true);
callbackPlugin.setDefaultAlias(CallbackOptions.class);
callbackPlugin = addPlugin("Callbacks", true);
aliases = new String[] { "default", CallbackOptions.class.getName() };
callbackPlugin.setAliases(aliases);
callbackPlugin.setDefault(aliases[0]);
callbackPlugin.setString(aliases[0]);
callbackPlugin.setInstantiatingGetter("getCallbackOptionsInstance");
queryCompilationCachePlugin = new QueryCompilationCacheValue("QueryCompilationCache");
queryCompilationCachePlugin.setInstantiatingGetter("getQueryCompilationCacheInstance");
addValue(queryCompilationCachePlugin);
@ -511,24 +564,37 @@ public class OpenJPAConfigurationImpl
queryTimeout.setDefault("-1");
queryTimeout.setDynamic(true);
lifecycleEventManager = addPlugin(LifecycleEventManager.class, true);
lifecycleEventManager.setDefaultAlias(LifecycleEventManager.class);
lifecycleEventManager.setAlias("validating", ValidatingLifecycleEventManager.class);
lifecycleEventManager = addPlugin("LifecycleEventManager", true);
aliases = new String[] {
"default", LifecycleEventManager.class.getName(),
"validating", ValidatingLifecycleEventManager.class.getName(),
};
lifecycleEventManager.setAliases(aliases);
lifecycleEventManager.setDefault(aliases[0]);
lifecycleEventManager.setString(aliases[0]);
lifecycleEventManager.setInstantiatingGetter("getLifecycleEventManagerInstance");
dynamicEnhancementAgent = addBoolean("DynamicEnhancementAgent");
dynamicEnhancementAgent.setDefault("true");
dynamicEnhancementAgent.set(true);
instrumentationManager = addPlugin(InstrumentationManager.class, true);
instrumentationManager.setDefaultAlias(InstrumentationManagerImpl.class);
instrumentationManager = addPlugin("InstrumentationManager", true);
aliases =
new String[] { "default", InstrumentationManagerImpl.class.getName(), };
instrumentationManager.setAliases(aliases);
instrumentationManager.setDefault(aliases[0]);
instrumentationManager.setString(aliases[0]);
instrumentationManager.setInstantiatingGetter("getInstrumentationManager");
instrumentationProviders = addPluginList(InstrumentationProvider[].class, "Instrumentation");
instrumentationProviders = addPluginList("Instrumentation");
aliases = new String[] { "jmx", "org.apache.openjpa.instrumentation.jmx.JMXProvider" };
instrumentationProviders.setAliases(aliases);
instrumentationProviders.setInstantiatingGetter("getInstrumentationInstances");
auditorPlugin = addPlugin(Auditor.class, true);
auditorPlugin.setAlias("default", AuditLogger.class);
auditorPlugin = addPlugin("Auditor", true);
aliases = new String[] { "default", AuditLogger.class.getName(), };
auditorPlugin.setAliases(aliases);
auditorPlugin.setInstantiatingGetter("getAuditorInstance");
// initialize supported options that some runtimes may not support
supportedOptions.add(OPTION_NONTRANS_READ);
@ -568,7 +634,7 @@ public class OpenJPAConfigurationImpl
}
public Specification getSpecificationInstance() {
return specification.get();
return (Specification)specification.get();
}
/**
@ -599,8 +665,8 @@ public class OpenJPAConfigurationImpl
public ClassResolver getClassResolverInstance() {
if (classResolverPlugin.get() == null)
classResolverPlugin.instantiate(this);
return classResolverPlugin.get();
classResolverPlugin.instantiate(ClassResolver.class, this);
return (ClassResolver) classResolverPlugin.get();
}
public void setBrokerFactory(String factory) {
@ -620,7 +686,7 @@ public class OpenJPAConfigurationImpl
}
public BrokerImpl newBrokerInstance(String user, String pass) {
BrokerImpl broker = (BrokerImpl) brokerPlugin.instantiate(this);
BrokerImpl broker = (BrokerImpl) brokerPlugin.instantiate(BrokerImpl.class, this);
if (broker != null)
broker.setAuthentication(user, pass);
return broker;
@ -641,9 +707,9 @@ public class OpenJPAConfigurationImpl
}
public DataCacheManager getDataCacheManagerInstance() {
DataCacheManager dcm = dataCacheManagerPlugin.get();
DataCacheManager dcm = (DataCacheManager) dataCacheManagerPlugin.get();
if (dcm == null) {
dcm = (DataCacheManager) dataCacheManagerPlugin.instantiate(this);
dcm = (DataCacheManager) dataCacheManagerPlugin.instantiate(DataCacheManager.class, this);
if (dcm != null) {
dcm.initialize(this, dataCachePlugin, queryCachePlugin);
}
@ -718,7 +784,8 @@ public class OpenJPAConfigurationImpl
// don't validate plugin properties on instantiation because it
// is likely that back ends will override defaults with their
// own subclasses with new properties
return lockManagerPlugin.instantiate(this, false);
return (LockManager) lockManagerPlugin.instantiate(LockManager.class,
this, false);
}
public void setInverseManager(String inverseManager) {
@ -730,7 +797,7 @@ public class OpenJPAConfigurationImpl
}
public InverseManager newInverseManagerInstance() {
return inverseManagerPlugin.instantiate(this);
return (InverseManager) inverseManagerPlugin.instantiate(InverseManager.class, this);
}
public void setSavepointManager(String savepointManager) {
@ -743,8 +810,8 @@ public class OpenJPAConfigurationImpl
public SavepointManager getSavepointManagerInstance() {
if (savepointManagerPlugin.get() == null)
savepointManagerPlugin.instantiate(this);
return savepointManagerPlugin.get();
savepointManagerPlugin.instantiate(SavepointManager.class, this);
return (SavepointManager) savepointManagerPlugin.get();
}
public void setOrphanedKeyAction(String action) {
@ -757,8 +824,8 @@ public class OpenJPAConfigurationImpl
public OrphanedKeyAction getOrphanedKeyActionInstance() {
if (orphanedKeyPlugin.get() == null)
orphanedKeyPlugin.instantiate(this);
return orphanedKeyPlugin.get();
orphanedKeyPlugin.instantiate(OrphanedKeyAction.class, this);
return (OrphanedKeyAction) orphanedKeyPlugin.get();
}
public void setOrphanedKeyAction(OrphanedKeyAction action) {
@ -821,8 +888,8 @@ public class OpenJPAConfigurationImpl
public ManagedRuntime getManagedRuntimeInstance() {
if (managedRuntimePlugin.get() == null)
managedRuntimePlugin.instantiate(this);
return managedRuntimePlugin.get();
managedRuntimePlugin.instantiate(ManagedRuntime.class, this);
return (ManagedRuntime) managedRuntimePlugin.get();
}
public void setProxyManager(String proxyManager) {
@ -839,8 +906,8 @@ public class OpenJPAConfigurationImpl
public ProxyManager getProxyManagerInstance() {
if (proxyManagerPlugin.get() == null)
proxyManagerPlugin.instantiate(this);
return proxyManagerPlugin.get();
proxyManagerPlugin.instantiate(ProxyManager.class, this);
return (ProxyManager) proxyManagerPlugin.get();
}
public void setMapping(String mapping) {
@ -852,7 +919,7 @@ public class OpenJPAConfigurationImpl
}
public void setMetaDataFactory(String meta) {
metaFactoryPlugin.setString(meta);
this.metaFactoryPlugin.setString(meta);
}
public String getMetaDataFactory() {
@ -860,11 +927,12 @@ public class OpenJPAConfigurationImpl
}
public MetaDataFactory newMetaDataFactoryInstance() {
return metaFactoryPlugin.instantiate(this);
return (MetaDataFactory) metaFactoryPlugin.instantiate(
MetaDataFactory.class, this);
}
public void setMetaDataRepository(String meta) {
metaRepositoryPlugin.setString(meta);
this.metaRepositoryPlugin.setString(meta);
}
public String getMetaDataRepository() {
@ -886,23 +954,24 @@ public class OpenJPAConfigurationImpl
}
public MetaDataRepository newMetaDataRepositoryInstance() {
return metaRepositoryPlugin.instantiate(this);
return (MetaDataRepository) metaRepositoryPlugin.instantiate(
MetaDataRepository.class, this);
}
public void setConnectionUserName(String userName) {
connectionUserName.setString(userName);
public void setConnectionUserName(String connectionUserName) {
this.connectionUserName.setString(connectionUserName);
}
public String getConnectionUserName() {
return connectionUserName.getString();
}
public void setConnectionPassword(String pwd) {
connectionPassword.setString(pwd);
public void setConnectionPassword(String connectionPassword) {
this.connectionPassword.setString(connectionPassword);
}
public String getConnectionPassword() {
EncryptionProvider p = getEncryptionProviderInstance();
EncryptionProvider p = getEncryptionProvider();
if(p != null) {
return p.decrypt(connectionPassword.getString());
}
@ -1006,8 +1075,8 @@ public class OpenJPAConfigurationImpl
}
public String getConnection2Password() {
EncryptionProvider p = getEncryptionProviderInstance();
if (p != null) {
EncryptionProvider p = getEncryptionProvider();
if(p != null){
return p.decrypt(connection2Password.getString());
}
return connection2Password.getString();
@ -1155,8 +1224,8 @@ public class OpenJPAConfigurationImpl
public DetachOptions getDetachStateInstance() {
if (detachStatePlugin.get() == null)
detachStatePlugin.instantiate(this);
return detachStatePlugin.get();
detachStatePlugin.instantiate(DetachOptions.class, this);
return (DetachOptions) detachStatePlugin.get();
}
public void setIgnoreChanges(boolean ignoreChanges) {
@ -1165,7 +1234,7 @@ public class OpenJPAConfigurationImpl
public void setIgnoreChanges(Boolean ignoreChanges) {
if (ignoreChanges != null)
setIgnoreChanges(ignoreChanges);
setIgnoreChanges(ignoreChanges.booleanValue());
}
public boolean getIgnoreChanges() {
@ -1336,8 +1405,8 @@ public class OpenJPAConfigurationImpl
public Seq getSequenceInstance() {
if (seqPlugin.get() == null)
seqPlugin.instantiate(this);
return seqPlugin.get();
seqPlugin.instantiate(Seq.class, this);
return (Seq) seqPlugin.get();
}
public void setConnectionRetainMode(String connectionRetainMode) {
@ -1370,8 +1439,8 @@ public class OpenJPAConfigurationImpl
public FilterListener[] getFilterListenerInstances() {
if (filterListenerPlugins.get() == null)
filterListenerPlugins.instantiate(this);
return filterListenerPlugins.get();
filterListenerPlugins.instantiate(FilterListener.class, this);
return (FilterListener[]) filterListenerPlugins.get();
}
public void setAggregateListeners(String aggregateListeners) {
@ -1388,8 +1457,8 @@ public class OpenJPAConfigurationImpl
public AggregateListener[] getAggregateListenerInstances() {
if (aggregateListenerPlugins.get() == null)
aggregateListenerPlugins.instantiate(this);
return aggregateListenerPlugins.get();
aggregateListenerPlugins.instantiate(AggregateListener.class, this);
return (AggregateListener[]) aggregateListenerPlugins.get();
}
public void setRetryClassRegistration(boolean retry) {
@ -1424,11 +1493,11 @@ public class OpenJPAConfigurationImpl
Specification spec = getSpecificationInstance();
Compatibility comp = spec != null ? spec.getCompatibility() : null;
if (comp == null)
compatibilityPlugin.instantiate(this);
compatibilityPlugin.instantiate(Compatibility.class, this);
else
compatibilityPlugin.configure(comp, this);
}
return compatibilityPlugin.get();
return (Compatibility) compatibilityPlugin.get();
}
public String getCallbackOptions() {
@ -1441,8 +1510,8 @@ public class OpenJPAConfigurationImpl
public CallbackOptions getCallbackOptionsInstance() {
if (callbackPlugin.get() == null)
callbackPlugin.instantiate(this);
return callbackPlugin.get();
callbackPlugin.instantiate(CallbackOptions.class, this);
return (CallbackOptions) callbackPlugin.get();
}
public String getQueryCompilationCache() {
@ -1455,8 +1524,8 @@ public class OpenJPAConfigurationImpl
public Map getQueryCompilationCacheInstance() {
if (queryCompilationCachePlugin.get() == null)
queryCompilationCachePlugin.instantiate(this);
return queryCompilationCachePlugin.get();
queryCompilationCachePlugin.instantiate(Map.class, this);
return (Map) queryCompilationCachePlugin.get();
}
public StoreFacadeTypeRegistry getStoreFacadeTypeRegistry() {
@ -1557,8 +1626,8 @@ public class OpenJPAConfigurationImpl
public InstrumentationProvider[] getInstrumentationInstances() {
if (instrumentationProviders.get() == null)
instrumentationProviders.instantiate(this);
return instrumentationProviders.get();
instrumentationProviders.instantiate(InstrumentationProvider.class, this);
return (InstrumentationProvider[]) instrumentationProviders.get();
}
public void setInstrumentationManager(String mgr) {
@ -1578,7 +1647,7 @@ public class OpenJPAConfigurationImpl
public InstrumentationManager getInstrumentationManagerInstance() {
InstrumentationManager im = (InstrumentationManager) instrumentationManager.get();
if (im == null) {
im = instrumentationManager.instantiate(this);
im = (InstrumentationManager) instrumentationManager.instantiate(InstrumentationManager.class, this);
if (im != null) {
im.initialize(this, instrumentationProviders);
im.start(InstrumentationLevel.IMMEDIATE, this);
@ -1627,9 +1696,10 @@ public class OpenJPAConfigurationImpl
return null;
if (preparedQueryCachePlugin.get() == null) {
preparedQueryCachePlugin.instantiate(this);
preparedQueryCachePlugin.instantiate(PreparedQueryCache.class,
this);
}
return preparedQueryCachePlugin.get();
return (PreparedQueryCache)preparedQueryCachePlugin.get();
}
public void setFinderCache(String finderCache) {
@ -1642,9 +1712,9 @@ public class OpenJPAConfigurationImpl
public FinderCache getFinderCacheInstance() {
if (finderCachePlugin.get() == null) {
finderCachePlugin.instantiate(this);
finderCachePlugin.instantiate(FinderCache.class, this);
}
return finderCachePlugin.get();
return (FinderCache)finderCachePlugin.get();
}
public Object getValidationFactoryInstance() {
@ -1655,11 +1725,11 @@ public class OpenJPAConfigurationImpl
validationFactory.set(factory);
}
public Validator getValidatorInstance() {
public Object getValidatorInstance() {
return validator.get();
}
public void setValidatorInstance(Validator val) {
public void setValidatorInstance(Object val) {
validator.set(val);
}
@ -1671,7 +1741,8 @@ public class OpenJPAConfigurationImpl
LifecycleEventManager lem = (LifecycleEventManager)
lifecycleEventManager.get();
if (lem == null) {
lem = lifecycleEventManager.instantiate(this);
lem = (LifecycleEventManager)lifecycleEventManager
.instantiate(LifecycleEventManager.class, this);
}
return lem;
}
@ -1702,10 +1773,10 @@ public class OpenJPAConfigurationImpl
encryptionProvider.setString(p);
}
public EncryptionProvider getEncryptionProviderInstance() {
public EncryptionProvider getEncryptionProvider() {
if (encryptionProvider.get() == null)
encryptionProvider.instantiate(this);
return encryptionProvider.get();
encryptionProvider.instantiate(EncryptionProvider.class, this);
return (EncryptionProvider) encryptionProvider.get();
}
public void setDataCacheMode(String mode) {
@ -1722,9 +1793,10 @@ public class OpenJPAConfigurationImpl
}
public CacheDistributionPolicy getCacheDistributionPolicyInstance() {
CacheDistributionPolicy policy = cacheDistributionPolicyPlugin.get();
CacheDistributionPolicy policy = (CacheDistributionPolicy) cacheDistributionPolicyPlugin.get();
if (policy == null) {
policy = cacheDistributionPolicyPlugin.instantiate(this);
policy = (CacheDistributionPolicy)
cacheDistributionPolicyPlugin.instantiate(CacheDistributionPolicy.class, this);
}
return policy;
}
@ -1746,9 +1818,9 @@ public class OpenJPAConfigurationImpl
}
public Auditor getAuditorInstance() {
Auditor auditor = auditorPlugin.get();
Auditor auditor = (Auditor) auditorPlugin.get();
if (auditor == null) {
auditor = auditorPlugin.instantiate(this);
auditor = (Auditor) auditorPlugin.instantiate(Auditor.class, this);
}
return auditor;
}

View File

@ -36,7 +36,7 @@ import org.apache.openjpa.util.CacheMap;
* @nojavadoc
*/
public class QueryCompilationCacheValue
extends PluginValue<Map> {
extends PluginValue {
public static final String[] ALIASES = {
"true", CacheMap.class.getName(),
@ -45,18 +45,19 @@ public class QueryCompilationCacheValue
};
public QueryCompilationCacheValue(String prop) {
super(Map.class, prop, true);
super(prop, true);
setAliases(ALIASES);
setDefault(ALIASES[0]);
setClassName(ALIASES[1]);
}
public Map newInstance(String clsName, Configuration conf, boolean fatal) {
public Object newInstance(String clsName, Class type,
Configuration conf, boolean fatal) {
// make sure map handles concurrency
Map map;
try {
map = super.newInstance(clsName, conf, fatal);
map = (Map) super.newInstance(clsName, type, conf, fatal);
} catch (ParseException pe) {
// OPENJPA256: this class differs from most plugins in that
// the plugin type is the standard java interface Map.class (rather
@ -67,7 +68,8 @@ public class QueryCompilationCacheValue
// the ParseException (which is what we wrap the
// ClassNotFoundException in) and try again, this time using
// this class' ClassLoader.
map = super.newInstance(clsName, conf, fatal);
map = (Map) super.newInstance(clsName,
QueryCompilationCacheValue.class, conf, fatal);
} catch (IllegalArgumentException iae) {
// OPENJPA256: this class differs from most plugins in that
// the plugin type is the standard java interface Map.class (rather
@ -78,7 +80,8 @@ public class QueryCompilationCacheValue
// the IllegalArgumentException (which is what we wrap the
// ClassNotFoundException in) and try again, this time using
// this class' ClassLoader.
map = super.newInstance(clsName, conf, fatal);
map = (Map) super.newInstance(clsName,
QueryCompilationCacheValue.class, conf, fatal);
}
if (map != null && !(map instanceof Hashtable)

View File

@ -35,7 +35,7 @@ import org.apache.openjpa.lib.util.Options;
* @nojavadoc
*/
public class RemoteCommitProviderValue
extends PluginValue<RemoteCommitProvider> {
extends PluginValue {
private static final String[] ALIASES = new String[]{
"sjvm", "org.apache.openjpa.event.SingleJVMRemoteCommitProvider",
@ -47,7 +47,7 @@ public class RemoteCommitProviderValue
private Boolean _transmitPersIds = null;
public RemoteCommitProviderValue() {
super(RemoteCommitProvider.class, "RemoteCommitProvider", true);
super("RemoteCommitProvider", true);
setAliases(ALIASES);
}
@ -67,7 +67,7 @@ public class RemoteCommitProviderValue
* The cached provider.
*/
public RemoteCommitProvider getProvider() {
return get();
return (RemoteCommitProvider) get();
}
/**
@ -101,8 +101,10 @@ public class RemoteCommitProviderValue
/**
* Instantiate the provider.
*/
public RemoteCommitProvider instantiateProvider(Configuration conf, boolean fatal) {
return instantiate(conf, fatal);
public RemoteCommitProvider instantiateProvider(Configuration conf,
boolean fatal) {
return (RemoteCommitProvider) instantiate(RemoteCommitProvider.class,
conf, fatal);
}
/**
@ -117,8 +119,8 @@ public class RemoteCommitProviderValue
/**
* Override to keep decorators out of transport configuration.
*/
public RemoteCommitProvider instantiate(Configuration conf, boolean fatal) {
RemoteCommitProvider obj = newInstance(getClassName(), conf, fatal);
public Object instantiate(Class type, Configuration conf, boolean fatal) {
Object obj = newInstance(getClassName(), type, conf, fatal);
parseOptions();
Configurations.configureInstance(obj, conf, _opts, getProperty());
set(obj, true);

View File

@ -18,7 +18,6 @@
*/
package org.apache.openjpa.conf;
import org.apache.openjpa.kernel.Seq;
import org.apache.openjpa.kernel.TimeSeededSeq;
import org.apache.openjpa.lib.conf.PluginValue;
import org.apache.openjpa.meta.SequenceMetaData;
@ -32,7 +31,7 @@ import org.apache.openjpa.meta.SequenceMetaData;
* @nojavadoc
*/
public class SeqValue
extends PluginValue<Seq> {
extends PluginValue {
private static final String[] ALIASES = new String[]{
SequenceMetaData.IMPL_TIME, TimeSeededSeq.class.getName(),
@ -42,7 +41,7 @@ public class SeqValue
};
public SeqValue(String prop) {
super(Seq.class, prop, true);
super(prop, true);
setAliases(ALIASES);
setDefault(ALIASES[0]);
setClassName(ALIASES[1]);

View File

@ -33,17 +33,22 @@ import org.apache.openjpa.util.UserException;
* @author Pinaki Poddar
*
*/
public class SpecificationPlugin extends ObjectValue<Specification> implements ValueListener {
public class SpecificationPlugin extends ObjectValue implements ValueListener {
private Configuration _conf;
protected static final Localizer _loc = Localizer.forPackage
(SpecificationPlugin.class);
public SpecificationPlugin(Configuration conf, String prop) {
super(Specification.class, prop);
super(prop);
_conf = conf;
addListener(this);
}
@Override
public Class<?> getValueType() {
return Specification.class;
}
/**
* Set a value from the given String after validating.
*
@ -62,12 +67,16 @@ public class SpecificationPlugin extends ObjectValue<Specification> implements V
* @param obj can be null to set the Specification to null.
*/
@Override
public void set(Specification obj) {
public void set(Object obj) {
if (obj == null) {
super.set(null);
return;
}
validateOverwrite(obj);
if (obj instanceof Specification == false) {
throw new UserException(_loc.get("spec-wrong-obj", obj,
obj.getClass())).setFatal(true);
}
validateOverwrite((Specification)obj);
super.set(obj);
}

View File

@ -101,7 +101,11 @@ public abstract class AbstractQueryCache
entityTimestampMap = new ConcurrentHashMap<String,Long>();
// Get all persistence types to pre-load the entityTimestamp Map
Collection perTypes = conf.getMetaDataRepositoryInstance().getPersistentTypeNames(false);
Collection perTypes =
conf.getMetaDataRepositoryInstance().getPersistentTypeNames(
false,
AccessController.doPrivileged(J2DoPrivHelper
.getContextClassLoaderAction()));
// Pre-load all the entity types into the HashMap to handle
// synchronization on the map efficiently
@ -299,7 +303,7 @@ public abstract class AbstractQueryCache
// ok if no metadata for oid; that just means the pc type
// probably hasn't been loaded into this JVM yet, and therefore
// there's no chance that it's in the cache anyway
meta = repos.getMetaData(oid, false);
meta = repos.getMetaData(oid, null, false);
if (meta != null)
classes.add(meta.getDescribedType());
}

View File

@ -36,7 +36,7 @@ class Caches {
if (classNames == null || classNames.isEmpty())
return classes;
ClassLoader loader = conf.getClassLoader();
ClassLoader loader = conf.getClassResolverInstance().getClassLoader(null, null);
Class<?> cls;
for (String className : classNames) {

View File

@ -43,8 +43,8 @@ public interface DataCacheManager {
/**
* Initialize the manager, supplying the cache configuration.
*/
public void initialize(OpenJPAConfiguration conf, ObjectValue<DataCache> dataCache,
ObjectValue<QueryCache> queryCache);
public void initialize(OpenJPAConfiguration conf, ObjectValue dataCache,
ObjectValue queryCache);
/**
* Return the system-wide data cache, or null if caching is not enabled.

View File

@ -57,13 +57,12 @@ public class DataCacheManagerImpl
private Set<String> _includedTypes;
private Set<String> _excludedTypes;
public void initialize(OpenJPAConfiguration conf, ObjectValue<DataCache> dataCache,
ObjectValue<QueryCache> queryCache) {
public void initialize(OpenJPAConfiguration conf, ObjectValue dataCache, ObjectValue queryCache) {
_conf = conf;
_queryCache = queryCache.instantiate(conf);
_queryCache = (QueryCache) queryCache.instantiate(QueryCache.class, conf);
if (_queryCache != null)
_queryCache.initialize(this);
_cache = dataCache.instantiate(conf);
_cache = (DataCache) dataCache.instantiate(DataCache.class, conf);
if (_cache == null)
return;

View File

@ -112,9 +112,11 @@ public class DataCacheStoreManager
return;
MetaDataRepository mdr = _ctx.getConfiguration().getMetaDataRepositoryInstance();
ClassLoader loader = _ctx.getClassLoader();
DataCache cache;
for (Class<?> cls : classes) {
cache = mdr.getMetaData(cls, false).getDataCache();
cache = mdr.getMetaData(cls, loader, false).getDataCache();
if (cache != null && cache.getEvictOnBulkUpdate())
cache.removeAll(cls, false);
}
@ -655,7 +657,7 @@ public class DataCacheStoreManager
return unloaded;
}
public Collection<Exception> flush(Collection<? extends OpenJPAStateManager> states) {
public Collection<Exception> flush(Collection<OpenJPAStateManager> states) {
Collection<Exception> exceps = super.flush(states);
// if there were errors evict bad instances and don't record changes

View File

@ -86,7 +86,8 @@ public class PartitionedDataCache extends ConcurrentDataCache {
*/
public void setPartitionType(String type) throws Exception {
Value value = conf.getValue("DataCache");
ClassLoader loader = conf.getClassLoader();
ClassLoader ctxLoader = AccessController.doPrivileged(J2DoPrivHelper.getContextClassLoaderAction());
ClassLoader loader = conf.getClassResolverInstance().getClassLoader(null, ctxLoader);
_type = (Class<? extends DataCache>) AccessController.doPrivileged(
J2DoPrivHelper.getForNameAction(value.unalias(type), true, loader));
}
@ -100,12 +101,12 @@ public class PartitionedDataCache extends ConcurrentDataCache {
public void setPartitions(String parts) {
_partProperties.clear();
parsePartitionProperties(parts);
PluginListValue<DataCache> partitions = new PluginListValue<DataCache>(DataCache[].class, "partitions");
PluginListValue partitions = new PluginListValue("partitions");
String[] types = (String[])Array.newInstance(String.class, _partProperties.size());
Arrays.fill(types, _type.getName());
partitions.setClassNames(types);
partitions.setProperties(_partProperties.toArray(new String[_partProperties.size()]));
DataCache[] array = partitions.instantiate(conf);
DataCache[] array = (DataCache[])partitions.instantiate(_type, conf);
for (DataCache part : array) {
if (part.getName() == null)
throw new UserException(_loc.get("partition-cache-null-partition", parts));

View File

@ -222,7 +222,7 @@ public class QueryKey
// won't find metadata for interfaces.
if (candidateClass.isInterface())
return null;
meta = repos.getMetaData(candidateClass, true);
meta = repos.getMetaData(candidateClass, ctx.getClassLoader(), true);
int timeout = meta.getDataCacheTimeout();
if (subclasses) {
metas = meta.getPCSubclassMetaDatas();

View File

@ -62,8 +62,10 @@ public class InvocationManagedRuntime extends AbstractManagedRuntime
public TransactionManager getTransactionManager()
throws Exception {
if (_method == null) {
ClassLoader loader = _conf.getClassLoader();
_method = Class.forName(_clazz, true, loader).getMethod(_methodName, null);
ClassLoader loader = _conf.getClassResolverInstance().
getClassLoader(getClass(), null);
_method = Class.forName(_clazz, true, loader)
.getMethod(_methodName, null);
}
return (TransactionManager) _method.invoke(null, null);
}

View File

@ -103,7 +103,7 @@ public class ApplicationIdTool {
repos.setValidate(repos.VALIDATE_NONE);
repos.setSourceMode(repos.MODE_MAPPING, false);
loadObjectIds(repos, true);
_meta = repos.getMetaData(type, false);
_meta = repos.getMetaData(type, null, false);
if (_meta != null) {
_abstract = Modifier.isAbstract(_meta.getDescribedType().
getModifiers());
@ -1335,13 +1335,16 @@ public class ApplicationIdTool {
}
Configurations.populateConfiguration(conf, opts);
return run(conf, args, flags);
ClassLoader loader = conf.getClassResolverInstance().
getClassLoader(ApplicationIdTool.class, null);
return run(conf, args, flags, loader);
}
/**
* Run the tool. Returns false if invalid options were given.
*/
public static boolean run(OpenJPAConfiguration conf, String[] args, Flags flags)
public static boolean run(OpenJPAConfiguration conf, String[] args,
Flags flags, ClassLoader loader)
throws IOException, ClassNotFoundException {
MetaDataRepository repos = conf.newMetaDataRepositoryInstance();
repos.setValidate(repos.VALIDATE_NONE, true);
@ -1351,11 +1354,11 @@ public class ApplicationIdTool {
Collection classes;
if (args.length == 0) {
log.info(_loc.get("running-all-classes"));
classes = repos.loadPersistentTypes(true);
classes = repos.loadPersistentTypes(true, loader);
} else {
ClassArgParser cap = conf.getMetaDataRepositoryInstance().
getMetaDataFactory().newClassArgParser();
cap.setClassLoader(conf.getClassLoader());
cap.setClassLoader(loader);
classes = new HashSet();
for (int i = 0; i < args.length; i++)
classes.addAll(Arrays.asList(cap.parseTypes(args[i])));
@ -1372,7 +1375,7 @@ public class ApplicationIdTool {
cls = (Class) itr.next();
log.info(_loc.get("appid-running", cls));
meta = repos.getMetaData(cls, false);
meta = repos.getMetaData(cls, null, false);
setObjectIdType(meta, flags, bc);
tool = new ApplicationIdTool(conf, cls, meta);

View File

@ -25,8 +25,6 @@ import java.lang.reflect.Method;
import java.security.ProtectionDomain;
import java.util.Map;
import javax.security.auth.login.Configuration;
import org.apache.openjpa.conf.OpenJPAConfiguration;
import org.apache.openjpa.lib.log.Log;
import org.apache.openjpa.lib.util.JavaVersions;
@ -55,13 +53,13 @@ public class ClassRedefiner {
public static void redefineClasses(OpenJPAConfiguration conf,
final Map<Class<?>,byte[]> classes) {
Log log = conf.getLog(OpenJPAConfiguration.LOG_ENHANCE);
if (classes == null || classes.size() == 0 || !canRedefineClasses(conf))
if (classes == null || classes.size() == 0 || !canRedefineClasses(log))
return;
Instrumentation inst = null;
ClassFileTransformer t = null;
try {
inst = InstrumentationFactory.getInstrumentation(conf);
inst = InstrumentationFactory.getInstrumentation(log);
Class<?>[] array = classes.keySet().toArray(new Class[classes.size()]);
if (JavaVersions.VERSION >= 6) {
@ -89,9 +87,9 @@ public class ClassRedefiner {
log.trace(_loc.get("redefine-types", classes.keySet()));
// in a Java 5 context, we can use class redefinition instead
ClassDefinition[] defs = new ClassDefinition[array.length];
for (int i = 0; i < defs.length; i++) {
defs[i] = new ClassDefinition(array[i], classes.get(array[i]));
}
for (int i = 0; i < defs.length; i++)
defs[i] = new ClassDefinition(array[i],
classes.get(array[i]));
inst.redefineClasses(defs);
}
} catch (Exception e) {
@ -110,10 +108,10 @@ public class ClassRedefiner {
* only checks whether or not an instrumentation is available and
* if retransformation is possible.
*/
public static boolean canRedefineClasses(OpenJPAConfiguration conf) {
public static boolean canRedefineClasses(Log log) {
if (_canRedefine == null) {
try {
Instrumentation inst = InstrumentationFactory.getInstrumentation(conf);
Instrumentation inst = InstrumentationFactory.getInstrumentation(log);
if (inst == null) {
_canRedefine = Boolean.FALSE;
} else if (JavaVersions.VERSION == 5) {

View File

@ -57,7 +57,8 @@ public class CodeGenerator {
* Constructor. Supply configuration and class to generate code for.
*/
public CodeGenerator(OpenJPAConfiguration conf, Class type) {
this(conf.newMetaDataRepositoryInstance().getMetaData(type, true));
this(conf.newMetaDataRepositoryInstance().
getMetaData(type, null, true));
}
/**

View File

@ -37,8 +37,6 @@ import java.util.jar.Manifest;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.apache.openjpa.conf.OpenJPAConfiguration;
import org.apache.openjpa.lib.conf.Configuration;
import org.apache.openjpa.lib.log.Log;
import org.apache.openjpa.lib.util.J2DoPrivHelper;
import org.apache.openjpa.lib.util.JavaVendors;
@ -55,7 +53,9 @@ import org.apache.openjpa.lib.util.Localizer;
public class InstrumentationFactory {
private static Instrumentation _inst;
private static boolean _dynamicallyInstall = true;
private static final Localizer _loc = Localizer.forPackage(InstrumentationFactory.class);
private static final String _name = InstrumentationFactory.class.getName();
private static final Localizer _loc = Localizer.forPackage(
InstrumentationFactory.class);
/**
* This method is not synchronized because when the agent is loaded from
@ -81,48 +81,63 @@ public class InstrumentationFactory {
* @return null if Instrumentation can not be obtained, or if any
* Exceptions are encountered.
*/
public static synchronized Instrumentation getInstrumentation(final OpenJPAConfiguration conf) {
final Log log = conf.getConfigurationLog();
trace(conf, "getInstrumentation()", "_inst:" + _inst + " _dynamicallyInstall:" + _dynamicallyInstall);
public static synchronized Instrumentation getInstrumentation(final Log log) {
if (log.isTraceEnabled() == true) {
log.trace(_name + ".getInstrumentation() _inst:" + _inst
+ " _dynamicallyInstall:" + _dynamicallyInstall);
}
if ( _inst != null || !_dynamicallyInstall)
return _inst;
// dynamic loading of the agent is only available in JDK 1.6+
if (JavaVersions.VERSION < 6) {
trace(conf, "getInstrumentation()", "Dynamic loading only supported on Java SE 6 or later");
if (log.isTraceEnabled() == true) {
log.trace(_name + ".getInstrumentation() Dynamic loading only supported on Java SE 6 or later");
}
return null;
}
AccessController.doPrivileged(new PrivilegedAction<Object>() {
public Object run() {
// Dynamic agent enhancement should only occur when the OpenJPA library is
// loaded using the system class loader. Otherwise, the OpenJPA
// library may get loaded by separate, disjunct loaders, leading to linkage issues.
try {
if (!InstrumentationFactory.class.getClassLoader().equals(
ClassLoader.getSystemClassLoader())) {
return null;
}
} catch (Throwable t) {
return null;
}
JavaVendors vendor = JavaVendors.getCurrentVendor();
File toolsJar = null;
// When running on IBM, the attach api classes are packaged in vm.jar which is a part
// of the default vm classpath.
if (!vendor.isIBM()) {
if (vendor.isIBM() == false) {
// If we can't find the tools.jar and we're not on IBM we can't load the agent.
toolsJar = findToolsJar(conf);
toolsJar = findToolsJar(log);
if (toolsJar == null) {
return null;
}
}
Class<?> vmClass = loadVMClass(toolsJar, conf, vendor);
Class<?> vmClass = loadVMClass(toolsJar, log, vendor);
if (vmClass == null) {
return null;
}
String agentPath = getAgentJar(conf);
String agentPath = getAgentJar(log);
if (agentPath == null) {
return null;
}
loadAgent(conf, agentPath, vmClass);
loadAgent(log, agentPath, vmClass);
return null;
}
}// end run()
});
// If the load(...) agent call was successful, this variable will no
// longer be null.
return _inst;
}
}//end getInstrumentation()
/**
* The method that is called when a jar is added as an agent at runtime.
@ -161,35 +176,52 @@ public class InstrumentationFactory {
}
/**
* Finds [java_home]/lib/tools.jar.
* This private worker method attempts to find [java_home]/lib/tools.jar.
* Note: The tools.jar is a part of the SDK, it is not present in the JRE.
*
* @return If tools.jar can be found, a File representing tools.jar. <BR>
* If tools.jar cannot be found, null.
*/
private static File findToolsJar(Configuration conf) {
private static File findToolsJar(Log log) {
String javaHome = System.getProperty("java.home");
File javaHomeFile = new File(javaHome);
File toolsJarFile = new File(javaHomeFile, "lib" + File.separator + "tools.jar");
if (!toolsJarFile.exists()) {
// If we're on an IBM SDK, then remove /jre off of java.home and try again.
if (javaHomeFile.getAbsolutePath().endsWith(File.separator + "jre")) {
if (toolsJarFile.exists() == false) {
if (log.isTraceEnabled() == true) {
log.trace(_name + ".findToolsJar() -- couldn't find default " + toolsJarFile.getAbsolutePath());
}
// If we're on an IBM SDK, then remove /jre off of java.home and try again.
if (javaHomeFile.getAbsolutePath().endsWith(File.separator + "jre") == true) {
javaHomeFile = javaHomeFile.getParentFile();
toolsJarFile = new File(javaHomeFile, "lib" + File.separator + "tools.jar");
if (toolsJarFile.exists() == false) {
if (log.isTraceEnabled() == true) {
log.trace(_name + ".findToolsJar() -- for IBM SDK couldn't find " +
toolsJarFile.getAbsolutePath());
}
}
} else if (System.getProperty("os.name").toLowerCase().indexOf("mac") >= 0) {
// If we're on a Mac, then change the search path to use ../Classes/classes.jar.
if (javaHomeFile.getAbsolutePath().endsWith(File.separator + "Home") == true) {
javaHomeFile = javaHomeFile.getParentFile();
toolsJarFile = new File(javaHomeFile, "Classes" + File.separator + "classes.jar");
if (toolsJarFile.exists() == false) {
if (log.isTraceEnabled() == true) {
log.trace(_name + ".findToolsJar() -- for Mac OS couldn't find " +
toolsJarFile.getAbsolutePath());
}
}
}
}
}
if (!toolsJarFile.exists()) {
if (toolsJarFile.exists() == false) {
return null;
} else {
trace(conf, ".findToolsJar()", "found " + toolsJarFile.getAbsolutePath());
if (log.isTraceEnabled() == true) {
log.trace(_name + ".findToolsJar() -- found " + toolsJarFile.getAbsolutePath());
}
return toolsJarFile;
}
}
@ -204,14 +236,15 @@ public class InstrumentationFactory {
* @return absolute path to the agent jar or null if anything unexpected
* happens.
*/
private static String getAgentJar(Configuration conf) {
private static String getAgentJar(Log log) {
File agentJarFile = null;
// Find the name of the File that this class was loaded from. That
// jar *should* be the same location as our agent.
CodeSource cs = InstrumentationFactory.class.getProtectionDomain().getCodeSource();
CodeSource cs =
InstrumentationFactory.class.getProtectionDomain().getCodeSource();
if (cs != null) {
URL loc = cs.getLocation();
if (loc != null){
if(loc!=null){
agentJarFile = new File(loc.getFile());
}
}
@ -219,27 +252,30 @@ public class InstrumentationFactory {
// Determine whether the File that this class was loaded from has this
// class defined as the Agent-Class.
boolean createJar = false;
if (cs == null || agentJarFile == null || agentJarFile.isDirectory()) {
if (cs == null || agentJarFile == null
|| agentJarFile.isDirectory() == true) {
createJar = true;
} else if (!InstrumentationFactory.class.getName().equals(getAgentClassName(agentJarFile, conf))) {
}else if(validateAgentJarManifest(agentJarFile, log, _name) == false){
// We have an agentJarFile, but this class isn't the Agent-Class.
createJar = true;
createJar=true;
}
String agentJar;
if (createJar) {
if (createJar == true) {
// This can happen when running in eclipse as an OpenJPA
// developer or for some reason the CodeSource is null. We
// should log a warning here because this will create a jar
// in your temp directory that doesn't always get cleaned up.
try {
agentJar = createAgentJar();
Log log = conf.getConfigurationLog();
if (log.isInfoEnabled()) {
if (log.isInfoEnabled() == true) {
log.info(_loc.get("temp-file-creation", agentJar));
}
} catch (IOException ioe) {
trace(conf, "getAgentJar()", "caught unexpected exception " + ioe);
if (log.isTraceEnabled() == true) {
log.trace(_name + ".getAgentJar() caught unexpected "
+ "exception.", ioe);
}
agentJar = null;
}
} else {
@ -247,7 +283,7 @@ public class InstrumentationFactory {
}
return agentJar;
}
}//end getAgentJar
/**
* Attach and load an agent class.
@ -256,7 +292,7 @@ public class InstrumentationFactory {
* @param agentJar absolute path to the agent jar.
* @param vmClass VirtualMachine.class from tools.jar.
*/
private static void loadAgent(Configuration conf, String agentJar, Class<?> vmClass) {
private static void loadAgent(Log log, String agentJar, Class<?> vmClass) {
try {
// first obtain the PID of the currently-running process
// ### this relies on the undocumented convention of the
@ -277,13 +313,18 @@ public class InstrumentationFactory {
.invoke(null, new Object[] { pid });
// now deploy the actual agent, which will wind up calling
// agentmain()
vmClass.getMethod("loadAgent", new Class[] { String.class }).invoke(vm, new Object[] { agentJar });
vmClass.getMethod("detach", new Class[] {}).invoke(vm, new Object[] {});
vmClass.getMethod("loadAgent", new Class[] { String.class })
.invoke(vm, new Object[] { agentJar });
vmClass.getMethod("detach", new Class[] {}).invoke(vm,
new Object[] {});
} catch (Throwable t) {
// Log the message from the exception. Don't log the entire
// stack as this is expected when running on a JDK that doesn't
// support the Attach API.
trace(conf, "loadAgent()", "caught an exception. Message: " + t.getMessage());
if (log.isTraceEnabled() == true) {
// Log the message from the exception. Don't log the entire
// stack as this is expected when running on a JDK that doesn't
// support the Attach API.
log.trace(_name + ".loadAgent() caught an exception. Message: "
+ t.getMessage());
}
}
}
@ -299,16 +340,19 @@ public class InstrumentationFactory {
* @return The AttachAPI VirtualMachine class <br>
* or null if something unexpected happened.
*/
private static Class<?> loadVMClass(File toolsJar, Configuration conf, JavaVendors vendor) {
private static Class<?> loadVMClass(File toolsJar, Log log, JavaVendors vendor) {
try {
ClassLoader loader = Thread.currentThread().getContextClassLoader();
String cls = vendor.getVirtualMachineClassName();
if (!vendor.isIBM()) {
if (vendor.isIBM() == false) {
loader = new URLClassLoader(new URL[] { toolsJar.toURI().toURL() }, loader);
}
return loader.loadClass(cls);
} catch (Exception e) {
trace(conf, "loadVMClass()", "failed to load the VirtualMachine class");
if (log.isTraceEnabled()) {
log.trace(_name
+ ".loadVMClass() failed to load the VirtualMachine class");
}
}
return null;
}
@ -326,25 +370,26 @@ public class InstrumentationFactory {
* @return True if the provided agentClassName is defined as the Agent-Class
* in the manifest from the provided agentJarFile. False otherwise.
*/
private static String getAgentClassName(File agentJarFile, Configuration conf) {
private static boolean validateAgentJarManifest(File agentJarFile, Log log,
String agentClassName) {
try {
JarFile jar = new JarFile(agentJarFile);
Manifest manifest = jar.getManifest();
if (manifest == null) {
return null;
return false;
}
Attributes attributes = manifest.getMainAttributes();
return attributes.getValue("Agent-Class");
String ac = attributes.getValue("Agent-Class");
if (ac != null && ac.equals(agentClassName)) {
return true;
}
} catch (Exception e) {
trace(conf, "validateAgentJarManifest()", " caught unexpected exception " + e.getMessage());
if (log.isTraceEnabled() == true) {
log.trace(_name
+ ".validateAgentJarManifest() caught unexpected "
+ "exception " + e.getMessage());
}
}
return null;
}
private static void trace(Configuration conf, String method, String message) {
Log log = conf.getConfigurationLog();
if (log.isTraceEnabled()) {
log.trace(InstrumentationFactory.class.getName() + "." + method + ":" + message);
}
}
return false;
}// end validateAgentJarManifest
}

View File

@ -32,8 +32,9 @@ import java.util.Set;
import org.apache.openjpa.conf.OpenJPAConfiguration;
import org.apache.openjpa.lib.log.Log;
import org.apache.openjpa.lib.util.BytecodeWriter;
import org.apache.openjpa.lib.util.Files;
import org.apache.openjpa.lib.util.JavaVersions;
import org.apache.openjpa.lib.util.Localizer;
import org.apache.openjpa.lib.util.Files;
import org.apache.openjpa.lib.util.Localizer.Message;
import org.apache.openjpa.meta.AccessCode;
import org.apache.openjpa.meta.ClassMetaData;
@ -45,7 +46,6 @@ import org.apache.openjpa.util.ImplHelper;
import org.apache.openjpa.util.InternalException;
import org.apache.openjpa.util.MetaDataException;
import org.apache.openjpa.util.UserException;
import serp.bytecode.BCClass;
/**
@ -80,7 +80,8 @@ public class ManagedClassSubclasser {
*/
public static List<Class<?>> prepareUnenhancedClasses(
final OpenJPAConfiguration conf,
final Collection<? extends Class<?>> classes) {
final Collection<? extends Class<?>> classes,
final ClassLoader envLoader) {
if (classes == null)
return null;
if (classes.size() == 0)
@ -93,7 +94,7 @@ public class ManagedClassSubclasser {
if (!PersistenceCapable.class.isAssignableFrom(cls))
unenhanced.add(cls);
if (unenhanced.size() > 0) {
if (PCEnhancerAgent.getLoadSuccessful()) {
if (PCEnhancerAgent.getLoadSuccessful() == true) {
// This means that the enhancer has been ran but we
// have some unenhanced classes. This can happen if an
// entity is loaded by the JVM before the EntityManger
@ -118,7 +119,7 @@ public class ManagedClassSubclasser {
return null;
}
boolean redefine = ClassRedefiner.canRedefineClasses(conf);
boolean redefine = ClassRedefiner.canRedefineClasses(log);
if (redefine) {
log.info(_loc.get("enhance-and-subclass-and-redef-start", classes));
} else {
@ -175,13 +176,13 @@ public class ManagedClassSubclasser {
ClassRedefiner.redefineClasses(conf, map);
for (Class<?> cls : map.keySet()) {
setIntercepting(conf, cls);
configureMetaData(conf, cls, redefine);
setIntercepting(conf, envLoader, cls);
configureMetaData(conf, envLoader, cls, redefine);
}
for (Class<?> cls : subs)
configureMetaData(conf, cls, redefine);
configureMetaData(conf, envLoader, cls, redefine);
for (Class<?> cls : ints)
setIntercepting(conf, cls);
setIntercepting(conf, envLoader, cls);
return subs;
}
@ -223,8 +224,9 @@ public class ManagedClassSubclasser {
}
private static void configureMetaData(OpenJPAConfiguration conf,
Class<?> cls, boolean redefineAvailable) {
ClassMetaData meta = conf.getMetaDataRepositoryInstance().getMetaData(cls, true);
ClassLoader envLoader, Class<?> cls, boolean redefineAvailable) {
ClassMetaData meta = conf.getMetaDataRepositoryInstance()
.getMetaData(cls, envLoader, true);
configureMetaData(meta, conf, redefineAvailable, true);
}
@ -304,9 +306,10 @@ public class ManagedClassSubclasser {
}
}
private static void setIntercepting(OpenJPAConfiguration conf, Class<?> cls) {
private static void setIntercepting(OpenJPAConfiguration conf,
ClassLoader envLoader, Class<?> cls) {
ClassMetaData meta = conf.getMetaDataRepositoryInstance()
.getMetaData(cls, true);
.getMetaData(cls, envLoader, true);
meta.setIntercepting(true);
}

View File

@ -43,15 +43,16 @@ import serp.bytecode.lowlevel.ConstantPoolTable;
public class PCClassFileTransformer
implements ClassFileTransformer {
private static final Localizer _loc = Localizer.forPackage(PCClassFileTransformer.class);
private static final Localizer _loc = Localizer.forPackage
(PCClassFileTransformer.class);
private final MetaDataRepository _repos;
private final PCEnhancer.Flags _flags;
private final ClassLoader _tmpLoader;
private final Log _log;
private final Set<String> _names;
private final Set _names;
private boolean _transforming = false;
private static final String PERSISTENCE_CAPABLE = "org/apache/openjpa/enhance/PersistenceCapable";
/**
* Constructor.
*
@ -93,20 +94,17 @@ public class PCClassFileTransformer
_repos = repos;
_tmpLoader = tmpLoader;
_log = repos.getConfiguration().getLog(OpenJPAConfiguration.LOG_ENHANCE);
_log = repos.getConfiguration().
getLog(OpenJPAConfiguration.LOG_ENHANCE);
_flags = flags;
repos.getConfiguration().addClassLoader(tmpLoader);
_names = repos.getPersistentTypeNames(devscan);
_names = repos.getPersistentTypeNames(devscan, tmpLoader);
if (_names == null && _log.isInfoEnabled())
_log.info(_loc.get("runtime-enhance-pcclasses"));
}
/**
* The hook to transform byte code as they are loaded in Java Virtual Machine.
*
*/
public byte[] transform(ClassLoader loader, String className,
Class<?> redef, ProtectionDomain domain, byte[] bytes)
Class redef, ProtectionDomain domain, byte[] bytes)
throws IllegalClassFormatException {
if (loader == _tmpLoader)
return null;
@ -131,27 +129,29 @@ public class PCClassFileTransformer
* ClassCircularityError when executing method using pure-JIT JVMs
* such as JRockit.
*/
private byte[] transform0(String className, Class<?> redef, byte[] bytes)
private byte[] transform0(String className, Class redef, byte[] bytes)
throws IllegalClassFormatException {
byte[] returnBytes = null;
try {
Boolean enhance = needsEnhance(className, redef, bytes);
if (enhance != null && _log.isTraceEnabled()) {
_log.trace(_loc.get("needs-runtime-enhance", className, enhance));
}
if (enhance != Boolean.TRUE) {
if (enhance != null && _log.isTraceEnabled())
_log.trace(_loc.get("needs-runtime-enhance", className,
enhance));
if (enhance != Boolean.TRUE)
return null;
}
PCEnhancer enhancer = new PCEnhancer(_repos.getConfiguration(),
new Project().loadClass(new ByteArrayInputStream(bytes), _tmpLoader), _repos);
new Project().loadClass(new ByteArrayInputStream(bytes),
_tmpLoader), _repos);
enhancer.setAddDefaultConstructor(_flags.addDefaultConstructor);
enhancer.setEnforcePropertyRestrictions(_flags.enforcePropertyRestrictions);
enhancer.setEnforcePropertyRestrictions
(_flags.enforcePropertyRestrictions);
if (enhancer.run() == PCEnhancer.ENHANCE_NONE) {
if (enhancer.run() == PCEnhancer.ENHANCE_NONE)
return null;
}
return enhancer.getPCBytecode().toByteArray();
returnBytes = enhancer.getPCBytecode().toByteArray();
return returnBytes;
} catch (Throwable t) {
_log.warn(_loc.get("cft-exception-thrown", className), t);
if (t instanceof RuntimeException)
@ -161,38 +161,40 @@ public class PCClassFileTransformer
throw new GeneralException(t);
} finally {
_transforming = false;
if (returnBytes != null && _log.isTraceEnabled())
_log.trace(_loc.get("runtime-enhance-complete", className,
bytes.length, returnBytes.length));
}
}
/**
* Return whether the given class needs enhancement.
*/
private Boolean needsEnhance(String clsName, Class<?> redef, byte[] bytes) {
private Boolean needsEnhance(String clsName, Class redef, byte[] bytes) {
if (redef != null) {
Class<?>[] intfs = redef.getInterfaces();
for (int i = 0; i < intfs.length; i++) {
if (PersistenceCapable.class.getName().equals(intfs[i].getName())) {
return !isEnhanced(bytes);
}
}
Class[] intfs = redef.getInterfaces();
for (int i = 0; i < intfs.length; i++)
if (PersistenceCapable.class.getName().
equals(intfs[i].getName()))
return Boolean.valueOf(!isEnhanced(bytes));
return null;
}
if (_names != null) {
if (_names.contains(clsName.replace('/', '.')))
return !isEnhanced(bytes);
return Boolean.valueOf(!isEnhanced(bytes));
return null;
}
if (clsName.startsWith("java/") || clsName.startsWith("javax/")) {
if (clsName.startsWith("java/") || clsName.startsWith("javax/"))
return null;
}
if (isEnhanced(bytes))
return Boolean.FALSE;
try {
Class<?> c = Class.forName(clsName.replace('/', '.'), false, _tmpLoader);
if (_repos.getMetaData(c, false) != null)
Class c = Class.forName(clsName.replace('/', '.'), false,
_tmpLoader);
if (_repos.getMetaData(c, null, false) != null)
return Boolean.TRUE;
return null;
} catch (ClassNotFoundException cnfe) {
@ -227,7 +229,7 @@ public class PCClassFileTransformer
clsEntry = table.readUnsignedShort(idx);
utfEntry = table.readUnsignedShort(table.get(clsEntry));
name = table.readString(table.get(utfEntry));
if (PERSISTENCE_CAPABLE.equals(name))
if ("org/apache/openjpa/enhance/PersistenceCapable".equals(name))
return true;
}
return false;

View File

@ -249,14 +249,18 @@ public class PCEnhancer {
* @deprecated use {@link #PCEnhancer(OpenJPAConfiguration, BCClass,
MetaDataRepository, ClassLoader)} instead.
*/
public PCEnhancer(OpenJPAConfiguration conf, BCClass type,
MetaDataRepository repos) {
this(conf, type, repos, null);
}
/**
* Constructor. Supply configuration.
*
* @param type the bytecode representation for the type to
* @param type the bytecode representation fo the type to
* enhance; this can be created from any stream or file
* @param repos a metadata repository to use for metadata access,
* or null to create a new repository; the repository
* or null to create a new reporitory; the repository
* from the given configuration isn't used by default
* because the configuration might be an
* implementation-specific subclass whose metadata
@ -264,7 +268,8 @@ public class PCEnhancer {
* @param loader the environment classloader to use for loading
* classes and resources.
*/
public PCEnhancer(OpenJPAConfiguration conf, BCClass type, MetaDataRepository repos) {
public PCEnhancer(OpenJPAConfiguration conf, BCClass type,
MetaDataRepository repos, ClassLoader loader) {
_managedType = type;
_pc = type;
@ -273,10 +278,9 @@ public class PCEnhancer {
if (repos == null) {
_repos = conf.newMetaDataRepositoryInstance();
_repos.setSourceMode(MetaDataRepository.MODE_META);
} else {
} else
_repos = repos;
}
_meta = _repos.getMetaData(type.getType(), false);
_meta = _repos.getMetaData(type.getType(), loader, false);
}
/**
@ -1128,7 +1132,7 @@ public class PCEnhancer {
if (_meta != null && _meta.getDescribedType().isInterface())
return _meta;
return _repos.getMetaData(f.getDeclaringClass(), false);
return _repos.getMetaData(f.getDeclaringClass(), null, false);
}
/**
@ -4682,18 +4686,22 @@ public class PCEnhancer {
PCEnhancer.class.getName() + "#bytecodeWriter");
Configurations.populateConfiguration(conf, opts);
return run(conf, args, flags, null, writer);
return run(conf, args, flags, null, writer, null);
}
/**
* Enhance the given classes.
*/
public static boolean run(OpenJPAConfiguration conf, String[] args,
Flags flags, MetaDataRepository repos, BytecodeWriter writer)
Flags flags, MetaDataRepository repos, BytecodeWriter writer,
ClassLoader loader)
throws IOException {
ClassLoader loader = conf.getClassLoader();
// if (flags.tmpClassLoader)
// loader = AccessController.doPrivileged(J2DoPrivHelper.newTemporaryClassLoaderAction(loader));
if (loader == null)
loader = conf.getClassResolverInstance().
getClassLoader(PCEnhancer.class, null);
if (flags.tmpClassLoader)
loader = AccessController.doPrivileged(J2DoPrivHelper
.newTemporaryClassLoaderAction(loader));
if (repos == null) {
repos = conf.newMetaDataRepositoryInstance();
@ -4704,7 +4712,7 @@ public class PCEnhancer {
Collection classes;
if (args == null || args.length == 0) {
log.info(_loc.get("running-all-classes"));
classes = repos.getPersistentTypeNames(true);
classes = repos.getPersistentTypeNames(true, loader);
if (classes == null) {
log.warn(_loc.get("no-class-to-enhance"));
return false;
@ -4714,9 +4722,8 @@ public class PCEnhancer {
getMetaDataFactory().newClassArgParser();
cap.setClassLoader(loader);
classes = new HashSet();
for (int i = 0; i < args.length; i++) {
for (int i = 0; i < args.length; i++)
classes.addAll(Arrays.asList(cap.parseTypes(args[i])));
}
}
Project project = new Project();
@ -4732,7 +4739,7 @@ public class PCEnhancer {
bc = project.loadClass((String) o, loader);
else
bc = project.loadClass((Class) o);
enhancer = new PCEnhancer(conf, bc, repos);
enhancer = new PCEnhancer(conf, bc, repos, loader);
if (writer != null)
enhancer.setBytecodeWriter(writer);
enhancer.setDirectory(flags.directory);

View File

@ -74,38 +74,38 @@ public class PCEnhancerAgent {
private static boolean disableDynamicAgent = false;
/**
* Affirms if the Agent has ran successfully.
* @return True if the Agent has ran successfully. False otherwise.
*/
public static synchronized boolean getLoadSuccessful() {
return loadSuccessful;
}
/**
* disables dynamic agent.
* @return True if the dynamic agent was disabled via configuration.
*/
public static void disableDynamicAgent(){
disableDynamicAgent = true;
disableDynamicAgent=true;
}
/**
* @param configuration
* @param log
* @return True if the agent is loaded successfully
*/
public static synchronized boolean loadDynamicAgent(OpenJPAConfiguration conf) {
if (loadAttempted || disableDynamicAgent) {
return false;
public static synchronized boolean loadDynamicAgent(Log log) {
if (loadAttempted == false && disableDynamicAgent == false) {
Instrumentation inst =
InstrumentationFactory.getInstrumentation(log);
if (inst != null) {
premain("", inst);
return true;
}
// If we successfully get the Instrumentation, we will call premain
// where loadAttempted will be set to true. This case is the path
// where we were unable to get Instrumentation so we need to set the
// loadAttempted flag to true. We do this so we will only run
// through this code one time.
loadAttempted = true;
}
Instrumentation inst = InstrumentationFactory.getInstrumentation(conf);
if (inst != null) {
premain("", inst);
return true;
}
// If we successfully get the Instrumentation, we will call premain
// where loadAttempted will be set to true. This case is the path
// where we were unable to get Instrumentation so we need to set the
// loadAttempted flag to true. We do this so we will only run
// through this code one time.
loadAttempted = true;
return false;
}
@ -116,7 +116,7 @@ public class PCEnhancerAgent {
// The agent will be disabled when running in an application
// server.
synchronized (PCEnhancerAgent.class) {
if (loadAttempted) {
if (loadAttempted == true) {
return;
}
// See the comment in loadDynamicAgent as to why we set this to true
@ -128,11 +128,15 @@ public class PCEnhancerAgent {
if (opts.containsKey("ClassLoadEnhancement") ||
opts.containsKey("classLoadEnhancement")) {
if (opts.getBooleanProperty("ClassLoadEnhancement", "classLoadEnhancement", true))
if (opts.getBooleanProperty(
"ClassLoadEnhancement", "classLoadEnhancement", true))
registerClassLoadEnhancer(inst, opts);
} else if (opts.containsKey("RuntimeEnhancement") || opts.containsKey("runtimeEnhancement")) {
}
else if (opts.containsKey("RuntimeEnhancement") ||
opts.containsKey("runtimeEnhancement")) {
// Deprecated property setting
if (opts.getBooleanProperty("RuntimeEnhancement", "runtimeEnhancement", true))
if (opts.getBooleanProperty(
"RuntimeEnhancement", "runtimeEnhancement", true))
registerClassLoadEnhancer(inst, opts);
} else {
// if neither is set, then we should be turning it on. We need this
@ -141,7 +145,8 @@ public class PCEnhancerAgent {
registerClassLoadEnhancer(inst, opts);
}
if (opts.getBooleanProperty("RuntimeRedefinition", "runtimeRedefinition", true)) {
if (opts.getBooleanProperty(
"RuntimeRedefinition", "runtimeRedefinition", true)) {
InstrumentationFactory.setInstrumentation(inst);
} else {
InstrumentationFactory.setDynamicallyInstallAgent(false);
@ -149,8 +154,10 @@ public class PCEnhancerAgent {
loadSuccessful = true;
}
private static void registerClassLoadEnhancer(Instrumentation inst, Options opts) {
List<String> anchors = Configurations.getFullyQualifiedAnchorsInPropertiesLocation(opts);
private static void registerClassLoadEnhancer(Instrumentation inst,
Options opts) {
List<String> anchors = Configurations.
getFullyQualifiedAnchorsInPropertiesLocation(opts);
for (String a : anchors) {
Options clonedOptions = (Options) opts.clone();
clonedOptions.setProperty("properties", a);
@ -168,7 +175,12 @@ public class PCEnhancerAgent {
.newTemporaryClassLoaderAction(AccessController
.doPrivileged(J2DoPrivHelper.getContextClassLoaderAction())
));
conf.addClassLoader(tmpLoader);
conf.setClassResolver(new ClassResolver() {
public ClassLoader getClassLoader(Class context,
ClassLoader env) {
return tmpLoader;
}
});
conf.setReadOnly(Configuration.INIT_STATE_FREEZING);
conf.instantiateAll(); // avoid threading issues

View File

@ -64,7 +64,7 @@ public class ReflectingPersistenceCapable
Class type = o.getClass();
pcSubclassInstance = PCRegistry.newInstance(type, null, false);
meta = conf.getMetaDataRepositoryInstance()
.getMetaData(type, true);
.getMetaData(type, null, true);
}
public int pcGetEnhancementContractVersion() {

View File

@ -38,7 +38,7 @@ public interface InstrumentationManager extends Closeable {
* @param conf the configuration to use for initialization
* @param providers one or more providers as supplied via plugin list value
*/
public void initialize(OpenJPAConfiguration conf, PluginListValue<InstrumentationProvider> providers);
public void initialize(OpenJPAConfiguration conf, PluginListValue providers);
/**
* Manage a given provider. This will plug the instruments managed by the

View File

@ -43,8 +43,9 @@ public class InstrumentationManagerImpl implements InstrumentationManager {
* @param conf
* @param providers
*/
public void initialize(OpenJPAConfiguration conf, PluginListValue<InstrumentationProvider> pluginVal) {
InstrumentationProvider[] providers = pluginVal.instantiate(conf);
public void initialize(OpenJPAConfiguration conf, PluginListValue pluginVal) {
InstrumentationProvider[] providers =
(InstrumentationProvider[])pluginVal.instantiate(InstrumentationProvider.class, conf);
_providers.addAll(Arrays.asList(providers));
}

View File

@ -19,6 +19,7 @@
package org.apache.openjpa.kernel;
import java.io.ObjectStreamException;
import java.security.AccessController;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
@ -39,6 +40,7 @@ import javax.transaction.TransactionManager;
import org.apache.commons.collections.set.MapBackedSet;
import org.apache.commons.lang.StringUtils;
import org.apache.openjpa.kernel.AuditManager;
import org.apache.openjpa.audit.Auditor;
import org.apache.openjpa.conf.BrokerValue;
import org.apache.openjpa.conf.OpenJPAConfiguration;
@ -103,7 +105,7 @@ public abstract class AbstractBrokerFactory
// cache the class names loaded from the persistent classes property so
// that we can re-load them for each new broker
private transient Collection<String> _pcClassNames = null;
// private transient Collection<ClassLoader> _pcClassLoaders = null;
private transient Collection<ClassLoader> _pcClassLoaders = null;
private transient boolean _persistentTypesLoaded = false;
// lifecycle listeners to pass to each broker
@ -153,6 +155,7 @@ public abstract class AbstractBrokerFactory
protected AbstractBrokerFactory(OpenJPAConfiguration config) {
_conf = config;
_brokers = newBrokerSet();
getPcClassLoaders();
}
/**
@ -232,7 +235,7 @@ public abstract class AbstractBrokerFactory
if (remote.areRemoteEventsEnabled())
broker.addTransactionListener(remote);
loadPersistentTypes();
loadPersistentTypes(broker.getClassLoader());
_brokers.add(broker);
_conf.setReadOnly(Configuration.INIT_STATE_FROZEN);
}
@ -259,7 +262,7 @@ public abstract class AbstractBrokerFactory
* Load the configured persistent classes list. Performed automatically
* whenever a broker is created.
*/
public void loadPersistentTypes() {
public void loadPersistentTypes(ClassLoader envLoader) {
// if we've loaded the persistent types and the class name list
// is empty, then we can simply return. Note that there is a
// potential threading scenario in which _persistentTypesLoaded is
@ -272,11 +275,12 @@ public abstract class AbstractBrokerFactory
return;
// cache persistent type names if not already
ClassLoader loader = _conf.getClassLoader();
ClassLoader loader = _conf.getClassResolverInstance().
getClassLoader(getClass(), envLoader);
Collection<Class<?>> toRedefine = new ArrayList<Class<?>>();
if (!_persistentTypesLoaded) {
Collection<Class<?>> clss = _conf.getMetaDataRepositoryInstance().
loadPersistentTypes(false, _conf.isInitializeEagerly());
loadPersistentTypes(false, loader, _conf.isInitializeEagerly());
if (clss.isEmpty())
_pcClassNames = Collections.emptyList();
else {
@ -287,27 +291,27 @@ public abstract class AbstractBrokerFactory
if (needsSub(cls))
toRedefine.add(cls);
}
// getPcClassLoaders().add(loader);
getPcClassLoaders().add(loader);
_pcClassNames = c;
}
_persistentTypesLoaded = true;
} else {
// reload with this loader
// if (getPcClassLoaders().add(loader)) {
// for (String clsName : _pcClassNames) {
// try {
// Class<?> cls = Class.forName(clsName, true, loader);
// if (needsSub(cls))
// toRedefine.add(cls);
// } catch (Throwable t) {
// _conf.getLog(OpenJPAConfiguration.LOG_RUNTIME).warn(null, t);
// }
// }
// }
if (getPcClassLoaders().add(loader)) {
for (String clsName : _pcClassNames) {
try {
Class<?> cls = Class.forName(clsName, true, loader);
if (needsSub(cls))
toRedefine.add(cls);
} catch (Throwable t) {
_conf.getLog(OpenJPAConfiguration.LOG_RUNTIME).warn(null, t);
}
}
}
}
// get the ManagedClassSubclasser into the loop
ManagedClassSubclasser.prepareUnenhancedClasses(_conf, toRedefine);
ManagedClassSubclasser.prepareUnenhancedClasses(_conf, toRedefine, envLoader);
}
private boolean needsSub(Class<?> cls) {
@ -809,12 +813,12 @@ public abstract class AbstractBrokerFactory
/**
* Method insures that deserialized EMF has this reference re-instantiated
*/
// private Collection<ClassLoader> getPcClassLoaders() {
// if (_pcClassLoaders == null)
// _pcClassLoaders = new ConcurrentReferenceHashSet<ClassLoader>(ConcurrentReferenceHashSet.WEAK);
//
// return _pcClassLoaders;
// }
private Collection<ClassLoader> getPcClassLoaders() {
if (_pcClassLoaders == null)
_pcClassLoaders = new ConcurrentReferenceHashSet<ClassLoader>(ConcurrentReferenceHashSet.WEAK);
return _pcClassLoaders;
}
/**
* <P>
@ -857,13 +861,14 @@ public abstract class AbstractBrokerFactory
}
// Don't catch any exceptions here because we want to fail-fast if something bad happens when we're preloading.
Options o = Configurations.parseProperties(Configurations.getProperties(_conf.getMetaDataRepository()));
if (MetaDataRepository.needsPreload(o)) {
if (MetaDataRepository.needsPreload(o) == true) {
MetaDataRepository mdr = _conf.getMetaDataRepositoryInstance();
mdr.setValidate(MetaDataRepository.VALIDATE_RUNTIME, true);
mdr.setResolve(MetaDataRepository.MODE_MAPPING_INIT, true);
// Load persistent classes and hook in subclasser
loadPersistentTypes();
loadPersistentTypes((ClassLoader) AccessController.doPrivileged(J2DoPrivHelper
.getContextClassLoaderAction()));
mdr.preload();
}

View File

@ -62,10 +62,13 @@ public abstract class AbstractPCResultObjectProvider
load(sm, fetch);
}
public Object getResultObject() throws Exception {
Class<?> type = getPCType();
MetaDataRepository repos = ctx.getConfiguration().getMetaDataRepositoryInstance();
ClassMetaData meta = repos.getMetaData(type, true);
public Object getResultObject()
throws Exception {
Class type = getPCType();
MetaDataRepository repos = ctx.getConfiguration().
getMetaDataRepositoryInstance();
ClassMetaData meta = repos.getMetaData
(type, ctx.getClassLoader(), true);
Object oid = getObjectId(meta);
Object res = ctx.find(oid, null, null, this, 0);
@ -78,25 +81,30 @@ public abstract class AbstractPCResultObjectProvider
* Implement this method to extract the object id value from the
* current record of the input.
*/
protected abstract Object getObjectId(ClassMetaData meta) throws Exception;
protected abstract Object getObjectId(ClassMetaData meta)
throws Exception;
/**
* Implement this method to extract the type of the pc stored
* in the current record of the input.
*/
protected abstract Class<?> getPCType() throws Exception;
protected abstract Class getPCType()
throws Exception;
/**
* Load data from the current input record into the given state
* manager. Remember to call {@link OpenJPAStateManager#setVersion} to set
* the optimistic versioning information, if it has any.
*/
protected abstract void load(OpenJPAStateManager sm, FetchConfiguration fetch) throws Exception;
protected abstract void load(OpenJPAStateManager sm,
FetchConfiguration fetch)
throws Exception;
/**
* Override if desired. Does nothing by default.
*/
public void open() throws Exception {
public void open()
throws Exception {
}
/**
@ -113,14 +121,16 @@ public abstract class AbstractPCResultObjectProvider
*
* @see ResultObjectProvider#next
*/
public abstract boolean next() throws Exception;
public abstract boolean next()
throws Exception;
/**
* Override if desired. Throws an exception by default.
*
* @see ResultObjectProvider#absolute
*/
public boolean absolute(int pos) throws Exception {
public boolean absolute(int pos)
throws Exception {
throw new UnsupportedOperationException();
}
@ -129,7 +139,8 @@ public abstract class AbstractPCResultObjectProvider
*
* @see ResultObjectProvider#size
*/
public int size() throws Exception {
public int size()
throws Exception {
return Integer.MAX_VALUE;
}
@ -138,7 +149,8 @@ public abstract class AbstractPCResultObjectProvider
*
* @see ResultObjectProvider#reset
*/
public void reset() throws Exception {
public void reset()
throws Exception {
throw new UnsupportedOperationException();
}
@ -147,7 +159,8 @@ public abstract class AbstractPCResultObjectProvider
*
* @see ResultObjectProvider#close
*/
public void close() throws Exception {
public void close()
throws Exception {
}
/**

View File

@ -247,7 +247,8 @@ public class AttachManager {
//### need to handle ACT_RUN without also ACT_CASCADE
ClassMetaData meta = _broker.getConfiguration().
getMetaDataRepositoryInstance().getMetaData(
ImplHelper.getManagedInstance(toAttach).getClass(), true);
ImplHelper.getManagedInstance(toAttach).getClass(),
_broker.getClassLoader(), true);
return getStrategy(toAttach).attach(this, toAttach, meta, into,
owner, ownerMeta, explicit);
}

View File

@ -39,7 +39,11 @@ import org.apache.openjpa.util.UserException;
*/
public class Bootstrap {
private static final Class<?>[] CONFIGURATION_ARG = { ConfigurationProvider.class };
private static final Class<?>[] CONFIGURATION_ARG =
new Class<?>[]{ ConfigurationProvider.class };
private static final Class<?>[] CONFIGURATION_CLASSLOADER_ARGS =
new Class<?>[] { ConfigurationProvider.class, ClassLoader.class };
private static Localizer s_loc = Localizer.forPackage(Bootstrap.class);
@ -47,24 +51,30 @@ public class Bootstrap {
* Return a new factory for the default configuration.
*/
public static BrokerFactory newBrokerFactory() {
return Bootstrap.newBrokerFactory(null);
return Bootstrap.newBrokerFactory(null, null);
}
/**
* Return a new factory for the given configuration.
* Return a new factory for the given configuration. The classloader
* will be used to load the factory class. If no classloader is given,
* the thread's context classloader is used.
*/
public static BrokerFactory newBrokerFactory(ConfigurationProvider conf) {
public static BrokerFactory newBrokerFactory(ConfigurationProvider conf,
ClassLoader loader) {
try {
BrokerFactory factory = invokeFactory(conf, "newInstance", CONFIGURATION_ARG, new Object[] { conf });
BrokerFactory factory =
invokeFactory(conf, loader, "newInstance", CONFIGURATION_ARG, new Object[] { conf });
factory.postCreationCallback();
return factory;
} catch (InvocationTargetException ite) {
Throwable cause = ite.getTargetException();
if (cause instanceof OpenJPAException)
throw (OpenJPAException) cause;
throw new InternalException(s_loc.get("new-brokerfactory-excep", getFactoryClassName(conf), cause));
throw new InternalException(s_loc.get("new-brokerfactory-excep",
getFactoryClassName(conf, loader)), cause);
} catch (Exception e) {
throw new UserException(s_loc.get("bad-new-brokerfactory", getFactoryClassName(conf)), e).setFatal(true);
throw new UserException(s_loc.get("bad-new-brokerfactory",
getFactoryClassName(conf, loader)), e).setFatal(true);
}
}
@ -72,41 +82,59 @@ public class Bootstrap {
* Return a pooled factory for the default configuration.
*/
public static BrokerFactory getBrokerFactory() {
return Bootstrap.getBrokerFactory(null);
return Bootstrap.getBrokerFactory(null, null);
}
/**
* Return a pooled factory for the given configuration.
* Return a pooled factory for the given configuration. The classloader
* will be used to load the factory class. If no classloader is given,
* the thread's context classloader is used.
*/
public static BrokerFactory getBrokerFactory(ConfigurationProvider conf) {
public static BrokerFactory getBrokerFactory(ConfigurationProvider conf,
ClassLoader loader) {
try {
return invokeFactory(conf, "getInstance", CONFIGURATION_ARG, new Object[] { conf});
return invokeFactory(conf, loader, "getInstance", CONFIGURATION_CLASSLOADER_ARGS, new Object[] { conf,
loader });
} catch (InvocationTargetException ite) {
Throwable cause = ite.getTargetException();
if (cause instanceof OpenJPAException)
throw (OpenJPAException) cause;
throw new InternalException(s_loc.get("brokerfactory-excep", getFactoryClassName(conf)), cause);
throw new InternalException(s_loc.get("brokerfactory-excep",
getFactoryClassName(conf, loader)), cause);
} catch (Exception e) {
throw new UserException(s_loc.get("bad-brokerfactory", getFactoryClassName(conf)), e).setFatal(true);
throw new UserException(s_loc.get("bad-brokerfactory",
getFactoryClassName(conf, loader)), e).setFatal(true);
}
}
private static BrokerFactory invokeFactory(ConfigurationProvider conf, String methodName,
Class<?>[] argTypes, Object[] args)
throws InvocationTargetException, NoSuchMethodException, IllegalAccessException {
private static BrokerFactory invokeFactory(ConfigurationProvider conf,
ClassLoader loader, String methodName, Class<?>[] argTypes, Object[] args)
throws InvocationTargetException, NoSuchMethodException,
IllegalAccessException {
if (conf == null)
conf = new MapConfigurationProvider();
ProductDerivations.beforeConfigurationConstruct(conf);
Class<?> cls = getFactoryClass(conf);
Method meth = cls.getMethod(methodName, argTypes);
Class cls = getFactoryClass(conf, loader);
Method meth;
try {
meth = cls.getMethod(methodName, argTypes);
} catch (NoSuchMethodException nsme) {
// handle cases where there is a mismatch between loaders by falling
// back to the configuration's class loader for broker resolution
cls = getFactoryClass(conf,
AccessController.doPrivileged(
J2DoPrivHelper.getClassLoaderAction(conf.getClass())));
meth = cls.getMethod(methodName, argTypes);
}
return (BrokerFactory) meth.invoke(null, args);
}
private static String getFactoryClassName(ConfigurationProvider conf) {
private static String getFactoryClassName(ConfigurationProvider conf,
ClassLoader loader) {
try {
return getFactoryClass(conf).getName();
return getFactoryClass(conf, loader).getName();
} catch (Exception e) {
return "<" + e.toString() + ">";
}
@ -115,21 +143,28 @@ public class Bootstrap {
/**
* Instantiate the factory class designated in properties.
*/
private static Class<?> getFactoryClass(ConfigurationProvider conf) {
private static Class getFactoryClass(ConfigurationProvider conf,
ClassLoader loader) {
if (loader == null)
loader = AccessController.doPrivileged(
J2DoPrivHelper.getContextClassLoaderAction());
Object cls = BrokerFactoryValue.get(conf);
if (cls instanceof Class)
return (Class<?>) cls;
return (Class) cls;
BrokerFactoryValue value = new BrokerFactoryValue();
value.setString((String) cls);
String clsName = value.getClassName();
if (clsName == null)
throw new UserException(s_loc.get("no-brokerfactory", conf.getProperties())).setFatal(true);
throw new UserException(s_loc.get("no-brokerfactory",
conf.getProperties())).setFatal(true);
try {
return Class.forName(clsName, true, conf.getClassLoader());
return Class.forName(clsName, true, loader);
} catch (Exception e) {
throw new UserException(s_loc.get("bad-brokerfactory-class", clsName), e).setFatal(true);
throw new UserException(s_loc.get("bad-brokerfactory-class",
clsName), e).setFatal(true);
}
}
}

View File

@ -53,7 +53,8 @@ public interface Broker
* after the first invocation with non-null arguments,
* subsequent invocations of this method are ignored.
*/
public void setImplicitBehavior(OpCallbacks call, RuntimeExceptionTranslator ex);
public void setImplicitBehavior(OpCallbacks call,
RuntimeExceptionTranslator ex);
/**
* Return the factory that produced this broker.
@ -287,7 +288,7 @@ public interface Broker
*
* @since 0.3.3
*/
public void addLifecycleListener(Object listener, Class<?>[] classes);
public void addLifecycleListener(Object listener, Class[] classes);
/**
* Remove a listener for lifecycle-related events.
@ -468,7 +469,7 @@ public interface Broker
/**
* Persist the given objects.
*/
public void persistAll(Collection<?> objs, OpCallbacks call);
public void persistAll(Collection objs, OpCallbacks call);
/**
* Make the given instance persistent. Unlike other persist operations,
@ -489,7 +490,7 @@ public interface Broker
/**
* Delete the given objects.
*/
public void deleteAll(Collection<?> objs, OpCallbacks call);
public void deleteAll(Collection objs, OpCallbacks call);
/**
* Release the given object from management. This operation is not
@ -501,7 +502,7 @@ public interface Broker
* Release the given objects from management. This operation is not
* recursive.
*/
public void releaseAll(Collection<?> objs, OpCallbacks call);
public void releaseAll(Collection objs, OpCallbacks call);
/**
* Refresh the state of the given object.
@ -511,7 +512,7 @@ public interface Broker
/**
* Refresh the state of the given objects.
*/
public void refreshAll(Collection<?> objs, OpCallbacks call);
public void refreshAll(Collection objs, OpCallbacks call);
/**
* Evict the given object.
@ -521,7 +522,7 @@ public interface Broker
/**
* Evict the given objects.
*/
public void evictAll(Collection<?> objs, OpCallbacks call);
public void evictAll(Collection objs, OpCallbacks call);
/**
* Evict all clean objects.
@ -532,7 +533,7 @@ public interface Broker
* Evict all persistent-clean and persistent-nontransactional
* instances in the given {@link Extent}.
*/
public void evictAll(Extent<?> extent, OpCallbacks call);
public void evictAll(Extent extent, OpCallbacks call);
/**
* Detach all objects in place. A flush will be performed before
@ -572,7 +573,7 @@ public interface Broker
* @param objs the instances to detach
* @return the detached instances
*/
public Object[] detachAll(Collection<?> objs, OpCallbacks call);
public Object[] detachAll(Collection objs, OpCallbacks call);
/**
* Import the specified detached object into the broker.
@ -593,7 +594,8 @@ public interface Broker
* @return the re-attached instances
* @param copyNew whether to copy new instances
*/
public Object[] attachAll(Collection<?> objs, boolean copyNew, OpCallbacks call);
public Object[] attachAll(Collection objs, boolean copyNew,
OpCallbacks call);
/**
* Create a new instance of type <code>cls</code>. If <code>cls</code> is
@ -606,7 +608,7 @@ public interface Broker
* @throws IllegalArgumentException if <code>cls</code> is not a managed
* type or interface.
*/
public Object newInstance(Class<?> cls);
public Object newInstance(Class cls);
/**
* Returns <code>true</code> if <code>obj</code> is a detached object
@ -618,13 +620,13 @@ public interface Broker
/**
* Return an extent of the given class, optionally including subclasses.
*/
public <T> Extent<T> newExtent(Class<T> cls, boolean subs);
public Extent newExtent(Class cls, boolean subs);
/**
* Create a new query from the given data, with the given candidate class
* and language.
*/
public Query newQuery(String language, Class<?> cls, Object query);
public Query newQuery(String language, Class cls, Object query);
/**
* Create a new query in the given language.
@ -672,7 +674,8 @@ public interface Broker
* giving up, or -1 for no limit
* @since 0.3.1
*/
public void lockAll(Collection<?> objs, int level, int timeout, OpCallbacks call);
public void lockAll(Collection objs, int level, int timeout,
OpCallbacks call);
/**
* Ensure that the given instances are locked at the current lock level, as
@ -680,7 +683,7 @@ public interface Broker
*
* @since 0.3.1
*/
public void lockAll(Collection<?> objs, OpCallbacks call);
public void lockAll(Collection objs, OpCallbacks call);
/**
* Cancel all pending data store statements. If statements are cancelled
@ -697,7 +700,7 @@ public interface Broker
*
* @since 0.3.0
*/
public void dirtyType(Class<?> cls);
public void dirtyType(Class cls);
/**
* Begin a logical operation. This indicates to the broker the

View File

@ -180,6 +180,9 @@ public class BrokerImpl
private transient OpenJPAConfiguration _conf = null;
private transient MetaDataRepository _repo = null;
// cache class loader associated with the broker
private transient ClassLoader _loader = null;
// user state
private Synchronization _sync = null;
private Map<Object, Object> _userObjects = null;
@ -326,6 +329,8 @@ public class BrokerImpl
boolean fromDeserialization, boolean fromWriteBehindCallback) {
_fromWriteBehindCallback = fromWriteBehindCallback;
_initializeWasInvoked = true;
_loader = AccessController.doPrivileged(
J2DoPrivHelper.getContextClassLoaderAction());
if (!fromDeserialization){
_conf = factory.getConfiguration();
_repo = _conf.getMetaDataRepositoryInstance();
@ -482,6 +487,10 @@ public class BrokerImpl
return _runtime;
}
public ClassLoader getClassLoader() {
return _loader;
}
public DelegatingStoreManager getStoreManager() {
return _store;
}
@ -735,7 +744,7 @@ public class BrokerImpl
// Events
// ////////
public void addLifecycleListener(Object listener, Class<?>[] classes) {
public void addLifecycleListener(Object listener, Class[] classes) {
beginOperation(false);
try {
_lifeEventManager.addListener(listener, classes);
@ -1032,22 +1041,23 @@ public class BrokerImpl
return sm;
}
public Object[] findAll(Collection<?> oids, boolean validate, FindCallbacks call) {
public Object[] findAll(Collection oids, boolean validate,
FindCallbacks call) {
int flags = OID_COPY | OID_ALLOW_NEW | OID_NODELETED;
if (!validate) {
if (!validate)
flags |= OID_NOVALIDATE;
}
return findAll(oids, _fc, null, null, flags, call);
}
public Object[] findAll(Collection<?> oids, FetchConfiguration fetch, BitSet exclude, Object edata, int flags) {
public Object[] findAll(Collection oids, FetchConfiguration fetch,
BitSet exclude, Object edata, int flags) {
return findAll(oids, fetch, exclude, edata, flags, null);
}
/**
* Internal finder.
*/
protected Object[] findAll(Collection<?> oids, FetchConfiguration fetch,
protected Object[] findAll(Collection oids, FetchConfiguration fetch,
BitSet exclude, Object edata, int flags, FindCallbacks call) {
findAllDepth ++;
@ -1110,8 +1120,10 @@ public class BrokerImpl
// pass all state managers in need of loading or validation to the
// store manager
if (load != null) {
PCState state = (transState) ? PCState.PCLEAN : PCState.PNONTRANS;
Collection<Object> failed = _store.loadAll(load, state, StoreManager.FORCE_LOAD_NONE, fetch, edata);
PCState state = (transState) ? PCState.PCLEAN
: PCState.PNONTRANS;
Collection<Object> failed = _store.loadAll(load, state,
StoreManager.FORCE_LOAD_NONE, fetch, edata);
// set failed instances to null
if (failed != null && !failed.isEmpty()) {
@ -1223,7 +1235,7 @@ public class BrokerImpl
beginOperation(false);
try {
ClassMetaData meta = _repo.getMetaData(cls, false);
ClassMetaData meta = _repo.getMetaData(cls, _loader, false);
if (meta == null
|| meta.getIdentityType() == ClassMetaData.ID_UNKNOWN)
return null;
@ -1246,7 +1258,7 @@ public class BrokerImpl
beginOperation(false);
try {
ClassMetaData meta = _repo.getMetaData(cls, true);
ClassMetaData meta = _repo.getMetaData(cls, _loader, true);
switch (meta.getIdentityType()) {
case ClassMetaData.ID_DATASTORE:
// delegate to store manager for datastore ids
@ -1308,9 +1320,9 @@ public class BrokerImpl
Class<?> pcType = _store.getManagedType(oid);
ClassMetaData meta;
if (pcType != null)
meta = _repo.getMetaData(pcType, true);
meta = _repo.getMetaData(pcType, _loader, true);
else
meta = _repo.getMetaData(oid, true);
meta = _repo.getMetaData(oid, _loader, true);
// copy the oid if needed
if (copy && _compat.getCopyObjectIds()) {
@ -2075,7 +2087,7 @@ public class BrokerImpl
protected void flush(int reason) {
// this will enlist proxied states as necessary so we know whether we
// have anything to flush
Collection<StateManagerImpl> transactional = getTransactionalStates();
Collection transactional = getTransactionalStates();
// do we actually have to flush? only if our flags say so, or if
// we have transaction listeners that need to be invoked for commit
@ -2090,14 +2102,13 @@ public class BrokerImpl
if (!flush && (reason != FLUSH_COMMIT || !listeners))
return;
ManagedObjectCollection mobjs = null;
Collection mobjs = null;
_flags |= FLAG_PRESTORING;
try {
if (flush) {
// call pre store on all currently transactional objs
for (StateManagerImpl sm : transactional) {
sm.beforeFlush(reason, _call);
}
for (Iterator itr = transactional.iterator(); itr.hasNext();)
((StateManagerImpl) itr.next()).beforeFlush(reason, _call);
flushAdditions(transactional, reason);
}
@ -2172,7 +2183,9 @@ public class BrokerImpl
// mark states as flushed
if (flush) {
for (StateManagerImpl sm : transactional) {
StateManagerImpl sm;
for (Iterator itr = transactional.iterator(); itr.hasNext();) {
sm = (StateManagerImpl) itr.next();
try {
// the state may have become transient, such as if
// it is embedded and the owner has been deleted during
@ -2210,7 +2223,7 @@ public class BrokerImpl
/**
* Flush newly-transactional objects.
*/
private void flushAdditions(Collection<StateManagerImpl> transactional, int reason) {
private void flushAdditions(Collection transactional, int reason) {
boolean loop;
do {
// flush new transactional instances; note logical or
@ -2222,7 +2235,7 @@ public class BrokerImpl
/**
* Flush transactional additions.
*/
private boolean flushTransAdditions(Collection<StateManagerImpl> transactional, int reason) {
private boolean flushTransAdditions(Collection transactional, int reason) {
if (_transAdditions == null || _transAdditions.isEmpty())
return false;
@ -2230,7 +2243,8 @@ public class BrokerImpl
transactional.addAll(_transAdditions);
// copy the change set, then clear it for the next iteration
StateManagerImpl[] states = _transAdditions.toArray(new StateManagerImpl[_transAdditions.size()]);
StateManagerImpl[] states = (StateManagerImpl[]) _transAdditions.
toArray(new StateManagerImpl[_transAdditions.size()]);
_transAdditions = null;
for (int i = 0; i < states.length; i++)
@ -2241,14 +2255,15 @@ public class BrokerImpl
/**
* Delete new dereferenced objects.
*/
private boolean deleteDerefAdditions(Collection<StateManagerImpl> derefs) {
private boolean deleteDerefAdditions(Collection derefs) {
if (_derefAdditions == null || _derefAdditions.isEmpty())
return false;
// remember these additions in case one becomes derefed again later
derefs.addAll(_derefAdditions);
StateManagerImpl[] states = _derefAdditions.toArray(new StateManagerImpl[_derefAdditions.size()]);
StateManagerImpl[] states = (StateManagerImpl[]) _derefAdditions.
toArray(new StateManagerImpl[_derefAdditions.size()]);
_derefAdditions = null;
for (int i = 0; i < states.length; i++)
@ -2260,7 +2275,8 @@ public class BrokerImpl
* Delete a dereferenced dependent.
*/
private void deleteDeref(StateManagerImpl sm) {
int action = processArgument(OpCallbacks.OP_DELETE, sm.getManagedInstance(), sm, null);
int action = processArgument(OpCallbacks.OP_DELETE,
sm.getManagedInstance(), sm, null);
if ((action & OpCallbacks.ACT_RUN) != 0)
sm.delete();
if ((action & OpCallbacks.ACT_CASCADE) != 0)
@ -2271,7 +2287,8 @@ public class BrokerImpl
* Determine the action to take based on the user's given callbacks and
* our implicit behavior.
*/
private int processArgument(int op, Object obj, OpenJPAStateManager sm, OpCallbacks call) {
private int processArgument(int op, Object obj, OpenJPAStateManager sm,
OpCallbacks call) {
if (call != null)
return call.processArgument(op, obj, sm);
if (_call != null)
@ -2341,15 +2358,14 @@ public class BrokerImpl
_fc.setWriteLockLevel(LOCK_NONE);
_fc.setLockTimeout(-1);
TransactionalCache transStates;
if (hasTransactionalObjects()) {
Collection transStates;
if (hasTransactionalObjects())
transStates = _transCache;
} else {
transStates = new TransactionalCache(true);
}
else
transStates = Collections.EMPTY_SET;
// fire after rollback/commit event
ManagedObjectCollection mobjs = null;
Collection mobjs = null;
if (_transEventManager.hasEndListeners()) {
mobjs = new ManagedObjectCollection(transStates);
int eventType = (rollback) ? TransactionEvent.AFTER_ROLLBACK
@ -2384,7 +2400,9 @@ public class BrokerImpl
}
// perform commit or rollback state transitions on each instance
for (StateManagerImpl sm : transStates) {
StateManagerImpl sm;
for (Iterator itr = transStates.iterator(); itr.hasNext();) {
sm = (StateManagerImpl) itr.next();
try {
if (rollback) {
// tell objects that may have been derefed then flushed
@ -2444,7 +2462,7 @@ public class BrokerImpl
return persist(obj, id, true, call);
}
public void persistAll(Collection<?> objs, OpCallbacks call) {
public void persistAll(Collection objs, OpCallbacks call) {
persistAll(objs, true, call);
}
@ -2452,7 +2470,7 @@ public class BrokerImpl
* Persist the given objects. Indicate whether this was an explicit persist
* (PNEW) or a provisonal persist (PNEWPROVISIONAL).
*/
public void persistAll(Collection<?> objs, boolean explicit,
public void persistAll(Collection objs, boolean explicit,
OpCallbacks call) {
if (objs.isEmpty())
return;
@ -2611,7 +2629,7 @@ public class BrokerImpl
}
}
ClassMetaData meta = _repo.getMetaData(obj.getClass(), true);
ClassMetaData meta = _repo.getMetaData(obj.getClass(), _loader, true);
if (fireEvent) {
fireLifecycleEvent(obj, null, meta, LifecycleEvent.BEFORE_PERSIST);
}
@ -2665,7 +2683,7 @@ public class BrokerImpl
if (pc.pcGetStateManager() != null)
throw newDetachedException(obj, errOp);
ClassMetaData meta = _repo.getMetaData(obj.getClass(), true);
ClassMetaData meta = _repo.getMetaData(obj.getClass(), _loader, true);
StateManagerImpl sm = newStateManagerImpl(StateManagerId.
newInstance(this), meta);
sm.initialize(pc, PCState.TLOADED);
@ -2689,7 +2707,7 @@ public class BrokerImpl
}
}
public void deleteAll(Collection<?> objs, OpCallbacks call) {
public void deleteAll(Collection objs, OpCallbacks call) {
beginOperation(true);
try {
assertWriteOperation();
@ -2786,7 +2804,7 @@ public class BrokerImpl
Exceptions.toString(obj))).setFailedObject(obj);
}
public void releaseAll(Collection<?> objs, OpCallbacks call) {
public void releaseAll(Collection objs, OpCallbacks call) {
beginOperation(false);
try {
List<Exception> exceps = null;
@ -2929,7 +2947,7 @@ public class BrokerImpl
if (sm == null) {
MetaDataRepository repos = _conf.
getMetaDataRepositoryInstance();
ClassMetaData meta = repos.getMetaData(type, true);
ClassMetaData meta = repos.getMetaData(type, _loader, true);
// construct a new state manager with all info known
sm = newStateManagerImpl(oid, meta);
sm.setObjectId(oid);
@ -2941,7 +2959,7 @@ public class BrokerImpl
}
}
public void refreshAll(Collection<?> objs, OpCallbacks call) {
public void refreshAll(Collection objs, OpCallbacks call) {
if (objs == null || objs.isEmpty())
return;
@ -3007,7 +3025,7 @@ public class BrokerImpl
* This method is called with the full set of objects reachable via
* cascade-refresh relations from the user-given instances.
*/
protected void refreshInternal(Collection<?> objs, OpCallbacks call) {
protected void refreshInternal(Collection objs, OpCallbacks call) {
if (objs == null || objs.isEmpty())
return;
List<Exception> exceps = null;
@ -3124,7 +3142,8 @@ public class BrokerImpl
}
public void retrieveAll(Collection<?> objs, boolean dfgOnly, OpCallbacks call) {
public void retrieveAll(Collection objs, boolean dfgOnly,
OpCallbacks call) {
if (objs == null || objs.isEmpty())
return;
if (objs.size() == 1) {
@ -3260,7 +3279,7 @@ public class BrokerImpl
}
}
public void evictAll(Collection<?> objs, OpCallbacks call) {
public void evictAll(Collection objs, OpCallbacks call) {
List<Exception> exceps = null;
beginOperation(false);
try {
@ -3277,7 +3296,7 @@ public class BrokerImpl
throwNestedExceptions(exceps, false);
}
public void evictAll(Extent<?> extent, OpCallbacks call) {
public void evictAll(Extent extent, OpCallbacks call) {
if (extent == null)
return;
@ -3349,7 +3368,7 @@ public class BrokerImpl
}
}
public Object[] detachAll(Collection<?> objs, OpCallbacks call) {
public Object[] detachAll(Collection objs, OpCallbacks call) {
if (objs == null)
return null;
if (objs.isEmpty())
@ -3466,7 +3485,8 @@ public class BrokerImpl
}
}
public Object[] attachAll(Collection<?> objs, boolean copyNew, OpCallbacks call) {
public Object[] attachAll(Collection objs, boolean copyNew,
OpCallbacks call) {
if (objs == null)
return null;
if (objs.isEmpty())
@ -3492,7 +3512,7 @@ public class BrokerImpl
}
}
public void nontransactionalAll(Collection<?> objs, OpCallbacks call) {
public void nontransactionalAll(Collection objs, OpCallbacks call) {
beginOperation(true);
try {
List<Exception> exceps = null;
@ -3533,7 +3553,7 @@ public class BrokerImpl
/**
* Make the given instances transactional.
*/
public void transactionalAll(Collection<?> objs, boolean updateVersion,
public void transactionalAll(Collection objs, boolean updateVersion,
OpCallbacks call) {
if (objs.isEmpty())
return;
@ -3565,7 +3585,7 @@ public class BrokerImpl
if (sm == null) {
// manage transient instance
meta = _repo.getMetaData(obj.getClass(), true);
meta = _repo.getMetaData(obj.getClass(), _loader, true);
sm = newStateManagerImpl
(StateManagerId.newInstance(this), meta);
@ -3636,7 +3656,7 @@ public class BrokerImpl
_flags |= FLAG_FLUSH_REQUIRED; // version check/up
} else if (sm == null) {
// manage transient instance
ClassMetaData meta = _repo.getMetaData(obj.getClass(), true);
ClassMetaData meta = _repo.getMetaData(obj.getClass(), _loader, true);
Object id = StateManagerId.newInstance(this);
sm = newStateManagerImpl(id, meta);
sm.initialize(assertPersistenceCapable(obj),
@ -3655,10 +3675,12 @@ public class BrokerImpl
/**
* Transition the given state managers to transactional.
*/
private void transactionalStatesAll(Collection<StateManagerImpl> sms, Collection<?> failed,
List<Exception> exceps) {
private void transactionalStatesAll(Collection sms, Collection failed,
List<Exception> exceps) {
// make instances transactional and make sure they are loaded
for (StateManagerImpl sm : sms) {
StateManagerImpl sm;
for (Iterator<?> itr = sms.iterator(); itr.hasNext();) {
sm = (StateManagerImpl) itr.next();
if (failed != null && failed.contains(sm.getId()))
continue;
@ -3676,14 +3698,15 @@ public class BrokerImpl
// Extent, Query
/////////////////
public <T> Extent<T> newExtent(Class<T> type, boolean subclasses) {
public Extent newExtent(Class type, boolean subclasses) {
return newExtent(type, subclasses, null);
}
private <T> Extent<T> newExtent(Class<T> type, boolean subclasses, FetchConfiguration fetch) {
private Extent newExtent(Class type, boolean subclasses,
FetchConfiguration fetch) {
beginOperation(true);
try {
ExtentImpl<T> extent = new ExtentImpl<T>(this, type, subclasses, fetch);
ExtentImpl extent = new ExtentImpl(this, type, subclasses, fetch);
if (_extents == null)
_extents = new ReferenceHashSet(ReferenceHashSet.WEAK);
_extents.add(extent);
@ -3698,14 +3721,14 @@ public class BrokerImpl
}
}
public <T> Iterator<T> extentIterator(Class<T> type, boolean subclasses,
FetchConfiguration fetch, boolean ignoreChanges) {
Extent<T> extent = newExtent(type, subclasses, fetch);
public Iterator extentIterator(Class type, boolean subclasses,
FetchConfiguration fetch, boolean ignoreChanges) {
Extent extent = newExtent(type, subclasses, fetch);
extent.setIgnoreChanges(ignoreChanges);
return extent.iterator();
}
public Query newQuery(String lang, Class<?> cls, Object query) {
public Query newQuery(String lang, Class cls, Object query) {
Query q = newQuery(lang, query);
q.setCandidateType(cls, true);
return q;
@ -3792,7 +3815,7 @@ public class BrokerImpl
SequenceMetaData smd = (fmd == null)
? meta.getIdentitySequenceMetaData()
: fmd.getValueSequenceMetaData();
return smd.getInstance();
return smd.getInstance(_loader);
default:
// use store manager for native sequence
if (fmd == null) {
@ -3811,7 +3834,7 @@ public class BrokerImpl
}
if (smd != null) {
return smd.getInstance();
return smd.getInstance(_loader);
} else {
return _store.getDataStoreIdSequence(meta);
}
@ -3862,7 +3885,7 @@ public class BrokerImpl
}
}
public void lockAll(Collection<?> objs, OpCallbacks call) {
public void lockAll(Collection objs, OpCallbacks call) {
if (objs.isEmpty())
return;
@ -3875,7 +3898,8 @@ public class BrokerImpl
}
}
public void lockAll(Collection<?> objs, int level, int timeout, OpCallbacks call) {
public void lockAll(Collection objs, int level, int timeout,
OpCallbacks call) {
if (objs.isEmpty())
return;
if (objs.size() == 1) {
@ -3904,9 +3928,8 @@ public class BrokerImpl
}
_lm.lockAll(sms, level, timeout, null);
for (Iterator<StateManagerImpl> itr = sms.iterator(); itr.hasNext();) {
for (Iterator<StateManagerImpl> itr = sms.iterator(); itr.hasNext();)
itr.next().readLocked(level, level);
}
} catch (OpenJPAException ke) {
throw ke;
} catch (RuntimeException re) {
@ -3978,7 +4001,7 @@ public class BrokerImpl
// Cache
/////////
public Collection<Object> getManagedObjects() {
public Collection getManagedObjects() {
beginOperation(false);
try {
return new ManagedObjectCollection(getManagedStates());
@ -3987,7 +4010,7 @@ public class BrokerImpl
}
}
public Collection<Object> getTransactionalObjects() {
public Collection getTransactionalObjects() {
beginOperation(false);
try {
return new ManagedObjectCollection(getTransactionalStates());
@ -3996,16 +4019,17 @@ public class BrokerImpl
}
}
public Collection<Object> getPendingTransactionalObjects() {
public Collection getPendingTransactionalObjects() {
beginOperation(false);
try {
return new ManagedObjectCollection(getPendingTransactionalStates());
return new ManagedObjectCollection
(getPendingTransactionalStates());
} finally {
endOperation();
}
}
public Collection<Object> getDirtyObjects() {
public Collection getDirtyObjects() {
beginOperation(false);
try {
return new ManagedObjectCollection(getDirtyStates());
@ -4025,7 +4049,7 @@ public class BrokerImpl
/**
* Return a copy of all managed state managers.
*/
protected Collection<StateManagerImpl> getManagedStates() {
protected Collection getManagedStates() {
return _cache.copy();
}
@ -4053,9 +4077,9 @@ public class BrokerImpl
/**
* Return a copy of all dirty state managers.
*/
protected Collection<StateManagerImpl> getDirtyStates() {
protected Collection getDirtyStates() {
if (!hasTransactionalObjects())
return Collections.emptySet();
return Collections.EMPTY_SET;
return _transCache.copyDirty();
}
@ -4064,9 +4088,9 @@ public class BrokerImpl
* Return a copy of all state managers which will become
* transactional upon the next transaction.
*/
protected Collection<StateManagerImpl> getPendingTransactionalStates() {
protected Collection getPendingTransactionalStates() {
if (_pending == null)
return Collections.emptySet();
return Collections.EMPTY_SET;
return new LinkedHashSet<StateManagerImpl>(_pending);
}
@ -4275,7 +4299,7 @@ public class BrokerImpl
}
}
public void dirtyType(Class<?> cls) {
public void dirtyType(Class cls) {
if (cls == null)
return;
@ -4289,21 +4313,21 @@ public class BrokerImpl
}
}
public Collection<Class<?>> getPersistedTypes() {
public Collection getPersistedTypes() {
if (_persistedClss == null || _persistedClss.isEmpty())
return Collections.emptySet();
return Collections.EMPTY_SET;
return Collections.unmodifiableCollection(_persistedClss);
}
public Collection<Class<?>> getUpdatedTypes() {
public Collection getUpdatedTypes() {
if (_updatedClss == null || _updatedClss.isEmpty())
return Collections.emptySet();
return Collections.EMPTY_SET;
return Collections.unmodifiableCollection(_updatedClss);
}
public Collection<Class<?>> getDeletedTypes() {
public Collection getDeletedTypes() {
if (_deletedClss == null || _deletedClss.isEmpty())
return Collections.emptySet();
return Collections.EMPTY_SET;
return Collections.unmodifiableCollection(_deletedClss);
}
@ -4359,6 +4383,7 @@ public class BrokerImpl
_deletedClss = null;
_derefCache = null;
_pending = null;
_loader = null;
_transEventManager = null;
_lifeEventManager = null;
@ -4382,9 +4407,9 @@ public class BrokerImpl
}
if (_extents != null) {
Extent<?> e;
Extent e;
for (Iterator<?> itr = _extents.iterator(); itr.hasNext();) {
e = (Extent<?>) itr.next();
e = (Extent) itr.next();
try {
e.closeAll();
} catch (RuntimeException re) {
@ -4429,11 +4454,12 @@ public class BrokerImpl
// State management
////////////////////
public Object newInstance(Class<?> cls) {
public Object newInstance(Class cls) {
assertOpen();
if (!cls.isInterface() && Modifier.isAbstract(cls.getModifiers()))
throw new UnsupportedOperationException(_loc.get("new-abstract", cls).getMessage());
throw new UnsupportedOperationException(_loc.get
("new-abstract", cls).getMessage());
// 1.5 doesn't initialize classes without a true Class.forName
if (!PCRegistry.isRegistered(cls)) {
@ -4445,7 +4471,7 @@ public class BrokerImpl
}
}
if (_repo.getMetaData(cls, false) == null)
if (_repo.getMetaData(cls, getClassLoader(), false) == null)
throw new IllegalArgumentException(
_loc.get("no-interface-metadata", cls.getName()).getMessage());
@ -4467,7 +4493,7 @@ public class BrokerImpl
if (pc.pcGetStateManager() == null) {
// If the statemanager is null the call to pcFetchObjectId always returns null. Create a new object
// id.
return ApplicationIds.create(pc, _repo.getMetaData(pc.getClass(), true));
return ApplicationIds.create(pc, _repo.getMetaData(pc.getClass(), null, true));
}
return pc.pcFetchObjectId();
}
@ -4556,7 +4582,7 @@ public class BrokerImpl
return detached.booleanValue();
// last resort: instance is detached if it has a store record
ClassMetaData meta = _repo.getMetaData(ImplHelper.getManagedInstance(pc).getClass(), true);
ClassMetaData meta = _repo.getMetaData(ImplHelper.getManagedInstance(pc).getClass(), _loader, true);
Object oid = ApplicationIds.create(pc, meta);
if (oid == null)
return false;
@ -4685,7 +4711,8 @@ public class BrokerImpl
* Return an object not found exception containing nested exceptions
* for all of the given failed objects.
*/
private static ObjectNotFoundException newObjectNotFoundException(Collection<?> failed) {
private static ObjectNotFoundException newObjectNotFoundException
(Collection failed) {
Throwable[] t = new Throwable[failed.size()];
int idx = 0;
for (Iterator<?> itr = failed.iterator(); itr.hasNext(); idx++)
@ -4774,11 +4801,11 @@ public class BrokerImpl
* Transactional cache that holds soft refs to clean instances.
*/
static class TransactionalCache
implements Set<StateManagerImpl>, Serializable {
implements Set, Serializable {
private final boolean _orderDirty;
private Set<StateManagerImpl> _dirty;
private Set<StateManagerImpl> _clean;
private Set<StateManagerImpl> _dirty = null;
private Set<StateManagerImpl> _clean = null;
public TransactionalCache(boolean orderDirty) {
_orderDirty = orderDirty;
@ -4787,31 +4814,31 @@ public class BrokerImpl
/**
* Return a copy of all transactional state managers.
*/
public Collection<StateManagerImpl> copy() {
public Collection copy() {
if (isEmpty()) {
// Transaction Listeners may add entities to the transaction.
return new LinkedHashSet<StateManagerImpl>();
return new LinkedHashSet();
}
// size may not be entirely accurate due to refs expiring, so
// manually copy each object; doesn't matter this way if size too
// big by some
Set<StateManagerImpl> copy = new LinkedHashSet<StateManagerImpl>(size());
Set copy = new LinkedHashSet(size());
if (_dirty != null)
for (StateManagerImpl dirty : _dirty)
copy.add(dirty);
for (Iterator<StateManagerImpl> itr = _dirty.iterator(); itr.hasNext();)
copy.add(itr.next());
if (_clean != null)
for (StateManagerImpl clean : _clean)
copy.add(clean);
for (Iterator<StateManagerImpl> itr = _clean.iterator(); itr.hasNext();)
copy.add(itr.next());
return copy;
}
/**
* Return a copy of all dirty state managers.
*/
public Collection<StateManagerImpl> copyDirty() {
public Collection copyDirty() {
if (_dirty == null || _dirty.isEmpty())
return Collections.emptySet();
return Collections.EMPTY_SET;
return new LinkedHashSet<StateManagerImpl>(_dirty);
}
@ -4863,7 +4890,7 @@ public class BrokerImpl
return _clean != null && _clean.remove(sm);
}
public Iterator<StateManagerImpl> iterator() {
public Iterator iterator() {
IteratorChain chain = new IteratorChain();
if (_dirty != null && !_dirty.isEmpty())
chain.addIterator(_dirty.iterator());
@ -4877,7 +4904,7 @@ public class BrokerImpl
|| (_clean != null && _clean.contains(obj));
}
public boolean containsAll(Collection<?> coll) {
public boolean containsAll(Collection coll) {
for (Iterator<?> itr = coll.iterator(); itr.hasNext();)
if (!contains(itr.next()))
return false;
@ -4905,11 +4932,11 @@ public class BrokerImpl
return size;
}
public boolean add(StateManagerImpl obj) {
public boolean add(Object obj) {
throw new UnsupportedOperationException();
}
public boolean addAll(Collection<? extends StateManagerImpl> coll) {
public boolean addAll(Collection coll) {
throw new UnsupportedOperationException();
}
@ -4917,11 +4944,11 @@ public class BrokerImpl
throw new UnsupportedOperationException();
}
public boolean removeAll(Collection<?> coll) {
public boolean removeAll(Collection coll) {
throw new UnsupportedOperationException();
}
public boolean retainAll(Collection<?> c) {
public boolean retainAll(Collection c) {
throw new UnsupportedOperationException();
}
@ -4929,10 +4956,9 @@ public class BrokerImpl
throw new UnsupportedOperationException();
}
@Override
public <T> T[] toArray(T[] a) {
public Object[] toArray(Object[] arr) {
throw new UnsupportedOperationException();
}
}
}
/**
@ -4989,15 +5015,15 @@ public class BrokerImpl
* with the corresponding managed objects.
*/
private static class ManagedObjectCollection
extends AbstractCollection<Object> {
extends AbstractCollection {
private final Collection<? extends OpenJPAStateManager> _states;
private final Collection _states;
public ManagedObjectCollection(Collection<? extends OpenJPAStateManager> states) {
public ManagedObjectCollection(Collection states) {
_states = states;
}
public Collection<? extends OpenJPAStateManager> getStateManagers() {
public Collection getStateManagers() {
return _states;
}
@ -5005,16 +5031,17 @@ public class BrokerImpl
return _states.size();
}
public Iterator<Object> iterator() {
return new Iterator<Object>() {
private final Iterator<? extends OpenJPAStateManager> _itr = _states.iterator();
public Iterator iterator() {
return new Iterator() {
private final Iterator _itr = _states.iterator();
public boolean hasNext() {
return _itr.hasNext();
}
public Object next() {
return ((OpenJPAStateManager) _itr.next()).getManagedInstance();
return ((OpenJPAStateManager) _itr.next()).
getManagedInstance();
}
public void remove() {

View File

@ -170,6 +170,14 @@ public class DelegatingBroker
}
}
public ClassLoader getClassLoader() {
try {
return _broker.getClassLoader();
} catch (RuntimeException re) {
throw translate(re);
}
}
public LockManager getLockManager() {
try {
return _broker.getLockManager();

View File

@ -127,7 +127,7 @@ public abstract class DelegatingStoreManager
_store.beforeStateChange(sm, fromState, toState);
}
public Collection<Exception> flush(Collection<? extends OpenJPAStateManager> sms) {
public Collection<Exception> flush(Collection<OpenJPAStateManager> sms) {
return _store.flush(sms);
}

View File

@ -48,10 +48,12 @@ class DetachedStateAttachStrategy
return null;
Broker broker = manager.getBroker();
PersistenceCapable pc = ImplHelper.toPersistenceCapable(toAttach, broker.getConfiguration());
PersistenceCapable pc = ImplHelper.toPersistenceCapable(toAttach,
broker.getConfiguration());
ClassMetaData meta = broker.getConfiguration().
getMetaDataRepositoryInstance().getMetaData(
ImplHelper.getManagedInstance(toAttach).getClass(), true);
ImplHelper.getManagedInstance(toAttach).getClass(),
broker.getClassLoader(), true);
switch (meta.getIdentityType()) {
case ClassMetaData.ID_DATASTORE:

View File

@ -52,7 +52,8 @@ public class DetachedValueStateManager
public DetachedValueStateManager(Object pc, StoreContext ctx) {
this(ImplHelper.toPersistenceCapable(pc, ctx.getConfiguration()),
ctx.getConfiguration().getMetaDataRepositoryInstance()
.getMetaData(ImplHelper.getManagedInstance(pc).getClass(), true), ctx);
.getMetaData(ImplHelper.getManagedInstance(pc).getClass(),
ctx.getClassLoader(), true), ctx);
}
public DetachedValueStateManager(PersistenceCapable pc, ClassMetaData meta,

View File

@ -94,8 +94,8 @@ public class ExpressionStoreQuery
new StringContains(), new WildcardMatch(),
};
protected final ExpressionParser _parser;
protected transient Object _parsed;
private final ExpressionParser _parser;
private transient Object _parsed;
/**
* Construct a query with a parser for the language.
@ -172,7 +172,7 @@ public class ExpressionStoreQuery
public Executor newInMemoryExecutor(ClassMetaData meta, boolean subs) {
return new InMemoryExecutor(this, meta, subs, _parser,
ctx.getCompilation(), new InMemoryExpressionFactory());
ctx.getCompilation());
}
public Executor newDataStoreExecutor(ClassMetaData meta, boolean subs) {
@ -576,7 +576,7 @@ public class ExpressionStoreQuery
/**
* Runs the expression query in memory.
*/
public static class InMemoryExecutor
private static class InMemoryExecutor
extends AbstractExpressionExecutor
implements Executor, Serializable {
@ -588,10 +588,10 @@ public class ExpressionStoreQuery
public InMemoryExecutor(ExpressionStoreQuery q,
ClassMetaData candidate, boolean subclasses,
ExpressionParser parser, Object parsed, InMemoryExpressionFactory factory) {
ExpressionParser parser, Object parsed) {
_meta = candidate;
_subs = subclasses;
_factory = factory;
_factory = new InMemoryExpressionFactory();
_exps = new QueryExpressions[] {
parser.eval(parsed, q, _factory, _meta)
@ -637,9 +637,9 @@ public class ExpressionStoreQuery
Object obj;
while (itr.hasNext()) {
obj = itr.next();
if (_factory.matches(_exps[0], _meta, _subs, obj, ctx, params)) {
if (_factory.matches(_exps[0], _meta, _subs, obj, ctx,
params))
results.add(obj);
}
}
}
finally {
@ -703,7 +703,6 @@ public class ExpressionStoreQuery
public Class[] getProjectionTypes(StoreQuery q) {
return _projTypes;
}
/**
* Throws an exception if a variable is found.

View File

@ -66,7 +66,7 @@ public class ExtentImpl<T>
* @param type the candidate class
* @param subs whether subclasses are included in the extent
*/
protected ExtentImpl(Broker broker, Class<T> type, boolean subs,
ExtentImpl(Broker broker, Class<T> type, boolean subs,
FetchConfiguration fetch) {
_broker = broker;
_type = type;
@ -120,7 +120,8 @@ public class ExtentImpl<T>
// add database iterators for each implementing class
MetaDataRepository repos = _broker.getConfiguration().
getMetaDataRepositoryInstance();
ClassMetaData meta = repos.getMetaData(_type, false);
ClassMetaData meta = repos.getMetaData(_type,
_broker.getClassLoader(), false);
ClassMetaData[] metas;
if (meta != null && (!_subs || !meta.isManagedInterface())
@ -128,7 +129,8 @@ public class ExtentImpl<T>
&& meta.getMappedPCSubclassMetaDatas().length > 0)))
metas = new ClassMetaData[]{ meta };
else if (_subs && (meta == null || meta.isManagedInterface()))
metas = repos.getImplementorMetaDatas(_type, false);
metas = repos.getImplementorMetaDatas(_type,
_broker.getClassLoader(), false);
else
metas = EMPTY_METAS;

View File

@ -86,6 +86,7 @@ public class QueryImpl
private final StoreQuery _storeQuery;
private transient final BrokerImpl _broker;
private transient final Log _log;
private transient ClassLoader _loader = null;
// query has its own internal lock
private ReentrantLock _lock;
@ -353,6 +354,7 @@ public class QueryImpl
boolean invalidate = false;
if (_extent.getElementType() != _class) {
_class = _extent.getElementType();
_loader = null;
invalidate = true;
}
if (_extent.hasSubclasses() != _subclasses) {
@ -412,6 +414,7 @@ public class QueryImpl
assertNotReadOnly();
_class = candidateClass;
_subclasses = subs;
_loader = null;
invalidateCompilation();
} finally {
unlock();
@ -720,14 +723,17 @@ public class QueryImpl
private StoreQuery.Executor createExecutor(boolean inMem) {
assertCandidateType();
MetaDataRepository repos = _broker.getConfiguration().getMetaDataRepositoryInstance();
ClassMetaData meta = repos.getMetaData(_class, false);
MetaDataRepository repos = _broker.getConfiguration().
getMetaDataRepositoryInstance();
ClassMetaData meta = repos.getMetaData(_class,
_broker.getClassLoader(), false);
ClassMetaData[] metas;
if (_class == null || _storeQuery.supportsAbstractExecutors())
metas = new ClassMetaData[]{ meta };
else if (_subclasses && (meta == null || meta.isManagedInterface()))
metas = repos.getImplementorMetaDatas(_class, true);
metas = repos.getImplementorMetaDatas(_class,
_broker.getClassLoader(), true);
else if (meta != null && (_subclasses || meta.isMapped()))
metas = new ClassMetaData[]{ meta };
else
@ -738,7 +744,8 @@ public class QueryImpl
try {
if (metas.length == 1) {
if (inMem)
return _storeQuery.newInMemoryExecutor(metas[0], _subclasses);
return _storeQuery.newInMemoryExecutor(metas[0],
_subclasses);
return _storeQuery.newDataStoreExecutor(metas[0], _subclasses);
}
@ -1628,8 +1635,11 @@ public class QueryImpl
return type;
// first check the aliases map in the MetaDataRepository
ClassLoader loader = (_class == null) ? _loader
: AccessController.doPrivileged(
J2DoPrivHelper.getClassLoaderAction(_class));
ClassMetaData meta = _broker.getConfiguration().
getMetaDataRepositoryInstance().getMetaData(name, false);
getMetaDataRepositoryInstance().getMetaData(name, loader, false);
if (meta != null)
return meta.getDescribedType();
@ -1673,10 +1683,14 @@ public class QueryImpl
/**
* Return the {@link Class} for the given name, or null if name not valid.
*/
private Class<?> toClass(String name) {
private Class toClass(String name) {
if (_loader == null)
_loader = _broker.getConfiguration().getClassResolverInstance().
getClassLoader(_class, _broker.getClassLoader());
try {
return Class.forName(name, true, getBroker().getConfiguration().getClassLoader());
} catch (Exception re) {
return Strings.toClass(name, _loader);
} catch (RuntimeException re) {
} catch (NoClassDefFoundError ncdfe) {
}
return null;
}

View File

@ -160,7 +160,8 @@ public class StateManagerImpl
/**
* Constructor; supply id, type metadata, and owning persistence manager.
*/
public StateManagerImpl(Object id, ClassMetaData meta, BrokerImpl broker) {
protected StateManagerImpl(Object id, ClassMetaData meta,
BrokerImpl broker) {
_id = id;
_meta = meta;
_broker = broker;
@ -302,13 +303,15 @@ public class StateManagerImpl
// metadata to a superclass id -- the subclass' id may be a
// different class, so we need to reset it
if (_meta.getDescribedType() != cls) {
ClassMetaData sub = _meta.getRepository().getMetaData(cls, true);
ClassMetaData sub = _meta.getRepository().getMetaData
(cls, _broker.getClassLoader(), true);
if (_oid != null) {
if (_meta.getIdentityType() == ClassMetaData.ID_DATASTORE) {
_oid = _broker.getStoreManager().copyDataStoreId(_oid, sub);
} else if (_meta.isOpenJPAIdentity()) {
if (_meta.getIdentityType() == ClassMetaData.ID_DATASTORE)
_oid = _broker.getStoreManager().copyDataStoreId(_oid,
sub);
else if (_meta.isOpenJPAIdentity())
_oid = ApplicationIds.copy(_oid, sub);
} else if (sub.getObjectIdType() != _meta.getObjectIdType()) {
else if (sub.getObjectIdType() != _meta.getObjectIdType()) {
Object[] pkFields = ApplicationIds.toPKValues(_oid, _meta);
_oid = ApplicationIds.fromPKValues(pkFields, sub);
}
@ -321,9 +324,9 @@ public class StateManagerImpl
// the instance was null: check to see if the instance is
// abstract (as can sometimes be the case when the
// class discriminator strategy is not configured correctly)
if (Modifier.isAbstract(cls.getModifiers())) {
throw new UserException(_loc.get("instantiate-abstract", cls.getName(), _oid));
}
if (Modifier.isAbstract(cls.getModifiers()))
throw new UserException(_loc.get("instantiate-abstract",
cls.getName(), _oid));
throw new InternalException();
}
@ -333,7 +336,7 @@ public class StateManagerImpl
/**
* Initialize with the given instance and state.
*/
public void initialize(PersistenceCapable pc, PCState state) {
protected void initialize(PersistenceCapable pc, PCState state) {
if (pc == null)
throw new UserException(_loc.get("init-null-pc", _meta));
if (pc.pcGetStateManager() != null && pc.pcGetStateManager() != this)
@ -3364,7 +3367,7 @@ public class StateManagerImpl
// penalizes the serialization footprint of non-ReflectingPC SMs also.
Class managedType = (Class) in.readObject();
_meta = _broker.getConfiguration().getMetaDataRepositoryInstance()
.getMetaData(managedType, true);
.getMetaData(managedType, null, true);
_pc = readPC(in);
}

View File

@ -93,6 +93,12 @@ public interface StoreContext {
*/
public void popFetchConfiguration();
/**
* Return the current thread's class loader at the time this context
* was obtained.
*/
public ClassLoader getClassLoader();
/**
* Return the lock manager in use.
*/
@ -147,7 +153,8 @@ public interface StoreContext {
* parameter
* @see #find(Object,boolean,FindCallbacks)
*/
public Object[] findAll(Collection<?> oids, boolean validate, FindCallbacks call);
public Object[] findAll(Collection<Object> oids, boolean validate,
FindCallbacks call);
/**
* Return the object with the given oid. If present, the
@ -162,14 +169,15 @@ public interface StoreContext {
* if a cached instance has been deleted concurrently. These options
* are controllable through the given <code>OID_XXX</code> flags.
*/
public Object find(Object oid, FetchConfiguration fetch, BitSet exclude, Object edata, int flags);
public Object find(Object oid, FetchConfiguration fetch, BitSet exclude,
Object edata, int flags);
/**
* Return the objects with the given oids.
*
* @see #find(Object,FetchConfiguration,BitSet,Object,int)
*/
public Object[] findAll(Collection<?> oids, FetchConfiguration fetch,
public Object[] findAll(Collection<Object> oids, FetchConfiguration fetch,
BitSet exclude, Object edata, int flags);
/**
@ -178,7 +186,8 @@ public interface StoreContext {
* when no longer needed. This method delegates to
* {@link StoreManager#executeExtent}.
*/
public <T> Iterator<T> extentIterator(Class<T> cls, boolean subs, FetchConfiguration fetch, boolean ignoreChanges);
public Iterator<Object> extentIterator(Class<?> cls, boolean subs,
FetchConfiguration fetch, boolean ignoreChanges);
/**
* Immediately load the given object's persistent fields. One might
@ -200,7 +209,7 @@ public interface StoreContext {
* @param fgOnly indicator as to whether to retrieve only fields
* @see #retrieve
*/
public void retrieveAll(Collection<?> objs, boolean fgOnly, OpCallbacks call);
public void retrieveAll(Collection<Object> objs, boolean fgOnly, OpCallbacks call);
/**
* Make the given instance embedded.
@ -212,7 +221,8 @@ public interface StoreContext {
* @param ownerMeta the value in which the object is embedded
* @return the state manager for the embedded instance
*/
public OpenJPAStateManager embed(Object obj, Object id, OpenJPAStateManager owner, ValueMetaData ownerMeta);
public OpenJPAStateManager embed(Object obj, Object id,
OpenJPAStateManager owner, ValueMetaData ownerMeta);
/**
* Return the application or datastore identity class the given persistent
@ -329,7 +339,7 @@ public interface StoreContext {
* @param updateVersion if true, the instance's version will be
* incremented at the next flush
*/
public void transactionalAll(Collection<?> objs, boolean updateVersion, OpCallbacks call);
public void transactionalAll(Collection<Object> objs, boolean updateVersion, OpCallbacks call);
/**
* Make the given object non-transactional.
@ -339,7 +349,7 @@ public interface StoreContext {
/**
* Make the given objects nontransactional.
*/
public void nontransactionalAll(Collection<?> objs, OpCallbacks call);
public void nontransactionalAll(Collection<Object> objs, OpCallbacks call);
/**
* Return whether the given object is persistent.

View File

@ -252,7 +252,7 @@ public interface StoreManager
*
* @see org.apache.openjpa.util.ApplicationIds#assign()
*/
public Collection<Exception> flush(Collection<? extends OpenJPAStateManager> sms);
public Collection<Exception> flush(Collection<OpenJPAStateManager> sms);
/**
* Assign an object id to the given new instance. Return false if the

View File

@ -23,7 +23,6 @@ import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import org.apache.openjpa.conf.OpenJPAConfiguration;
import org.apache.openjpa.enhance.PersistenceCapable;
import org.apache.openjpa.enhance.Reflection;
import org.apache.openjpa.enhance.StateManager;
@ -49,31 +48,39 @@ class VersionAttachStrategy
extends AttachStrategy
implements DetachState {
private static final Localizer _loc = Localizer.forPackage(VersionAttachStrategy.class);
private static final Localizer _loc = Localizer.forPackage
(VersionAttachStrategy.class);
protected Object getDetachedObjectId(AttachManager manager, Object toAttach) {
protected Object getDetachedObjectId(AttachManager manager,
Object toAttach) {
Broker broker = manager.getBroker();
ClassMetaData meta = broker.getConfiguration().
getMetaDataRepositoryInstance().getMetaData(
ImplHelper.getManagedInstance(toAttach).getClass(), true);
return ApplicationIds.create(ImplHelper.toPersistenceCapable(toAttach, broker.getConfiguration()), meta);
ImplHelper.getManagedInstance(toAttach).getClass(),
broker.getClassLoader(), true);
return ApplicationIds.create(ImplHelper.toPersistenceCapable(toAttach,
broker.getConfiguration()),
meta);
}
protected void provideField(Object toAttach, StateManagerImpl sm, int field) {
sm.provideField(ImplHelper.toPersistenceCapable(toAttach, sm.getContext().getConfiguration()), this, field);
protected void provideField(Object toAttach, StateManagerImpl sm,
int field) {
sm.provideField(ImplHelper.toPersistenceCapable(toAttach,
sm.getContext().getConfiguration()), this, field);
}
public Object attach(AttachManager manager, Object toAttach,
ClassMetaData meta, PersistenceCapable into, OpenJPAStateManager owner,
ValueMetaData ownerMeta, boolean explicit) {
BrokerImpl broker = manager.getBroker();
PersistenceCapable pc = ImplHelper.toPersistenceCapable(toAttach, meta.getRepository().getConfiguration());
PersistenceCapable pc = ImplHelper.toPersistenceCapable(toAttach,
meta.getRepository().getConfiguration());
boolean embedded = ownerMeta != null && ownerMeta.isEmbeddedPC();
boolean isNew = !broker.isDetached(pc);
Object version = null;
StateManagerImpl sm;
OpenJPAConfiguration conf = broker.getConfiguration();
// if the state manager for the embedded instance is null, then
// it should be treated as a new instance (since the
// newly persisted owner may create a new embedded instance
@ -83,35 +90,39 @@ class VersionAttachStrategy
// copy into a new embedded instance
if (embedded && (isNew || into == null
|| broker.getStateManager(into) == null)) {
if (into == null) {
if (into == null)
into = pc.pcNewInstance(null, false);
}
sm = (StateManagerImpl) broker.embed(into, null, owner, ownerMeta);
into = sm.getPersistenceCapable();
} else if (isNew) {
Object oid = null;
if (!isPrimaryKeysGenerated(meta)) {
if (!isPrimaryKeysGenerated(meta))
oid = ApplicationIds.create(pc, meta);
}
sm = persist(manager, pc, meta, oid, explicit);
into = sm.getPersistenceCapable();
} else if (!embedded && into == null) {
Object id = getDetachedObjectId(manager, toAttach);
if (id != null) {
into = ImplHelper.toPersistenceCapable(broker.find(id, true, null), conf);
}
if (into == null) {
if (id != null)
into =
ImplHelper.toPersistenceCapable(broker.find(id, true, null),
broker.getConfiguration());
if (into == null)
throw new OptimisticException(_loc.get("attach-version-del",
ImplHelper.getManagedInstance(pc).getClass(), id, version)).setFailedObject(toAttach);
}
ImplHelper.getManagedInstance(pc).getClass(), id, version))
.setFailedObject(toAttach);
sm = manager.assertManaged(into);
if (meta.getDescribedType() != sm.getMetaData().getDescribedType()) {
throw new ObjectNotFoundException(_loc.get("attach-wrongclass", id, toAttach.getClass(),
sm.getMetaData().getDescribedType())).setFailedObject(toAttach);
if (meta.getDescribedType()
!= sm.getMetaData().getDescribedType()) {
throw new ObjectNotFoundException(_loc.get
("attach-wrongclass", id, toAttach.getClass(),
sm.getMetaData().getDescribedType())).
setFailedObject(toAttach);
}
} else {
} else
sm = manager.assertManaged(into);
}
// mark that we attached the instance *before* we
// fill in values to avoid endless recursion
manager.setAttachedCopy(toAttach, into);
@ -123,7 +134,8 @@ class VersionAttachStrategy
}
if (isNew) {
broker.fireLifecycleEvent(toAttach, null, meta, LifecycleEvent.BEFORE_PERSIST);
broker.fireLifecycleEvent(toAttach, null, meta,
LifecycleEvent.BEFORE_PERSIST);
} else {
// invoke any preAttach on the detached instance
manager.fireBeforeAttach(toAttach, meta);
@ -143,9 +155,9 @@ class VersionAttachStrategy
attachField(manager, toAttach, sm, fmds[i], true);
break;
case DETACH_FETCH_GROUPS:
if (fetch.requiresFetch(fmds[i]) != FetchConfiguration.FETCH_NONE) {
if (fetch.requiresFetch(fmds[i])
!= FetchConfiguration.FETCH_NONE)
attachField(manager, toAttach, sm, fmds[i], true);
}
break;
case DETACH_LOADED:
attachField(manager, toAttach, sm, fmds[i], false);
@ -155,9 +167,8 @@ class VersionAttachStrategy
} finally {
pc.pcReplaceStateManager(smBefore);
}
if (!embedded && !isNew) {
if (!embedded && !isNew)
compareVersion(sm, pc);
}
return ImplHelper.getManagedInstance(into);
}

View File

@ -234,8 +234,16 @@ public abstract class AbstractExpressionBuilder {
* Convenience method to get metadata for the given type.
*/
protected ClassMetaData getMetaData(Class<?> c, boolean required) {
return getMetaData(c, required, getClassLoader());
}
/**
* Convenience method to get metadata for the given type.
*/
protected ClassMetaData getMetaData(Class<?> c, boolean required,
ClassLoader loader) {
return resolver.getConfiguration().getMetaDataRepositoryInstance().
getMetaData(c, required);
getMetaData(c, loader, required);
}
/**

View File

@ -167,7 +167,7 @@ public class CandidatePath
/**
* Represents a traversal through a field.
*/
public static class Traversal {
private static class Traversal {
public final FieldMetaData field;
public final boolean nullTraversal;

View File

@ -27,7 +27,7 @@ import org.apache.openjpa.kernel.StoreContext;
*
* @author Abe White
*/
public class Exp
class Exp
implements Expression {
/**

View File

@ -82,7 +82,7 @@ public class InMemoryExpressionFactory
* of embedded procedural loops over the extents of all variables in the
* unbounds list.
*/
protected boolean matches(Exp exp, Object candidate, StoreContext ctx,
private boolean matches(Exp exp, Object candidate, StoreContext ctx,
Object[] params, int i) {
// base case: all variables have been aliased; evaluate for current
// values

View File

@ -168,11 +168,12 @@ public class JPQLExpressionBuilder
}
private ClassMetaData getClassMetaData(String alias, boolean assertValid) {
ClassLoader loader = getClassLoader();
MetaDataRepository repos = resolver.getConfiguration().
getMetaDataRepositoryInstance();
// first check for the alias
ClassMetaData cmd = repos.getMetaData(alias, false);
ClassMetaData cmd = repos.getMetaData(alias, loader, false);
if (cmd != null)
return cmd;
@ -183,9 +184,9 @@ public class JPQLExpressionBuilder
// the concept of entity names or aliases
Class<?> c = resolver.classForName(alias, null);
if (c != null)
cmd = repos.getMetaData(c, assertValid);
cmd = repos.getMetaData(c, loader, assertValid);
else if (assertValid)
cmd = repos.getMetaData(alias, false);
cmd = repos.getMetaData(alias, loader, false);
if (cmd == null && assertValid) {
String close = repos.getClosestAliasName(alias);

View File

@ -61,7 +61,7 @@ import serp.util.Strings;
/**
* Base class for factory implementations built around XML metadata files
* in the common format.
* in the common fomat.
*
* @author Abe White
* @since 0.4.0
@ -69,7 +69,8 @@ import serp.util.Strings;
public abstract class AbstractCFMetaDataFactory
extends AbstractMetaDataFactory {
private static final Localizer _loc = Localizer.forPackage(AbstractMetaDataFactory.class);
private static final Localizer _loc = Localizer.forPackage
(AbstractMetaDataFactory.class);
protected Collection<File> files = null;
protected Collection<URL> urls = null;
@ -180,7 +181,8 @@ public abstract class AbstractCFMetaDataFactory
if (!strict && (mode & MODE_META) != 0)
mode |= MODE_MAPPING;
Class<?> cls = (metas.length == 0) ? null : metas[0].getDescribedType();
ClassLoader loader = repos.getConfiguration().getClassLoader();
ClassLoader loader = repos.getConfiguration().
getClassResolverInstance().getClassLoader(cls, null);
Map<String,ClassMetaData> clsNames = new HashMap<String,ClassMetaData>
((int) (metas.length * 1.33 + 1));
for (int i = 0; i < metas.length; i++)
@ -191,7 +193,8 @@ public abstract class AbstractCFMetaDataFactory
Set metaFiles = null;
Set queryFiles = null;
if (isMappingOnlyFactory() || (mode & MODE_META) != 0)
metaFiles = assignDefaultMetaDataFiles(metas, queries, seqs, mode, clsNames);
metaFiles = assignDefaultMetaDataFiles(metas, queries, seqs, mode,
clsNames);
if (!isMappingOnlyFactory() && (mode & MODE_QUERY) != 0)
queryFiles = assignDefaultQueryFiles(queries, clsNames);
@ -209,6 +212,7 @@ public abstract class AbstractCFMetaDataFactory
if (metaFiles != null) {
parser = newParser(false);
parser.setMode(sermode);
parser.setClassLoader(loader);
parse(parser, metaFiles);
MetaDataRepository pr = parser.getRepository();
@ -230,9 +234,9 @@ public abstract class AbstractCFMetaDataFactory
&& (queries[i].getSourceMode() & mode) != 0)
ser.addQueryMetaData(queries[i]);
int flags = MetaDataSerializer.PRETTY;
int flags = ser.PRETTY;
if ((store & STORE_VERBOSE) != 0)
flags |= MetaDataSerializer.VERBOSE;
flags |= ser.VERBOSE;
serialize(ser, output, flags);
}
@ -250,19 +254,20 @@ public abstract class AbstractCFMetaDataFactory
if (queryFiles != null) {
parser = newParser(false);
parser.setMode(MODE_QUERY);
parser.setClassLoader(loader);
parse(parser, queryFiles);
ser.addAll(parser.getRepository());
}
for (int i = 0; i < queries.length; i++)
if (queries[i].getSourceMode() == MODE_QUERY)
ser.addQueryMetaData(queries[i]);
serialize(ser, output, MetaDataSerializer.PRETTY);
serialize(ser, output, ser.PRETTY);
}
}
return true;
}
public boolean drop(Class[] cls, int mode) {
public boolean drop(Class[] cls, int mode, ClassLoader envLoader) {
if (mode == MODE_NONE)
return true;
if (isMappingOnlyFactory() && (mode & MODE_MAPPING) == 0)
@ -295,7 +300,7 @@ public abstract class AbstractCFMetaDataFactory
clsNames.add(null);
else
clsNames.add(cls[i].getName());
meta = pr.getMetaData(cls[i], false);
meta = pr.getMetaData(cls[i], envLoader, false);
if (meta != null) {
if (getSourceFile(meta) != null)
files.add(getSourceFile(meta));
@ -337,7 +342,8 @@ public abstract class AbstractCFMetaDataFactory
// calling code can take advantage of metadata still in repos
if (isMappingOnlyFactory())
for (int i = 0; i < cls.length; i++)
ser.removeMetaData(pr.getMetaData(cls[i], false));
ser.removeMetaData(pr.getMetaData(cls[i], envLoader,
false));
serialize(ser, null, Serializer.PRETTY);
}
if (qqs != null && !qqs.isEmpty()) {
@ -496,7 +502,8 @@ public abstract class AbstractCFMetaDataFactory
for (Iterator itr = files.iterator(); itr.hasNext();) {
file = (File) itr.next();
if (Files.backup(file, false) != null)
AccessController.doPrivileged(J2DoPrivHelper.deleteAction(file));
AccessController
.doPrivileged(J2DoPrivHelper.deleteAction(file));
}
}
@ -594,7 +601,8 @@ public abstract class AbstractCFMetaDataFactory
return null;
}
public Set<String> getPersistentTypeNames(boolean devpath) {
public Set<String> getPersistentTypeNames(boolean devpath,
ClassLoader envLoader) {
// some configured locations might be implicit in spec, so return
// null if we don't find any classes, rather than if we don't have
// any locations
@ -602,16 +610,15 @@ public abstract class AbstractCFMetaDataFactory
return (_typeNames.isEmpty()) ? null : _typeNames;
try {
ClassLoader loader = repos.getConfiguration().getClassLoader();
ClassLoader loader = repos.getConfiguration().
getClassResolverInstance().getClassLoader(getClass(),
envLoader);
long start = System.currentTimeMillis();
Set names = parsePersistentTypeNames(loader);
if (names.isEmpty() && devpath) {
ClassArgParser cap = newClassArgParser();
cap.setClassLoader(repos.getConfiguration().getClassLoader());
if (names.isEmpty() && devpath)
scan(new ClasspathMetaDataIterator(null, newMetaDataFilter()),
cap, names, false, null);
}
newClassArgParser(), names, false, null);
else // we don't cache a full dev cp scan
_typeNames = names;
@ -630,7 +637,6 @@ public abstract class AbstractCFMetaDataFactory
protected Set<String> parsePersistentTypeNames(ClassLoader loader)
throws IOException {
ClassArgParser cparser = newClassArgParser();
cparser.setClassLoader(loader);
String[] clss;
Set<String> names = new HashSet<String>();
if (files != null) {
@ -754,8 +760,8 @@ public abstract class AbstractCFMetaDataFactory
} else {
if (log.isTraceEnabled())
log.trace(_loc.get("scanning-resource", rsrc));
mitr = new ResourceMetaDataIterator(rsrc, loader);
OpenJPAConfiguration conf = repos.getConfiguration();
mitr = new ResourceMetaDataIterator(rsrc, conf.getClassLoader());
Map peMap = null;
if (conf instanceof OpenJPAConfigurationImpl)
peMap = ((OpenJPAConfigurationImpl)conf).getPersistenceEnvironment();

View File

@ -45,13 +45,13 @@ public abstract class AbstractMetaDataFactory
protected File dir = null;
protected int store = STORE_DEFAULT;
protected boolean strict = false;
protected Set<String> types = null;
protected Set types = null;
/**
* Set of persistent type names supplied by user.
*/
public void setTypes(Set<String> types) {
public void setTypes(Set types) {
this.types = types;
}
@ -61,13 +61,14 @@ public abstract class AbstractMetaDataFactory
*/
public void setTypes(String types) {
this.types = (StringUtils.isEmpty(types)) ? null
: new HashSet<String>(Arrays.asList(Strings.split(types, ";", 0)));
: new HashSet(Arrays.asList(Strings.split(types, ";", 0)));
}
public void setRepository(MetaDataRepository repos) {
this.repos = repos;
if (repos != null)
log = repos.getConfiguration().getLog(OpenJPAConfiguration.LOG_METADATA);
log = repos.getConfiguration().getLog
(OpenJPAConfiguration.LOG_METADATA);
}
public void setStoreDirectory(File dir) {

View File

@ -135,10 +135,12 @@ public class ClassMetaData
private static final Localizer _loc = Localizer.forPackage
(ClassMetaData.class);
private static final FetchGroup[] EMPTY_FETCH_GROUP_ARRAY = new FetchGroup[0];
private static final FetchGroup[] EMPTY_FETCH_GROUP_ARRAY
= new FetchGroup[0];
private static final String[] EMPTY_STRING_ARRAY = new String[0];
private MetaDataRepository _repos;
private transient ClassLoader _loader = null;
private final ValueMetaData _owner;
private final LifecycleMetaData _lifeMeta = new LifecycleMetaData(this);
@ -234,6 +236,8 @@ public class ClassMetaData
protected ClassMetaData(ValueMetaData owner) {
_owner = owner;
_repos = owner.getRepository();
setEnvClassLoader(owner.getFieldMetaData().getDefiningMetaData().
getEnvClassLoader());
registerForValueUpdate("DataCacheTimeout");
}
@ -280,6 +284,24 @@ public class ClassMetaData
setIntercepting(true);
}
/**
* The environmental loader used when loading this metadata.
* The class metadata should use this loader when loading metadata for
* its superclass and field types.
*/
public ClassLoader getEnvClassLoader() {
return _loader;
}
/**
* The class environmental loader used when loading this metadata.
* The class metadata should use this loader when loading metadata for
* its superclass and field types.
*/
public void setEnvClassLoader(ClassLoader loader) {
_loader = loader;
}
/**
* The persistence capable superclass of the described type.
*/
@ -304,7 +326,7 @@ public class ClassMetaData
_superMeta = _repos.newEmbeddedClassMetaData(_owner);
_superMeta.setDescribedType(_super);
} else
_superMeta = _repos.getMetaData(_super, true);
_superMeta = _repos.getMetaData(_super, _loader, true);
}
return _superMeta;
}
@ -346,7 +368,7 @@ public class ClassMetaData
if (_owner != null)
return MetaDataRepository.EMPTY_CLASSES;
_repos.processRegisteredClasses();
_repos.processRegisteredClasses(_loader);
if (_subs == null) {
Collection<Class<?>> subs = _repos.getPCSubclasses(_type);
_subs = (Class[]) subs.toArray(new Class[subs.size()]);
@ -371,7 +393,7 @@ public class ClassMetaData
ClassMetaData[] metas = _repos.newClassMetaDataArray
(subs.length);
for (int i = 0; i < subs.length; i++)
metas[i] = _repos.getMetaData(subs[i], true);
metas[i] = _repos.getMetaData(subs[i], _loader, true);
_subMetas = metas;
}
}
@ -1807,7 +1829,7 @@ public class ClassMetaData
}
// copy info from the "real" metadata for this type
ClassMetaData meta = _repos.getMetaData(_type, true);
ClassMetaData meta = _repos.getMetaData(_type, _loader, true);
meta.resolve(MODE_META);
copy(this, meta);
_embedded = Boolean.FALSE; // embedded instance isn't embedded-only
@ -2598,20 +2620,21 @@ public class ClassMetaData
if (values == null)
return;
for (String key : values) {
Value<?> value = getRepository().getConfiguration().getValue(key);
Value value = getRepository().getConfiguration()
.getValue(key);
if (value != null)
value.addListener(this);
}
}
public void valueChanged(Value<?> val) {
public void valueChanged(Value val) {
if (val != null && val.matches("DataCacheTimeout")) {
_cacheTimeout = Integer.MIN_VALUE;
}
}
/**
* Utility method to get names of all fields including the super classes'
* Utility method to get names of all fields including the superclasses'
* sorted in lexical order.
*/
public String[] getFieldNames() {
@ -2620,7 +2643,7 @@ public class ClassMetaData
/**
* Utility method to get names of all declared fields excluding the
* super classes' sorted in lexical order.
* superclasses' sorted in lexical order.
*/
public String[] getDeclaredFieldNames() {
return toNames(getDeclaredFields());

View File

@ -55,7 +55,8 @@ public class DelegatingMetaDataFactory
*/
public MetaDataFactory getInnermostDelegate() {
if (_delegate instanceof DelegatingMetaDataFactory)
return ((DelegatingMetaDataFactory) _delegate).getInnermostDelegate();
return ((DelegatingMetaDataFactory) _delegate).
getInnermostDelegate();
return _delegate;
}
@ -75,17 +76,17 @@ public class DelegatingMetaDataFactory
_delegate.setStrict(true);
}
public void load(Class<?> cls, int mode) {
_delegate.load(cls, mode);
public void load(Class cls, int mode, ClassLoader envLoader) {
_delegate.load(cls, mode, envLoader);
}
public boolean store(ClassMetaData[] metas, QueryMetaData[] queries,
SequenceMetaData[] seqs, int mode, Map output) {
SequenceMetaData[] seqs, int mode, Map output) {
return _delegate.store(metas, queries, seqs, mode, output);
}
public boolean drop(Class<?>[] cls, int mode) {
return _delegate.drop(cls, mode);
public boolean drop(Class[] cls, int mode, ClassLoader envLoader) {
return _delegate.drop(cls, mode, envLoader);
}
public MetaDataDefaults getDefaults() {
@ -96,16 +97,18 @@ public class DelegatingMetaDataFactory
return _delegate.newClassArgParser();
}
public Set<String> getPersistentTypeNames(boolean classpath) {
return _delegate.getPersistentTypeNames(classpath);
public Set getPersistentTypeNames(boolean classpath,
ClassLoader envLoader) {
return _delegate.getPersistentTypeNames(classpath, envLoader);
}
public Class<?> getQueryScope(String queryName) {
return _delegate.getQueryScope(queryName);
public Class getQueryScope(String queryName, ClassLoader loader) {
return _delegate.getQueryScope(queryName, loader);
}
public Class<?> getResultSetMappingScope(String resultSetMappingName) {
return _delegate.getResultSetMappingScope(resultSetMappingName);
public Class getResultSetMappingScope(String resultSetMappingName,
ClassLoader loader) {
return _delegate.getResultSetMappingScope(resultSetMappingName, loader);
}
public void clear() {

View File

@ -328,7 +328,8 @@ public class FieldMetaData
if (_dec == null)
return _owner;
if (_decMeta == null)
_decMeta = getRepository().getMetaData(_dec, true);
_decMeta = getRepository().getMetaData(_dec,
_owner.getEnvClassLoader(), true);
return _decMeta;
}

View File

@ -215,10 +215,11 @@ public class JavaTypes {
* @param mustExist Whether the supplied loader <b>must</b> be able to load the class. If true no attempt to use a
* different classloader will be made. If false the ClassResolver from the configuration will be used.
*/
public static Class<?> classForName(String name, ValueMetaData context, boolean mustExist) {
public static Class<?> classForName(String name, ValueMetaData context,
ClassLoader loader, boolean mustExist) {
return classForName(name,
context.getFieldMetaData().getDefiningMetaData(),
context.getFieldMetaData().getDeclaringType(), context, mustExist);
context.getFieldMetaData().getDeclaringType(), context, loader, mustExist);
}
/**
@ -227,7 +228,7 @@ public class JavaTypes {
*/
private static Class<?> classForName(String name, ClassMetaData meta,
Class<?> dec, ValueMetaData vmd, ClassLoader loader) {
return classForName(name, meta, dec, vmd, true);
return classForName(name, meta, dec, vmd, loader, true);
}
/**
@ -235,7 +236,7 @@ public class JavaTypes {
* when parsing metadata.
*/
private static Class<?> classForName(String name, ClassMetaData meta, Class<?> dec, ValueMetaData vmd,
boolean mustExist) {
ClassLoader loader, boolean mustExist) {
// special case for PersistenceCapable and Object
if ("PersistenceCapable".equals(name)
|| "javax.jdo.PersistenceCapable".equals(name)) // backwards compatibility
@ -245,7 +246,9 @@ public class JavaTypes {
MetaDataRepository rep = meta.getRepository();
boolean runtime = (rep.getValidate() & MetaDataRepository.VALIDATE_RUNTIME) != 0;
ClassLoader loader = rep.getConfiguration().getClassLoader();
if (loader == null)
loader = rep.getConfiguration().getClassResolverInstance().
getClassLoader(dec, meta.getEnvClassLoader());
// try the owner's package
String pkg = Strings.getPackageName(dec);
@ -260,7 +263,8 @@ public class JavaTypes {
//load the class, check with the ClassResolver to get a loader
//and use it to attempt to load the class.
if (cls == null && !mustExist){
loader = rep.getConfiguration().getClassLoader();
loader = rep.getConfiguration().getClassResolverInstance().
getClassLoader(dec, meta.getEnvClassLoader());
cls = CFMetaDataParser.classForName(name, pkg, runtime, loader);
}
//OJ-758 end

View File

@ -75,7 +75,7 @@ public interface MetaDataFactory
* {@link MetaDataModes#MODE_META MODE_META}, so long as
* the <code>strict</code> property hasn't been set
*/
public void load(Class<?> cls, int mode);
public void load(Class<?> cls, int mode, ClassLoader envLoader);
/**
* Store the given metadata.
@ -95,7 +95,7 @@ public interface MetaDataFactory
*
* @return false if any metadata could not be dropped
*/
public boolean drop(Class<?>[] cls, int mode);
public boolean drop(Class<?>[] cls, int mode, ClassLoader envLoader);
/**
* Return the metadata defaults for this factory.
@ -112,17 +112,19 @@ public interface MetaDataFactory
* @see MetaDataRepository#getPersistentTypeNames
* @see MetaDataRepository#loadPersistentTypes
*/
public Set<String> getPersistentTypeNames(boolean devpath);
public Set<String> getPersistentTypeNames(boolean devpath,
ClassLoader envLoader);
/**
* Return the type defining the given query name, if any.
*/
public Class<?> getQueryScope(String queryName);
public Class<?> getQueryScope(String queryName, ClassLoader loader);
/**
* Return the type defining the given result set mapping name, if any.
*/
public Class<?> getResultSetMappingScope(String resultSetMappingName);
public Class<?> getResultSetMappingScope(String resultSetMappingName,
ClassLoader loader);
/**
* Return a properly-configured class arg parser for our expected

View File

@ -313,7 +313,21 @@ public class MetaDataRepository implements PCRegistry.RegisterClassListener, Con
}
Set<String> classes = getPersistentTypeNames(false);
MultiClassLoader multi = AccessController.doPrivileged(J2DoPrivHelper.newMultiClassLoaderAction());
multi.addClassLoader(AccessController.doPrivileged(J2DoPrivHelper.getContextClassLoaderAction()));
multi.addClassLoader(AccessController.doPrivileged(J2DoPrivHelper
.getClassLoaderAction(MetaDataRepository.class)));
// If a ClassLoader was passed into Persistence.createContainerEntityManagerFactory on the PersistenceUnitInfo
// we need to add that loader to the chain of classloaders
ClassResolver resolver = _conf.getClassResolverInstance();
if (resolver != null) {
ClassLoader cl = resolver.getClassLoader(null, null);
if (cl != null) {
multi.addClassLoader(cl);
}
}
Set<String> classes = getPersistentTypeNames(false, multi);
if (classes == null || classes.size() == 0) {
throw new MetaDataException(_loc.get("repos-initializeEager-none"));
}
@ -324,15 +338,15 @@ public class MetaDataRepository implements PCRegistry.RegisterClassListener, Con
List<Class<?>> loaded = new ArrayList<Class<?>>();
for (String c : classes) {
try {
Class<?> cls = Class.forName(c, true, _conf.getClassLoader());
Class<?> cls = AccessController.doPrivileged((J2DoPrivHelper.getForNameAction(c, true, multi)));
loaded.add(cls);
// This call may be unnecessary?
_factory.load(cls, MODE_ALL);
} catch (Exception pae) {
_factory.load(cls, MODE_ALL, multi);
} catch (PrivilegedActionException pae) {
throw new MetaDataException(_loc.get("repos-initializeEager-error"), pae);
}
}
resolveAll();
resolveAll(multi);
// Preload XML MetaData
for (Class<?> cls : loaded) {
@ -348,7 +362,7 @@ public class MetaDataRepository implements PCRegistry.RegisterClassListener, Con
// Hook in this class as a listener and process registered classes list to populate _aliases
// list.
PCRegistry.addRegisterClassListener(this);
processRegisteredClasses();
processRegisteredClasses(multi);
_locking = false;
_preloadComplete = true;
}
@ -364,17 +378,17 @@ public class MetaDataRepository implements PCRegistry.RegisterClassListener, Con
* @param mustExist
* if true, throws a {@link MetaDataException} if no metadata is found
*/
public ClassMetaData getMetaData(Class<?> cls, boolean mustExist) {
public ClassMetaData getMetaData(Class<?> cls, ClassLoader envLoader, boolean mustExist) {
if (_locking) {
synchronized(this){
return getMetaDataInternal(cls, mustExist);
return getMetaDataInternal(cls, envLoader, mustExist);
}
} else {
return getMetaDataInternal(cls, mustExist);
return getMetaDataInternal(cls, envLoader, mustExist);
}
}
private ClassMetaData getMetaDataInternal(Class<?> cls, boolean mustExist) {
private ClassMetaData getMetaDataInternal(Class<?> cls, ClassLoader envLoader, boolean mustExist) {
if (cls != null && DynamicPersistenceCapable.class.isAssignableFrom(cls))
cls = cls.getSuperclass();
@ -383,12 +397,12 @@ public class MetaDataRepository implements PCRegistry.RegisterClassListener, Con
if (cls != null && _implGen != null && _implGen.isImplType(cls))
cls = _implGen.toManagedInterface(cls);
ClassMetaData meta = getMetaDataInternal(cls);
ClassMetaData meta = getMetaDataInternal(cls, envLoader);
if (meta == null && mustExist) {
if (cls != null && !ImplHelper.isManagedType(_conf, cls))
throw new MetaDataException(_loc.get("no-meta-notpc", cls)).setFatal(false);
Set<String> pcNames = getPersistentTypeNames(false);
Set<String> pcNames = getPersistentTypeNames(false, envLoader);
if (pcNames != null && pcNames.size() > 0)
throw new MetaDataException(_loc.get("no-meta-types", cls, pcNames));
@ -409,22 +423,28 @@ public class MetaDataRepository implements PCRegistry.RegisterClassListener, Con
* if true, throws a {@link MetaDataException} if no metadata is found
* @see ClassMetaData#getTypeAlias
*/
public ClassMetaData getMetaData(String alias, boolean mustExist) {
public ClassMetaData getMetaData(String alias, ClassLoader envLoader, boolean mustExist) {
if (alias == null && mustExist)
throw new MetaDataException(_loc.get("no-alias-meta", alias, _aliases));
if (alias == null)
return null;
// check cache
processRegisteredClasses();
processRegisteredClasses(envLoader);
List<Class<?>> classList = _aliases.get(alias);
Set<String> pcNames = getPersistentTypeNames(false);
// multiple classes may have been defined with the same alias: we
// will filter by checking against the current list of the
// persistent types and filter based on which classes are loadable
// via the current environment's ClassLoader
Set<String> pcNames = getPersistentTypeNames(false, envLoader);
Class<?> cls = null;
for (int i = 0; classList != null && i < classList.size(); i++) {
Class<?> c = classList.get(i);
try {
Class<?> nc = Class.forName(c.getName(), false, _conf.getClassLoader());
// re-load the class in the current environment loader so
// that we can handle redeployment of the same class name
Class<?> nc = Class.forName(c.getName(), false, envLoader);
// if we have specified a list of persistent clases,
// also check to ensure that the class is in that list
@ -435,10 +455,14 @@ public class MetaDataRepository implements PCRegistry.RegisterClassListener, Con
break;
}
} catch (Throwable t) {
// this happens when the class is not loadable by
// the environment class loader, so it was probably
// listed elsewhere; also ignore linkage failures and
// other class loading problems
}
}
if (cls != null)
return getMetaData(cls, mustExist);
return getMetaData(cls, envLoader, mustExist);
// maybe this is some type we've seen but just isn't valid
if (_aliases.containsKey(alias)) {
@ -503,7 +527,7 @@ public class MetaDataRepository implements PCRegistry.RegisterClassListener, Con
/**
* Internal method to get the metadata for the given class, without resolving it.
*/
private ClassMetaData getMetaDataInternal(Class<?> cls) {
private ClassMetaData getMetaDataInternal(Class<?> cls, ClassLoader envLoader) {
if (cls == null)
return null;
@ -517,7 +541,7 @@ public class MetaDataRepository implements PCRegistry.RegisterClassListener, Con
// dev time so that user can manipulate persistent classes he's writing
// before adding them to the list
if ((_validate & VALIDATE_RUNTIME) != 0) {
Set<String> pcNames = getPersistentTypeNames(false);
Set<String> pcNames = getPersistentTypeNames(false, envLoader);
if (pcNames != null && !pcNames.contains(cls.getName()))
return meta;
}
@ -553,7 +577,7 @@ public class MetaDataRepository implements PCRegistry.RegisterClassListener, Con
if (mode != MODE_NONE) {
if (_log.isTraceEnabled())
_log.trace(_loc.get("load-cls", cls, toModeString(mode)));
_factory.load(cls, mode);
_factory.load(cls, mode, envLoader);
}
// check cache again
@ -660,7 +684,7 @@ public class MetaDataRepository implements PCRegistry.RegisterClassListener, Con
Class<?> sup = meta.getDescribedType().getSuperclass();
ClassMetaData supMeta;
while (sup != null && sup != Object.class) {
supMeta = getMetaData(sup, false);
supMeta = getMetaData(sup, meta.getEnvClassLoader(), false);
if (supMeta != null) {
meta.setPCSuperclass(sup);
meta.setPCSuperclassMetaData(supMeta);
@ -671,7 +695,7 @@ public class MetaDataRepository implements PCRegistry.RegisterClassListener, Con
if (meta.getDescribedType().isInterface()) {
Class<?>[] sups = meta.getDescribedType().getInterfaces();
for (int i = 0; i < sups.length; i++) {
supMeta = getMetaData(sups[i], false);
supMeta = getMetaData(sups[i], meta.getEnvClassLoader(), false);
if (supMeta != null) {
meta.setPCSuperclass(sup);
meta.setPCSuperclassMetaData(supMeta);
@ -687,7 +711,7 @@ public class MetaDataRepository implements PCRegistry.RegisterClassListener, Con
FieldMetaData[] fmds = meta.getDeclaredFields();
for (int i = 0; i < fmds.length; i++)
if (fmds[i].isPrimaryKey())
getMetaData(fmds[i].getDeclaredType(), false);
getMetaData(fmds[i].getDeclaredType(), meta.getEnvClassLoader(), false);
// resolve metadata; if we're not in the process of resolving
// others, this will return the set of interrelated metas that
@ -713,7 +737,7 @@ public class MetaDataRepository implements PCRegistry.RegisterClassListener, Con
if (_log.isTraceEnabled())
_log.trace(_loc.get("load-mapping", meta, toModeString(mode)));
try {
_factory.load(meta.getDescribedType(), mode);
_factory.load(meta.getDescribedType(), mode, meta.getEnvClassLoader());
} catch (RuntimeException re) {
removeMetaData(meta);
_errs.add(re);
@ -837,7 +861,7 @@ public class MetaDataRepository implements PCRegistry.RegisterClassListener, Con
ClassMetaData[] metas = (ClassMetaData[]) _metas.values().toArray(new ClassMetaData[_metas.size()]);
for (int i = 0; i < metas.length; i++)
if (metas[i] != null)
getMetaData(metas[i].getDescribedType(), true);
getMetaData(metas[i].getDescribedType(), metas[i].getEnvClassLoader(), true);
List<ClassMetaData> resolved = new ArrayList<ClassMetaData>(_metas.size());
for (ClassMetaData meta : _metas.values()) {
@ -1125,7 +1149,7 @@ public class MetaDataRepository implements PCRegistry.RegisterClassListener, Con
* @param mustExist
* if true, throws a {@link MetaDataException} if no metadata is found
*/
public ClassMetaData getMetaData(Object oid, boolean mustExist) {
public ClassMetaData getMetaData(Object oid, ClassLoader envLoader, boolean mustExist) {
if (oid == null && mustExist)
throw new MetaDataException(_loc.get("no-oid-meta", oid, "?", _oids.toString()));
if (oid == null)
@ -1133,14 +1157,14 @@ public class MetaDataRepository implements PCRegistry.RegisterClassListener, Con
if (oid instanceof OpenJPAId) {
Class<?> cls = ((OpenJPAId) oid).getType();
return getMetaData(cls, mustExist);
return getMetaData(cls, envLoader, mustExist);
}
// check cache
processRegisteredClasses();
processRegisteredClasses(envLoader);
Class<?> cls = _oids.get(oid.getClass());
if (cls != null)
return getMetaData(cls, mustExist);
return getMetaData(cls, envLoader, mustExist);
// maybe this is some type we've seen but just isn't valid
if (_oids.containsKey(oid.getClass())) {
@ -1152,10 +1176,10 @@ public class MetaDataRepository implements PCRegistry.RegisterClassListener, Con
// if still not match, register any classes that look similar to the
// oid class and check again
resolveIdentityClass(oid);
if (processRegisteredClasses().length > 0) {
if (processRegisteredClasses(envLoader).length > 0) {
cls = _oids.get(oid.getClass());
if (cls != null)
return getMetaData(cls, mustExist);
return getMetaData(cls, envLoader, mustExist);
}
// record that this is an invalid type
@ -1218,23 +1242,23 @@ public class MetaDataRepository implements PCRegistry.RegisterClassListener, Con
* @param mustExist
* if true, throws a {@link MetaDataException} if no metadata is found
*/
public ClassMetaData[] getImplementorMetaDatas(Class<?> cls, boolean mustExist) {
public ClassMetaData[] getImplementorMetaDatas(Class<?> cls, ClassLoader envLoader, boolean mustExist) {
if (cls == null && mustExist)
throw new MetaDataException(_loc.get("no-meta", cls));
if (cls == null)
return EMPTY_METAS;
// get impls of given interface / abstract class
loadRegisteredClassMetaData();
loadRegisteredClassMetaData(envLoader);
Collection<Class<?>> vals = _impls.get(cls);
ClassMetaData[] mapped = null;
if (vals != null) {
if (_locking) {
synchronized (vals) {
mapped = getImplementorMetaDatasInternal(vals, mustExist);
mapped = getImplementorMetaDatasInternal(vals, envLoader, mustExist);
}
} else {
mapped = getImplementorMetaDatasInternal(vals, mustExist);
mapped = getImplementorMetaDatasInternal(vals, envLoader, mustExist);
}
}
@ -1245,11 +1269,12 @@ public class MetaDataRepository implements PCRegistry.RegisterClassListener, Con
return mapped;
}
private ClassMetaData[] getImplementorMetaDatasInternal(Collection<Class<?>> classes, boolean mustExist) {
private ClassMetaData[] getImplementorMetaDatasInternal(Collection<Class<?>> classes, ClassLoader envLoader,
boolean mustExist) {
Collection<ClassMetaData> mapped = new ArrayList<ClassMetaData>(classes.size());
ClassMetaData meta = null;
for (Class<?> c : classes) {
meta = getMetaData(c, true);
meta = getMetaData(c, envLoader, true);
if (meta.isMapped() || meta.getMappedPCSubclassMetaDatas().length > 0) {
mapped.add(meta);
}
@ -1432,18 +1457,18 @@ public class MetaDataRepository implements PCRegistry.RegisterClassListener, Con
* @param envLoader
* the class loader to use, or null for default
*/
public Set<String> getPersistentTypeNames(boolean devpath) {
public Set<String> getPersistentTypeNames(boolean devpath, ClassLoader envLoader) {
if (_locking) {
synchronized (this) {
return getPersistentTypeNamesInternal(devpath);
return getPersistentTypeNamesInternal(devpath, envLoader);
}
} else {
return getPersistentTypeNamesInternal(devpath);
return getPersistentTypeNamesInternal(devpath, envLoader);
}
}
private Set<String> getPersistentTypeNamesInternal(boolean devpath) {
return _factory.getPersistentTypeNames(devpath);
private Set<String> getPersistentTypeNamesInternal(boolean devpath, ClassLoader envLoader) {
return _factory.getPersistentTypeNames(devpath, envLoader);
}
/**
* Load the persistent classes named in configuration.
@ -1457,8 +1482,8 @@ public class MetaDataRepository implements PCRegistry.RegisterClassListener, Con
* @param envLoader the class loader to use, or null for default
* @return the loaded classes, or empty collection if none
*/
public Collection<Class<?>> loadPersistentTypes(boolean devpath) {
return loadPersistentTypes(devpath, false);
public Collection<Class<?>> loadPersistentTypes(boolean devpath, ClassLoader envLoader) {
return loadPersistentTypes(devpath, envLoader, false);
}
/**
* Load the persistent classes named in configuration. This ensures that all subclasses and
@ -1475,18 +1500,19 @@ public class MetaDataRepository implements PCRegistry.RegisterClassListener, Con
* raise an exception.
* @return the loaded classes, or empty collection if none
*/
public Collection<Class<?>> loadPersistentTypes(boolean devpath, boolean mustExist) {
public Collection<Class<?>> loadPersistentTypes(boolean devpath, ClassLoader envLoader, boolean mustExist) {
if (_locking) {
synchronized (this) {
return loadPersistentTypesInternal(devpath, mustExist);
return loadPersistentTypesInternal(devpath, envLoader, mustExist);
}
} else {
return loadPersistentTypesInternal(devpath, mustExist);
return loadPersistentTypesInternal(devpath, envLoader, mustExist);
}
}
private Collection<Class<?>> loadPersistentTypesInternal(boolean devpath, boolean mustExist) {
Set<String> names = getPersistentTypeNames(devpath);
private Collection<Class<?>> loadPersistentTypesInternal(boolean devpath, ClassLoader envLoader,
boolean mustExist) {
Set<String> names = getPersistentTypeNames(devpath, envLoader);
if (names == null || names.isEmpty()) {
if (!mustExist)
return Collections.emptyList();
@ -1495,10 +1521,11 @@ public class MetaDataRepository implements PCRegistry.RegisterClassListener, Con
}
// attempt to load classes so that they get processed
ClassLoader clsLoader = _conf.getClassResolverInstance().getClassLoader(getClass(), envLoader);
List<Class<?>> classes = new ArrayList<Class<?>>(names.size());
Class<?> cls;
for (String className : names) {
cls = classForName(className);
cls = classForName(className, clsLoader);
if (_factory.isMetaClass(cls)) {
setMetaModel(cls);
continue;
@ -1509,7 +1536,7 @@ public class MetaDataRepository implements PCRegistry.RegisterClassListener, Con
// if the class is an interface, load its metadata to kick
// off the impl generator
if (cls.isInterface())
getMetaData(cls, false);
getMetaData(cls, clsLoader, false);
} else if (cls == null && mustExist) {
throw new MetaDataException(_loc.get("eager-class-not-found", className));
}
@ -1520,8 +1547,7 @@ public class MetaDataRepository implements PCRegistry.RegisterClassListener, Con
/**
* Return the class for the given name, or null if not loadable.
*/
private Class<?> classForName(String name) {
ClassLoader loader = _conf.getClassLoader();
private Class<?> classForName(String name, ClassLoader loader) {
try {
return Class.forName(name, true, loader);
} catch (Exception e) {
@ -1577,11 +1603,11 @@ public class MetaDataRepository implements PCRegistry.RegisterClassListener, Con
/**
* Parses the metadata for all registered classes.
*/
private void loadRegisteredClassMetaData() {
Class<?>[] reg = processRegisteredClasses();
private void loadRegisteredClassMetaData(ClassLoader envLoader) {
Class<?>[] reg = processRegisteredClasses(envLoader);
for (int i = 0; i < reg.length; i++) {
try {
getMetaData(reg[i], false);
getMetaData(reg[i], envLoader, false);
} catch (MetaDataException me) {
if (_log.isWarnEnabled())
_log.warn(me);
@ -1592,7 +1618,7 @@ public class MetaDataRepository implements PCRegistry.RegisterClassListener, Con
/**
* Updates our datastructures with the latest registered classes.
*/
Class<?>[] processRegisteredClasses() {
Class<?>[] processRegisteredClasses(ClassLoader envLoader) {
if (_registered.isEmpty())
return EMPTY_CLASSES;
@ -1604,7 +1630,7 @@ public class MetaDataRepository implements PCRegistry.RegisterClassListener, Con
_registered.clear();
}
Collection<String> pcNames = getPersistentTypeNames(false);
Collection<String> pcNames = getPersistentTypeNames(false, envLoader);
Collection<Class<?>> failed = null;
for (int i = 0; i < reg.length; i++) {
// don't process types that aren't listed by the user; may belong
@ -1887,29 +1913,30 @@ public class MetaDataRepository implements PCRegistry.RegisterClassListener, Con
/**
* Return query metadata for the given class, name, and classloader.
*/
public QueryMetaData getQueryMetaData(Class<?> cls, String name, boolean mustExist) {
public QueryMetaData getQueryMetaData(Class<?> cls, String name, ClassLoader envLoader, boolean mustExist) {
if (_locking) {
synchronized (this) {
return getQueryMetaDataInternal(cls, name, mustExist);
return getQueryMetaDataInternal(cls, name, envLoader, mustExist);
}
} else {
return getQueryMetaDataInternal(cls, name, mustExist);
return getQueryMetaDataInternal(cls, name, envLoader, mustExist);
}
}
private QueryMetaData getQueryMetaDataInternal(Class<?> cls, String name, boolean mustExist) {
QueryMetaData meta = getQueryMetaDataInternal(cls, name);
private QueryMetaData getQueryMetaDataInternal(Class<?> cls, String name, ClassLoader envLoader,
boolean mustExist) {
QueryMetaData meta = getQueryMetaDataInternal(cls, name, envLoader);
if (meta == null) {
// load all the metadatas for all the known classes so that
// query names are seen and registered
resolveAll();
meta = getQueryMetaDataInternal(cls, name);
resolveAll(envLoader);
meta = getQueryMetaDataInternal(cls, name, envLoader);
}
if (meta == null && mustExist) {
if (cls == null) {
throw new MetaDataException(_loc.get("no-named-query-null-class",
getPersistentTypeNames(false), name));
throw new MetaDataException(_loc.get("no-named-query-null-class", getPersistentTypeNames(false,
envLoader), name));
} else {
throw new MetaDataException(_loc.get("no-named-query", cls, name));
}
@ -1921,17 +1948,17 @@ public class MetaDataRepository implements PCRegistry.RegisterClassListener, Con
/**
* Resolve all known metadata classes.
*/
private void resolveAll() {
Collection<Class<?>> types = loadPersistentTypes(false);
private void resolveAll(ClassLoader envLoader) {
Collection<Class<?>> types = loadPersistentTypes(false, envLoader);
for (Class<?> c : types) {
getMetaData(c, false);
getMetaData(c, envLoader, false);
}
}
/**
* Return query metadata for the given class, name, and classloader.
*/
private QueryMetaData getQueryMetaDataInternal(Class<?> cls, String name) {
private QueryMetaData getQueryMetaDataInternal(Class<?> cls, String name, ClassLoader envLoader) {
if (name == null)
return null;
QueryMetaData qm = null;
@ -1947,7 +1974,7 @@ public class MetaDataRepository implements PCRegistry.RegisterClassListener, Con
return qm;
// get metadata for class, which will find queries in metadata file
if (cls != null && getMetaData(cls, false) != null) {
if (cls != null && getMetaData(cls, envLoader, false) != null) {
qm = _queries.get(key);
if (qm != null)
return qm;
@ -1957,10 +1984,10 @@ public class MetaDataRepository implements PCRegistry.RegisterClassListener, Con
// see if factory can figure out a scope for this query
if (cls == null)
cls = _factory.getQueryScope(name);
cls = _factory.getQueryScope(name, envLoader);
// not in cache; load
_factory.load(cls, MODE_QUERY);
_factory.load(cls, MODE_QUERY, envLoader);
return _queries.get(key);
}
@ -2089,18 +2116,18 @@ public class MetaDataRepository implements PCRegistry.RegisterClassListener, Con
/**
* Return sequence metadata for the given name and classloader.
*/
public SequenceMetaData getSequenceMetaData(String name, boolean mustExist) {
public SequenceMetaData getSequenceMetaData(String name, ClassLoader envLoader, boolean mustExist) {
if (_locking) {
synchronized (this) {
return getSequenceMetaDataInternal(name, mustExist);
return getSequenceMetaDataInternal(name, envLoader, mustExist);
}
} else {
return getSequenceMetaDataInternal(name, mustExist);
return getSequenceMetaDataInternal(name, envLoader, mustExist);
}
}
private SequenceMetaData getSequenceMetaDataInternal(String name, boolean mustExist) {
SequenceMetaData meta = getSequenceMetaDataInternal(name);
private SequenceMetaData getSequenceMetaDataInternal(String name, ClassLoader envLoader, boolean mustExist) {
SequenceMetaData meta = getSequenceMetaDataInternal(name, envLoader);
if (meta == null && SequenceMetaData.NAME_SYSTEM.equals(name)) {
if (_sysSeq == null)
_sysSeq = newSequenceMetaData(name);
@ -2119,7 +2146,7 @@ public class MetaDataRepository implements PCRegistry.RegisterClassListener, Con
// try with given name
MetaDataException e = null;
try {
SequenceMetaData seq = getSequenceMetaData(name, mustExist);
SequenceMetaData seq = getSequenceMetaData(name, context.getEnvClassLoader(), mustExist);
if (seq != null)
return seq;
} catch (MetaDataException mde) {
@ -2136,7 +2163,7 @@ public class MetaDataRepository implements PCRegistry.RegisterClassListener, Con
// try with qualified name
name = Strings.getPackageName(context.getDescribedType()) + "." + name;
try {
return getSequenceMetaData(name, mustExist);
return getSequenceMetaData(name, context.getEnvClassLoader(), mustExist);
} catch (MetaDataException mde) {
// throw original exception
if (e != null)
@ -2148,7 +2175,7 @@ public class MetaDataRepository implements PCRegistry.RegisterClassListener, Con
/**
* Return sequence metadata for the given name and classloader.
*/
private SequenceMetaData getSequenceMetaDataInternal(String name) {
private SequenceMetaData getSequenceMetaDataInternal(String name, ClassLoader envLoader) {
if (name == null)
return null;
@ -2157,7 +2184,7 @@ public class MetaDataRepository implements PCRegistry.RegisterClassListener, Con
if (meta == null) {
// load metadata for registered classes to hopefully find sequence
// definition
loadRegisteredClassMetaData();
loadRegisteredClassMetaData(envLoader);
meta = _seqs.get(name);
}
return meta;

Some files were not shown because too many files have changed in this diff Show More