diff --git a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/ant/MappingToolTask.java b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/ant/MappingToolTask.java index ceda9be51..d5e311837 100644 --- a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/ant/MappingToolTask.java +++ b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/ant/MappingToolTask.java @@ -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; } diff --git a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/ant/ReverseMappingToolTask.java b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/ant/ReverseMappingToolTask.java index db542379d..174ddedaf 100644 --- a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/ant/ReverseMappingToolTask.java +++ b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/ant/ReverseMappingToolTask.java @@ -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); diff --git a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/ant/SchemaToolTask.java b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/ant/SchemaToolTask.java index 1b59b60c1..64944a4f6 100644 --- a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/ant/SchemaToolTask.java +++ b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/ant/SchemaToolTask.java @@ -131,8 +131,7 @@ public class SchemaToolTask this.file = file; } - @Override - protected JDBCConfigurationImpl newConfiguration() { + protected ConfigurationImpl newConfiguration() { return new JDBCConfigurationImpl(); } diff --git a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/conf/JDBCConfigurationImpl.java b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/conf/JDBCConfigurationImpl.java index 543982d7c..f511705cb 100644 --- a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/conf/JDBCConfigurationImpl.java +++ b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/conf/JDBCConfigurationImpl.java @@ -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 jdbcListenerPlugins; - public PluginListValue connectionDecoratorPlugins; - public PluginValue dbdictionaryPlugin; - public ObjectValue updateManagerPlugin; - public ObjectValue schemaFactoryPlugin; - public ObjectValue sqlFactoryPlugin; - public ObjectValue mappingDefaultsPlugin; - public PluginValue 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 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) { diff --git a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/conf/MappingFactoryValue.java b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/conf/MappingFactoryValue.java index 47fbfc9f3..b03d7f60d 100644 --- a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/conf/MappingFactoryValue.java +++ b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/conf/MappingFactoryValue.java @@ -36,15 +36,16 @@ import org.apache.openjpa.meta.MetaDataFactory; * @nojavadoc */ public class MappingFactoryValue - extends PluginValue { + 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 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 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; + } } diff --git a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/conf/MappingRepositoryValue.java b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/conf/MappingRepositoryValue.java index 438f72dc6..660073cb6 100644 --- a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/conf/MappingRepositoryValue.java +++ b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/conf/MappingRepositoryValue.java @@ -36,19 +36,20 @@ import serp.util.Strings; * @nojavadoc */ public class MappingRepositoryValue - extends PluginValue { + 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 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); } } } diff --git a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/kernel/ClassTableJDBCSeq.java b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/kernel/ClassTableJDBCSeq.java index 00e588081..8ad278789 100644 --- a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/kernel/ClassTableJDBCSeq.java +++ b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/kernel/ClassTableJDBCSeq.java @@ -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 { diff --git a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/kernel/GenericResultObjectProvider.java b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/kernel/GenericResultObjectProvider.java index 96f1a3630..46294b9e8 100644 --- a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/kernel/GenericResultObjectProvider.java +++ b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/kernel/GenericResultObjectProvider.java @@ -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); } /** diff --git a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/kernel/JDBCBrokerFactory.java b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/kernel/JDBCBrokerFactory.java index 3f796a757..71f97afda 100644 --- a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/kernel/JDBCBrokerFactory.java +++ b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/kernel/JDBCBrokerFactory.java @@ -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 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> classes = repo.loadPersistentTypes(false); + Collection> 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()); } } diff --git a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/kernel/JDBCStoreManager.java b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/kernel/JDBCStoreManager.java index 6ee4d7cd3..2ce937bc6 100644 --- a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/kernel/JDBCStoreManager.java +++ b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/kernel/JDBCStoreManager.java @@ -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; } diff --git a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/kernel/PreparedQueryImpl.java b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/kernel/PreparedQueryImpl.java index bbbafeda9..540b9fae6 100644 --- a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/kernel/PreparedQueryImpl.java +++ b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/kernel/PreparedQueryImpl.java @@ -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[]) { diff --git a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/kernel/PreparedStatementManagerImpl.java b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/kernel/PreparedStatementManagerImpl.java index a6edadd66..d3cabcad1 100644 --- a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/kernel/PreparedStatementManagerImpl.java +++ b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/kernel/PreparedStatementManagerImpl.java @@ -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) {} diff --git a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/kernel/SQLStoreQuery.java b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/kernel/SQLStoreQuery.java index 6011065a5..bdd17e99e 100644 --- a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/kernel/SQLStoreQuery.java +++ b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/kernel/SQLStoreQuery.java @@ -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; diff --git a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/kernel/exps/CollectionParam.java b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/kernel/exps/CollectionParam.java index 6472f0569..5c39c5b82 100644 --- a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/kernel/exps/CollectionParam.java +++ b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/kernel/exps/CollectionParam.java @@ -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); } } } diff --git a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/kernel/exps/InstanceofExpression.java b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/kernel/exps/InstanceofExpression.java index 7a71abe1d..430461641 100644 --- a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/kernel/exps/InstanceofExpression.java +++ b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/kernel/exps/InstanceofExpression.java @@ -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)) diff --git a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/kernel/exps/Param.java b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/kernel/exps/Param.java index d76819ff3..3cb0bea83 100644 --- a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/kernel/exps/Param.java +++ b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/kernel/exps/Param.java @@ -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; diff --git a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/meta/ClassMapping.java b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/meta/ClassMapping.java index 0c9e8b7f3..f565fab8f 100644 --- a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/meta/ClassMapping.java +++ b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/meta/ClassMapping.java @@ -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 } diff --git a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/meta/FieldMapping.java b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/meta/FieldMapping.java index ad3e52b3d..68cf48392 100644 --- a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/meta/FieldMapping.java +++ b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/meta/FieldMapping.java @@ -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); diff --git a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/meta/MappingRepository.java b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/meta/MappingRepository.java index 331a47f37..64dc05340 100644 --- a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/meta/MappingRepository.java +++ b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/meta/MappingRepository.java @@ -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> classes = loadPersistentTypes(false); + Collection> classes = loadPersistentTypes(false, + mapping.getEnvClassLoader()); Class cls; for (Iterator> itr = classes.iterator(); itr.hasNext();) { cls = itr.next(); diff --git a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/meta/MappingTool.java b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/meta/MappingTool.java index 42b2f0483..7e42e9b15 100644 --- a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/meta/MappingTool.java +++ b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/meta/MappingTool.java @@ -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>(); 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]); diff --git a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/meta/MetaDataPlusMappingFactory.java b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/meta/MetaDataPlusMappingFactory.java index 29a3b1000..8dc133d3a 100644 --- a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/meta/MetaDataPlusMappingFactory.java +++ b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/meta/MetaDataPlusMappingFactory.java @@ -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() { diff --git a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/meta/QueryResultMapping.java b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/meta/QueryResultMapping.java index d9795eed0..e303bc4fc 100644 --- a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/meta/QueryResultMapping.java +++ b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/meta/QueryResultMapping.java @@ -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; } diff --git a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/meta/ReverseMappingTool.java b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/meta/ReverseMappingTool.java index 462d82123..028dfdfed 100644 --- a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/meta/ReverseMappingTool.java +++ b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/meta/ReverseMappingTool.java @@ -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); } diff --git a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/meta/strats/ClassNameDiscriminatorStrategy.java b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/meta/strats/ClassNameDiscriminatorStrategy.java index b423bab16..2c81abe64 100644 --- a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/meta/strats/ClassNameDiscriminatorStrategy.java +++ b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/meta/strats/ClassNameDiscriminatorStrategy.java @@ -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()); + } } diff --git a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/meta/strats/RelationStrategies.java b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/meta/strats/RelationStrategies.java index fb90a98d5..4bc70e378 100644 --- a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/meta/strats/RelationStrategies.java +++ b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/meta/strats/RelationStrategies.java @@ -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", diff --git a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/meta/strats/UntypedPCValueHandler.java b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/meta/strats/UntypedPCValueHandler.java index 06d7fc453..0cd1a3f96 100644 --- a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/meta/strats/UntypedPCValueHandler.java +++ b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/meta/strats/UntypedPCValueHandler.java @@ -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); diff --git a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/schema/DBCPDriverDataSource.java b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/schema/DBCPDriverDataSource.java index 55cc36679..62f7e4092 100644 --- a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/schema/DBCPDriverDataSource.java +++ b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/schema/DBCPDriverDataSource.java @@ -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); } diff --git a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/schema/DataSourceFactory.java b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/schema/DataSourceFactory.java index e8d100abb..60be30506 100644 --- a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/schema/DataSourceFactory.java +++ b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/schema/DataSourceFactory.java @@ -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) { diff --git a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/schema/FileSchemaFactory.java b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/schema/FileSchemaFactory.java index 38ef66e97..672b92c5c 100644 --- a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/schema/FileSchemaFactory.java +++ b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/schema/FileSchemaFactory.java @@ -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); } diff --git a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/schema/SchemaTool.java b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/schema/SchemaTool.java index d95dc43f5..dd1b197d8 100644 --- a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/schema/SchemaTool.java +++ b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/schema/SchemaTool.java @@ -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; diff --git a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/schema/XMLSchemaParser.java b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/schema/XMLSchemaParser.java index 196ec00b6..d5d1a0e0e 100644 --- a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/schema/XMLSchemaParser.java +++ b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/schema/XMLSchemaParser.java @@ -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); diff --git a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/sql/OracleDictionary.java b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/sql/OracleDictionary.java index 87fa19210..36568040e 100644 --- a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/sql/OracleDictionary.java +++ b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/sql/OracleDictionary.java @@ -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) { diff --git a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/sql/PostgresDictionary.java b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/sql/PostgresDictionary.java index 73603e3be..e05d5c244 100644 --- a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/sql/PostgresDictionary.java +++ b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/sql/PostgresDictionary.java @@ -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); diff --git a/openjpa-jest/src/main/java/org/apache/openjpa/persistence/jest/JESTContext.java b/openjpa-jest/src/main/java/org/apache/openjpa/persistence/jest/JESTContext.java index 67d8aa434..5f8c9a8dd 100644 --- a/openjpa-jest/src/main/java/org/apache/openjpa/persistence/jest/JESTContext.java +++ b/openjpa-jest/src/main/java/org/apache/openjpa/persistence/jest/JESTContext.java @@ -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); } /** diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/abstractstore/AbstractStoreBrokerFactory.java b/openjpa-kernel/src/main/java/org/apache/openjpa/abstractstore/AbstractStoreBrokerFactory.java index 54d82d6d7..9e815c80c 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/abstractstore/AbstractStoreBrokerFactory.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/abstractstore/AbstractStoreBrokerFactory.java @@ -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); diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/abstractstore/AbstractStoreManager.java b/openjpa-kernel/src/main/java/org/apache/openjpa/abstractstore/AbstractStoreManager.java index 054bd0db1..2006e7e9d 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/abstractstore/AbstractStoreManager.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/abstractstore/AbstractStoreManager.java @@ -244,7 +244,7 @@ public abstract class AbstractStoreManager * states, and delegates to * {@link #flush(Collection,Collection,Collection,Collection,Collection)}. */ - public Collection flush(Collection sms) { + public Collection flush(Collection sms) { // break down state managers by state; initialize as empty lists; // use constants for efficiency Collection pNew = new LinkedList(); diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/ant/ApplicationIdToolTask.java b/openjpa-kernel/src/main/java/org/apache/openjpa/ant/ApplicationIdToolTask.java index 0e094bd56..9232004a1 100755 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/ant/ApplicationIdToolTask.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/ant/ApplicationIdToolTask.java @@ -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 ()); } } diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/ant/PCEnhancerTask.java b/openjpa-kernel/src/main/java/org/apache/openjpa/ant/PCEnhancerTask.java index b7c5fa246..f82fda0ca 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/ant/PCEnhancerTask.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/ant/PCEnhancerTask.java @@ -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 ()); } } diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/conf/AutoDetachValue.java b/openjpa-kernel/src/main/java/org/apache/openjpa/conf/AutoDetachValue.java index 77eabe846..57c5f390e 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/conf/AutoDetachValue.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/conf/AutoDetachValue.java @@ -58,6 +58,10 @@ class AutoDetachValue setAliasListComprehensive(true); } + public Class getValueType() { + return String[].class; + } + public void setConstant(int flags) { _flags = flags; } diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/conf/BrokerFactoryValue.java b/openjpa-kernel/src/main/java/org/apache/openjpa/conf/BrokerFactoryValue.java index c64f63078..b76434532 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/conf/BrokerFactoryValue.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/conf/BrokerFactoryValue.java @@ -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 { + 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); } } diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/conf/BrokerValue.java b/openjpa-kernel/src/main/java/org/apache/openjpa/conf/BrokerValue.java index ec849a17a..ee0db6ca0 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/conf/BrokerValue.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/conf/BrokerValue.java @@ -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 { + 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 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; } } diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/conf/CacheMarshallerImpl.java b/openjpa-kernel/src/main/java/org/apache/openjpa/conf/CacheMarshallerImpl.java index 8a94e2f36..93169177e 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/conf/CacheMarshallerImpl.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/conf/CacheMarshallerImpl.java @@ -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(); ) diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/conf/CacheMarshallersValue.java b/openjpa-kernel/src/main/java/org/apache/openjpa/conf/CacheMarshallersValue.java index bea3dd57b..6869e9fdf 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/conf/CacheMarshallersValue.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/conf/CacheMarshallersValue.java @@ -32,28 +32,33 @@ import org.apache.openjpa.lib.conf.Configuration; * * @since 1.1.0 */ -public class CacheMarshallersValue extends PluginListValue { +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 _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(); for (int i = 0; i < ms.length; i++) { @@ -109,7 +114,7 @@ public class CacheMarshallersValue extends PluginListValue { protected synchronized void initialize() { if (!_initialized) { - instantiate(_conf); + instantiate(CacheMarshaller.class, _conf); _initialized = true; } } diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/conf/MetaDataCacheMaintenance.java b/openjpa-kernel/src/main/java/org/apache/openjpa/conf/MetaDataCacheMaintenance.java index 7c4843480..854f1a648 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/conf/MetaDataCacheMaintenance.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/conf/MetaDataCacheMaintenance.java @@ -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(); diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/conf/MetaDataRepositoryValue.java b/openjpa-kernel/src/main/java/org/apache/openjpa/conf/MetaDataRepositoryValue.java index e85708ea4..c027a5271 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/conf/MetaDataRepositoryValue.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/conf/MetaDataRepositoryValue.java @@ -32,12 +32,12 @@ import org.apache.openjpa.meta.MetaDataRepository; * @since 1.1.0 */ public class MetaDataRepositoryValue - extends PluginValue { + 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; } diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/conf/OpenJPAConfiguration.java b/openjpa-kernel/src/main/java/org/apache/openjpa/conf/OpenJPAConfiguration.java index 47c320103..878125e77 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/conf/OpenJPAConfiguration.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/conf/OpenJPAConfiguration.java @@ -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(); /** diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/conf/OpenJPAConfigurationImpl.java b/openjpa-kernel/src/main/java/org/apache/openjpa/conf/OpenJPAConfigurationImpl.java index 21f30940b..98e2d6886 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/conf/OpenJPAConfigurationImpl.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/conf/OpenJPAConfigurationImpl.java @@ -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 classResolverPlugin; + public ObjectValue classResolverPlugin; public BrokerValue brokerPlugin; - public ObjectValue dataCachePlugin; - public ObjectValue dataCacheManagerPlugin; - public ObjectValue auditorPlugin; - public ObjectValue cacheDistributionPolicyPlugin; + public ObjectValue dataCachePlugin; + public ObjectValue dataCacheManagerPlugin; + public ObjectValue auditorPlugin; + public ObjectValue cacheDistributionPolicyPlugin; public IntValue dataCacheTimeout; - public ObjectValue queryCachePlugin; + public ObjectValue queryCachePlugin; public BooleanValue dynamicDataStructs; - public ObjectValue 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 seqPlugin; - public PluginListValue filterListenerPlugins; - public PluginListValue aggregateListenerPlugins; + public ObjectValue seqPlugin; + public PluginListValue filterListenerPlugins; + public PluginListValue aggregateListenerPlugins; public BooleanValue retryClassRegistration; - public ObjectValue proxyManagerPlugin; + public ObjectValue proxyManagerPlugin; public StringValue connectionUserName; public StringValue connectionPassword; - public PluginValue encryptionProvider; + public PluginValue encryptionProvider; public StringValue connectionURL; public StringValue connectionDriverName; - public ObjectValue 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 connectionFactory2; + public ObjectValue connectionFactory2; public StringValue connectionFactory2Name; public StringValue connectionFactory2Properties; public BooleanValue optimistic; public IntValue autoClear; public BooleanValue retainState; public IntValue restoreState; - public ObjectValue detachStatePlugin; + public ObjectValue detachStatePlugin; public BooleanValue ignoreChanges; public BooleanValue nontransactionalRead; public BooleanValue nontransactionalWrite; public BooleanValue refreshFromDataCache; public BooleanValue multithreaded; public StringValue mapping; - public PluginValue metaFactoryPlugin; + public PluginValue metaFactoryPlugin; public MetaDataRepositoryValue metaRepositoryPlugin; - public ObjectValue lockManagerPlugin; - public ObjectValue inverseManagerPlugin; - public ObjectValue savepointManagerPlugin; - public ObjectValue orphanedKeyPlugin; - public ObjectValue compatibilityPlugin; - public ObjectValue 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 preparedQueryCachePlugin; - public PluginValue finderCachePlugin; - public ObjectValue specification; + public PluginValue preparedQueryCachePlugin; + public PluginValue finderCachePlugin; + public ObjectValue specification; public StringValue validationMode; - public ObjectValue validationFactory; - public ObjectValue validator; - public ObjectValue 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; - public PluginListValue 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; } diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/conf/QueryCompilationCacheValue.java b/openjpa-kernel/src/main/java/org/apache/openjpa/conf/QueryCompilationCacheValue.java index 7bed3f894..c7546b4ab 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/conf/QueryCompilationCacheValue.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/conf/QueryCompilationCacheValue.java @@ -36,7 +36,7 @@ import org.apache.openjpa.util.CacheMap; * @nojavadoc */ public class QueryCompilationCacheValue - extends PluginValue { + 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) diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/conf/RemoteCommitProviderValue.java b/openjpa-kernel/src/main/java/org/apache/openjpa/conf/RemoteCommitProviderValue.java index a369b0118..58a371283 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/conf/RemoteCommitProviderValue.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/conf/RemoteCommitProviderValue.java @@ -35,7 +35,7 @@ import org.apache.openjpa.lib.util.Options; * @nojavadoc */ public class RemoteCommitProviderValue - extends PluginValue { + 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); diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/conf/SeqValue.java b/openjpa-kernel/src/main/java/org/apache/openjpa/conf/SeqValue.java index d671ffbaa..d04108b5d 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/conf/SeqValue.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/conf/SeqValue.java @@ -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 { + 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]); diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/conf/SpecificationPlugin.java b/openjpa-kernel/src/main/java/org/apache/openjpa/conf/SpecificationPlugin.java index 8f02471ea..f3a071d63 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/conf/SpecificationPlugin.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/conf/SpecificationPlugin.java @@ -33,17 +33,22 @@ import org.apache.openjpa.util.UserException; * @author Pinaki Poddar * */ -public class SpecificationPlugin extends ObjectValue 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 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); } diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/datacache/AbstractQueryCache.java b/openjpa-kernel/src/main/java/org/apache/openjpa/datacache/AbstractQueryCache.java index 4a3085946..760386af1 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/datacache/AbstractQueryCache.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/datacache/AbstractQueryCache.java @@ -101,7 +101,11 @@ public abstract class AbstractQueryCache entityTimestampMap = new ConcurrentHashMap(); // 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()); } diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/datacache/Caches.java b/openjpa-kernel/src/main/java/org/apache/openjpa/datacache/Caches.java index bef8a9551..f5e532a4e 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/datacache/Caches.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/datacache/Caches.java @@ -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) { diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/datacache/DataCacheManager.java b/openjpa-kernel/src/main/java/org/apache/openjpa/datacache/DataCacheManager.java index 65af2cdbf..3e07c56b5 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/datacache/DataCacheManager.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/datacache/DataCacheManager.java @@ -43,8 +43,8 @@ public interface DataCacheManager { /** * Initialize the manager, supplying the cache configuration. */ - public void initialize(OpenJPAConfiguration conf, ObjectValue dataCache, - ObjectValue queryCache); + public void initialize(OpenJPAConfiguration conf, ObjectValue dataCache, + ObjectValue queryCache); /** * Return the system-wide data cache, or null if caching is not enabled. diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/datacache/DataCacheManagerImpl.java b/openjpa-kernel/src/main/java/org/apache/openjpa/datacache/DataCacheManagerImpl.java index 23de4be5b..10b39c76d 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/datacache/DataCacheManagerImpl.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/datacache/DataCacheManagerImpl.java @@ -57,13 +57,12 @@ public class DataCacheManagerImpl private Set _includedTypes; private Set _excludedTypes; - public void initialize(OpenJPAConfiguration conf, ObjectValue dataCache, - ObjectValue 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; diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/datacache/DataCacheStoreManager.java b/openjpa-kernel/src/main/java/org/apache/openjpa/datacache/DataCacheStoreManager.java index a5506c5a1..6d8aa2369 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/datacache/DataCacheStoreManager.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/datacache/DataCacheStoreManager.java @@ -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 flush(Collection states) { + public Collection flush(Collection states) { Collection exceps = super.flush(states); // if there were errors evict bad instances and don't record changes diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/datacache/PartitionedDataCache.java b/openjpa-kernel/src/main/java/org/apache/openjpa/datacache/PartitionedDataCache.java index bb56cf12f..fd1d8ae54 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/datacache/PartitionedDataCache.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/datacache/PartitionedDataCache.java @@ -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) 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 partitions = new PluginListValue(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)); diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/datacache/QueryKey.java b/openjpa-kernel/src/main/java/org/apache/openjpa/datacache/QueryKey.java index 82534d6ce..f5b6ed0be 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/datacache/QueryKey.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/datacache/QueryKey.java @@ -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(); diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/ee/InvocationManagedRuntime.java b/openjpa-kernel/src/main/java/org/apache/openjpa/ee/InvocationManagedRuntime.java index 6c43dd45f..9324439ef 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/ee/InvocationManagedRuntime.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/ee/InvocationManagedRuntime.java @@ -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); } diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/enhance/ApplicationIdTool.java b/openjpa-kernel/src/main/java/org/apache/openjpa/enhance/ApplicationIdTool.java index 12ce08428..669214a0f 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/enhance/ApplicationIdTool.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/enhance/ApplicationIdTool.java @@ -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); diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/enhance/ClassRedefiner.java b/openjpa-kernel/src/main/java/org/apache/openjpa/enhance/ClassRedefiner.java index cd03baf3e..4f1956fdc 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/enhance/ClassRedefiner.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/enhance/ClassRedefiner.java @@ -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,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) { diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/enhance/CodeGenerator.java b/openjpa-kernel/src/main/java/org/apache/openjpa/enhance/CodeGenerator.java index 3e3e2ffc0..981937aa6 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/enhance/CodeGenerator.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/enhance/CodeGenerator.java @@ -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)); } /** diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/enhance/InstrumentationFactory.java b/openjpa-kernel/src/main/java/org/apache/openjpa/enhance/InstrumentationFactory.java index f85f76add..56b6a761e 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/enhance/InstrumentationFactory.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/enhance/InstrumentationFactory.java @@ -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() { 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.
* 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
* 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 } diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/enhance/ManagedClassSubclasser.java b/openjpa-kernel/src/main/java/org/apache/openjpa/enhance/ManagedClassSubclasser.java index 306593bfa..4a27b78e1 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/enhance/ManagedClassSubclasser.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/enhance/ManagedClassSubclasser.java @@ -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> prepareUnenhancedClasses( final OpenJPAConfiguration conf, - final Collection> classes) { + final Collection> 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); } diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/enhance/PCClassFileTransformer.java b/openjpa-kernel/src/main/java/org/apache/openjpa/enhance/PCClassFileTransformer.java index 5fa0694e9..b0f052e19 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/enhance/PCClassFileTransformer.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/enhance/PCClassFileTransformer.java @@ -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 _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; diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/enhance/PCEnhancer.java b/openjpa-kernel/src/main/java/org/apache/openjpa/enhance/PCEnhancer.java index e0122f304..b16b83716 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/enhance/PCEnhancer.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/enhance/PCEnhancer.java @@ -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); diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/enhance/PCEnhancerAgent.java b/openjpa-kernel/src/main/java/org/apache/openjpa/enhance/PCEnhancerAgent.java index 626bcdc16..554164e26 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/enhance/PCEnhancerAgent.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/enhance/PCEnhancerAgent.java @@ -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 anchors = Configurations.getFullyQualifiedAnchorsInPropertiesLocation(opts); + private static void registerClassLoadEnhancer(Instrumentation inst, + Options opts) { + List 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 diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/enhance/ReflectingPersistenceCapable.java b/openjpa-kernel/src/main/java/org/apache/openjpa/enhance/ReflectingPersistenceCapable.java index dd3a9d32f..db2334e10 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/enhance/ReflectingPersistenceCapable.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/enhance/ReflectingPersistenceCapable.java @@ -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() { diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/instrumentation/InstrumentationManager.java b/openjpa-kernel/src/main/java/org/apache/openjpa/instrumentation/InstrumentationManager.java index c22992705..c2ce1c658 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/instrumentation/InstrumentationManager.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/instrumentation/InstrumentationManager.java @@ -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 providers); + public void initialize(OpenJPAConfiguration conf, PluginListValue providers); /** * Manage a given provider. This will plug the instruments managed by the diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/instrumentation/InstrumentationManagerImpl.java b/openjpa-kernel/src/main/java/org/apache/openjpa/instrumentation/InstrumentationManagerImpl.java index 31e91312f..2192aeb53 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/instrumentation/InstrumentationManagerImpl.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/instrumentation/InstrumentationManagerImpl.java @@ -43,8 +43,9 @@ public class InstrumentationManagerImpl implements InstrumentationManager { * @param conf * @param providers */ - public void initialize(OpenJPAConfiguration conf, PluginListValue 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)); } diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/AbstractBrokerFactory.java b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/AbstractBrokerFactory.java index 2784d8054..497b9b965 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/AbstractBrokerFactory.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/AbstractBrokerFactory.java @@ -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 _pcClassNames = null; -// private transient Collection _pcClassLoaders = null; + private transient Collection _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> toRedefine = new ArrayList>(); if (!_persistentTypesLoaded) { Collection> 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 getPcClassLoaders() { -// if (_pcClassLoaders == null) -// _pcClassLoaders = new ConcurrentReferenceHashSet(ConcurrentReferenceHashSet.WEAK); -// -// return _pcClassLoaders; -// } + private Collection getPcClassLoaders() { + if (_pcClassLoaders == null) + _pcClassLoaders = new ConcurrentReferenceHashSet(ConcurrentReferenceHashSet.WEAK); + + return _pcClassLoaders; + } /** *

@@ -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(); } diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/AbstractPCResultObjectProvider.java b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/AbstractPCResultObjectProvider.java index 8324943e7..3338f59a2 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/AbstractPCResultObjectProvider.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/AbstractPCResultObjectProvider.java @@ -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 { } /** diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/AttachManager.java b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/AttachManager.java index 90f9fb8a6..0f40ab38a 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/AttachManager.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/AttachManager.java @@ -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); } diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/Bootstrap.java b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/Bootstrap.java index b6db33faa..8066f26ec 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/Bootstrap.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/Bootstrap.java @@ -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); } } } diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/Broker.java b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/Broker.java index 1979738ca..64196848a 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/Broker.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/Broker.java @@ -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 cls. If cls is @@ -606,7 +608,7 @@ public interface Broker * @throws IllegalArgumentException if cls is not a managed * type or interface. */ - public Object newInstance(Class cls); + public Object newInstance(Class cls); /** * Returns true if obj is a detached object @@ -618,13 +620,13 @@ public interface Broker /** * Return an extent of the given class, optionally including subclasses. */ - public Extent newExtent(Class 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 diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/BrokerImpl.java b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/BrokerImpl.java index eaab8fbd8..c34729015 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/BrokerImpl.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/BrokerImpl.java @@ -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 _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 failed = _store.loadAll(load, state, StoreManager.FORCE_LOAD_NONE, fetch, edata); + PCState state = (transState) ? PCState.PCLEAN + : PCState.PNONTRANS; + Collection 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 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 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 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 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 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 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 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 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 sms, Collection failed, - List exceps) { + private void transactionalStatesAll(Collection sms, Collection failed, + List 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 Extent newExtent(Class type, boolean subclasses) { + public Extent newExtent(Class type, boolean subclasses) { return newExtent(type, subclasses, null); } - private Extent newExtent(Class type, boolean subclasses, FetchConfiguration fetch) { + private Extent newExtent(Class type, boolean subclasses, + FetchConfiguration fetch) { beginOperation(true); try { - ExtentImpl extent = new ExtentImpl(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 Iterator extentIterator(Class type, boolean subclasses, - FetchConfiguration fetch, boolean ignoreChanges) { - Extent 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 itr = sms.iterator(); itr.hasNext();) { + for (Iterator 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 getManagedObjects() { + public Collection getManagedObjects() { beginOperation(false); try { return new ManagedObjectCollection(getManagedStates()); @@ -3987,7 +4010,7 @@ public class BrokerImpl } } - public Collection getTransactionalObjects() { + public Collection getTransactionalObjects() { beginOperation(false); try { return new ManagedObjectCollection(getTransactionalStates()); @@ -3996,16 +4019,17 @@ public class BrokerImpl } } - public Collection getPendingTransactionalObjects() { + public Collection getPendingTransactionalObjects() { beginOperation(false); try { - return new ManagedObjectCollection(getPendingTransactionalStates()); + return new ManagedObjectCollection + (getPendingTransactionalStates()); } finally { endOperation(); } } - public Collection 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 getManagedStates() { + protected Collection getManagedStates() { return _cache.copy(); } @@ -4053,9 +4077,9 @@ public class BrokerImpl /** * Return a copy of all dirty state managers. */ - protected Collection 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 getPendingTransactionalStates() { + protected Collection getPendingTransactionalStates() { if (_pending == null) - return Collections.emptySet(); + return Collections.EMPTY_SET; return new LinkedHashSet(_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> getPersistedTypes() { + public Collection getPersistedTypes() { if (_persistedClss == null || _persistedClss.isEmpty()) - return Collections.emptySet(); + return Collections.EMPTY_SET; return Collections.unmodifiableCollection(_persistedClss); } - public Collection> getUpdatedTypes() { + public Collection getUpdatedTypes() { if (_updatedClss == null || _updatedClss.isEmpty()) - return Collections.emptySet(); + return Collections.EMPTY_SET; return Collections.unmodifiableCollection(_updatedClss); } - public Collection> 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, Serializable { + implements Set, Serializable { private final boolean _orderDirty; - private Set _dirty; - private Set _clean; + private Set _dirty = null; + private Set _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 copy() { + public Collection copy() { if (isEmpty()) { // Transaction Listeners may add entities to the transaction. - return new LinkedHashSet(); + 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 copy = new LinkedHashSet(size()); + Set copy = new LinkedHashSet(size()); if (_dirty != null) - for (StateManagerImpl dirty : _dirty) - copy.add(dirty); + for (Iterator itr = _dirty.iterator(); itr.hasNext();) + copy.add(itr.next()); if (_clean != null) - for (StateManagerImpl clean : _clean) - copy.add(clean); + for (Iterator itr = _clean.iterator(); itr.hasNext();) + copy.add(itr.next()); return copy; } /** * Return a copy of all dirty state managers. */ - public Collection copyDirty() { + public Collection copyDirty() { if (_dirty == null || _dirty.isEmpty()) - return Collections.emptySet(); + return Collections.EMPTY_SET; return new LinkedHashSet(_dirty); } @@ -4863,7 +4890,7 @@ public class BrokerImpl return _clean != null && _clean.remove(sm); } - public Iterator 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 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[] 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 { + extends AbstractCollection { - private final Collection _states; + private final Collection _states; - public ManagedObjectCollection(Collection states) { + public ManagedObjectCollection(Collection states) { _states = states; } - public Collection getStateManagers() { + public Collection getStateManagers() { return _states; } @@ -5005,16 +5031,17 @@ public class BrokerImpl return _states.size(); } - public Iterator iterator() { - return new Iterator() { - private final Iterator _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() { diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/DelegatingBroker.java b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/DelegatingBroker.java index ea1e4676a..d0ff9b501 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/DelegatingBroker.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/DelegatingBroker.java @@ -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(); diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/DelegatingStoreManager.java b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/DelegatingStoreManager.java index b0c856062..7de802863 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/DelegatingStoreManager.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/DelegatingStoreManager.java @@ -127,7 +127,7 @@ public abstract class DelegatingStoreManager _store.beforeStateChange(sm, fromState, toState); } - public Collection flush(Collection sms) { + public Collection flush(Collection sms) { return _store.flush(sms); } diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/DetachedStateAttachStrategy.java b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/DetachedStateAttachStrategy.java index b4ac76866..51fc74de7 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/DetachedStateAttachStrategy.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/DetachedStateAttachStrategy.java @@ -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: diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/DetachedValueStateManager.java b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/DetachedValueStateManager.java index f8d4ff52f..8ab181de7 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/DetachedValueStateManager.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/DetachedValueStateManager.java @@ -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, diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/ExpressionStoreQuery.java b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/ExpressionStoreQuery.java index 6d4e3d92f..7b22b8d16 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/ExpressionStoreQuery.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/ExpressionStoreQuery.java @@ -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. diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/ExtentImpl.java b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/ExtentImpl.java index c5eddffa0..0feade581 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/ExtentImpl.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/ExtentImpl.java @@ -66,7 +66,7 @@ public class ExtentImpl * @param type the candidate class * @param subs whether subclasses are included in the extent */ - protected ExtentImpl(Broker broker, Class type, boolean subs, + ExtentImpl(Broker broker, Class type, boolean subs, FetchConfiguration fetch) { _broker = broker; _type = type; @@ -120,7 +120,8 @@ public class ExtentImpl // 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 && 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; diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/QueryImpl.java b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/QueryImpl.java index 04ca3d8a0..1478c3ae7 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/QueryImpl.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/QueryImpl.java @@ -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; } diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/StateManagerImpl.java b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/StateManagerImpl.java index fd18faa5c..a66ed9867 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/StateManagerImpl.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/StateManagerImpl.java @@ -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); } diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/StoreContext.java b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/StoreContext.java index 2226387b3..bb85627b0 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/StoreContext.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/StoreContext.java @@ -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 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 OID_XXX 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 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 Iterator extentIterator(Class cls, boolean subs, FetchConfiguration fetch, boolean ignoreChanges); + public Iterator 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 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 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 objs, OpCallbacks call); /** * Return whether the given object is persistent. diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/StoreManager.java b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/StoreManager.java index 35e7b359d..f2efc97bf 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/StoreManager.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/StoreManager.java @@ -252,7 +252,7 @@ public interface StoreManager * * @see org.apache.openjpa.util.ApplicationIds#assign() */ - public Collection flush(Collection sms); + public Collection flush(Collection sms); /** * Assign an object id to the given new instance. Return false if the diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/VersionAttachStrategy.java b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/VersionAttachStrategy.java index c1d5c677c..31403f501 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/VersionAttachStrategy.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/VersionAttachStrategy.java @@ -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); } diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/exps/AbstractExpressionBuilder.java b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/exps/AbstractExpressionBuilder.java index fb6e8413e..11cd74b03 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/exps/AbstractExpressionBuilder.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/exps/AbstractExpressionBuilder.java @@ -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); } /** diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/exps/CandidatePath.java b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/exps/CandidatePath.java index 5971c376a..69ec96667 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/exps/CandidatePath.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/exps/CandidatePath.java @@ -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; diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/exps/Exp.java b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/exps/Exp.java index d136834e1..c2a134e6c 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/exps/Exp.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/exps/Exp.java @@ -27,7 +27,7 @@ import org.apache.openjpa.kernel.StoreContext; * * @author Abe White */ -public class Exp +class Exp implements Expression { /** diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/exps/InMemoryExpressionFactory.java b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/exps/InMemoryExpressionFactory.java index 89f22f3fc..da962e480 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/exps/InMemoryExpressionFactory.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/exps/InMemoryExpressionFactory.java @@ -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 diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/jpql/JPQLExpressionBuilder.java b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/jpql/JPQLExpressionBuilder.java index 159b0aa42..c22f06180 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/jpql/JPQLExpressionBuilder.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/jpql/JPQLExpressionBuilder.java @@ -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); diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/meta/AbstractCFMetaDataFactory.java b/openjpa-kernel/src/main/java/org/apache/openjpa/meta/AbstractCFMetaDataFactory.java index 01acbc705..b9be0ad8b 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/meta/AbstractCFMetaDataFactory.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/meta/AbstractCFMetaDataFactory.java @@ -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 files = null; protected Collection 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 clsNames = new HashMap ((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 getPersistentTypeNames(boolean devpath) { + public Set 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 parsePersistentTypeNames(ClassLoader loader) throws IOException { ClassArgParser cparser = newClassArgParser(); - cparser.setClassLoader(loader); String[] clss; Set names = new HashSet(); 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(); diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/meta/AbstractMetaDataFactory.java b/openjpa-kernel/src/main/java/org/apache/openjpa/meta/AbstractMetaDataFactory.java index ac5427ddc..8fb60f97b 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/meta/AbstractMetaDataFactory.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/meta/AbstractMetaDataFactory.java @@ -45,13 +45,13 @@ public abstract class AbstractMetaDataFactory protected File dir = null; protected int store = STORE_DEFAULT; protected boolean strict = false; - protected Set types = null; + protected Set types = null; /** * Set of persistent type names supplied by user. */ - public void setTypes(Set 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(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) { diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/meta/ClassMetaData.java b/openjpa-kernel/src/main/java/org/apache/openjpa/meta/ClassMetaData.java index 813b8b03f..5f52a9bc2 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/meta/ClassMetaData.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/meta/ClassMetaData.java @@ -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> 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()); diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/meta/DelegatingMetaDataFactory.java b/openjpa-kernel/src/main/java/org/apache/openjpa/meta/DelegatingMetaDataFactory.java index 318132abe..06b14bc04 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/meta/DelegatingMetaDataFactory.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/meta/DelegatingMetaDataFactory.java @@ -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 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() { diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/meta/FieldMetaData.java b/openjpa-kernel/src/main/java/org/apache/openjpa/meta/FieldMetaData.java index d9a9464af..9a667785d 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/meta/FieldMetaData.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/meta/FieldMetaData.java @@ -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; } diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/meta/JavaTypes.java b/openjpa-kernel/src/main/java/org/apache/openjpa/meta/JavaTypes.java index 1629a0ee9..6cbaf2948 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/meta/JavaTypes.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/meta/JavaTypes.java @@ -215,10 +215,11 @@ public class JavaTypes { * @param mustExist Whether the supplied loader must 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 diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/meta/MetaDataFactory.java b/openjpa-kernel/src/main/java/org/apache/openjpa/meta/MetaDataFactory.java index 7f152a006..5c5c0466f 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/meta/MetaDataFactory.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/meta/MetaDataFactory.java @@ -75,7 +75,7 @@ public interface MetaDataFactory * {@link MetaDataModes#MODE_META MODE_META}, so long as * the strict 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 getPersistentTypeNames(boolean devpath); + public Set 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 diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/meta/MetaDataRepository.java b/openjpa-kernel/src/main/java/org/apache/openjpa/meta/MetaDataRepository.java index 306dc04ba..2e1a63142 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/meta/MetaDataRepository.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/meta/MetaDataRepository.java @@ -313,7 +313,21 @@ public class MetaDataRepository implements PCRegistry.RegisterClassListener, Con } - Set 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 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> loaded = new ArrayList>(); 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 pcNames = getPersistentTypeNames(false); + Set 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> classList = _aliases.get(alias); - Set 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 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 pcNames = getPersistentTypeNames(false); + Set 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 resolved = new ArrayList(_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> 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> classes, boolean mustExist) { + private ClassMetaData[] getImplementorMetaDatasInternal(Collection> classes, ClassLoader envLoader, + boolean mustExist) { Collection mapped = new ArrayList(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 getPersistentTypeNames(boolean devpath) { + public Set 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 getPersistentTypeNamesInternal(boolean devpath) { - return _factory.getPersistentTypeNames(devpath); + private Set 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> loadPersistentTypes(boolean devpath) { - return loadPersistentTypes(devpath, false); + public Collection> 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> loadPersistentTypes(boolean devpath, boolean mustExist) { + public Collection> 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> loadPersistentTypesInternal(boolean devpath, boolean mustExist) { - Set names = getPersistentTypeNames(devpath); + private Collection> loadPersistentTypesInternal(boolean devpath, ClassLoader envLoader, + boolean mustExist) { + Set 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> classes = new ArrayList>(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 pcNames = getPersistentTypeNames(false); + Collection pcNames = getPersistentTypeNames(false, envLoader); Collection> 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> types = loadPersistentTypes(false); + private void resolveAll(ClassLoader envLoader) { + Collection> 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; diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/meta/MetaDataTool.java b/openjpa-kernel/src/main/java/org/apache/openjpa/meta/MetaDataTool.java index 758dfb6aa..c913ce65a 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/meta/MetaDataTool.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/meta/MetaDataTool.java @@ -188,7 +188,7 @@ public class MetaDataTool try { if (_drop != null && !_drop.isEmpty() && !mdf.drop((Class[]) _drop.toArray(new Class[_drop.size()]), - MODE_META | MODE_MAPPING | MODE_QUERY)) { + MODE_META | MODE_MAPPING | MODE_QUERY, null)) { Log log = _conf.getLog(OpenJPAConfiguration.LOG_METADATA); if (log.isWarnEnabled()) log.warn(_loc.get("bad-drop", _drop)); @@ -285,7 +285,8 @@ public class MetaDataTool } Configurations.populateConfiguration(conf, opts); - ClassLoader loader = conf.getClassLoader(); + ClassLoader loader = conf.getClassResolverInstance(). + getClassLoader(MetaDataTool.class, null); if (fileName != null) flags.file = Files.getFile(fileName, loader); @@ -319,8 +320,8 @@ public class MetaDataTool Log log = conf.getLog(OpenJPAConfiguration.LOG_TOOL); ClassArgParser cap = conf.getMetaDataRepositoryInstance(). getMetaDataFactory().newClassArgParser(); - cap.setClassLoader(conf.getClassLoader()); - Class[] classes; + cap.setClassLoader(loader); + Class[] classes; for (int i = 0; i < args.length; i++) { classes = cap.parseTypes(args[i]); for (int j = 0; j < classes.length; j++) { diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/meta/NoneMetaDataFactory.java b/openjpa-kernel/src/main/java/org/apache/openjpa/meta/NoneMetaDataFactory.java index e90861b46..5a831bc2a 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/meta/NoneMetaDataFactory.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/meta/NoneMetaDataFactory.java @@ -55,7 +55,7 @@ public class NoneMetaDataFactory public void setStrict(boolean strict) { } - public void load(Class cls, int mode) { + public void load(Class cls, int mode, ClassLoader envLoader) { } public boolean store(ClassMetaData[] metas, QueryMetaData[] queries, @@ -63,7 +63,7 @@ public class NoneMetaDataFactory return false; } - public boolean drop(Class[] cls, int mode) { + public boolean drop(Class[] cls, int mode, ClassLoader envLoader) { return false; } @@ -71,15 +71,17 @@ public class NoneMetaDataFactory return this; } - public Set getPersistentTypeNames(boolean classpath) { + public Set getPersistentTypeNames(boolean classpath, + ClassLoader envLoader) { return null; } - public Class getQueryScope(String queryName) { + public Class getQueryScope(String queryName, ClassLoader loader) { return null; } - public Class getResultSetMappingScope(String resultSetMappingName) { + public Class getResultSetMappingScope(String resultSetMappingName, + ClassLoader loader) { return null; } diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/meta/SequenceMetaData.java b/openjpa-kernel/src/main/java/org/apache/openjpa/meta/SequenceMetaData.java index d629c7d24..a8a26f56d 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/meta/SequenceMetaData.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/meta/SequenceMetaData.java @@ -70,7 +70,8 @@ public class SequenceMetaData private static final String PROP_SCHEMA = "Schema"; private static final String PROP_CATALOG = "Catalog"; - private static final Localizer _loc = Localizer.forPackage(SequenceMetaData.class); + private static final Localizer _loc = Localizer.forPackage + (SequenceMetaData.class); private MetaDataRepository _repos; private SequenceFactory _factory = null; @@ -257,25 +258,27 @@ public class SequenceMetaData /** * Return the initialized sequence instance. */ - public synchronized Seq getInstance() { + public synchronized Seq getInstance(ClassLoader envLoader) { if (_instance == null) - _instance = instantiate(); + _instance = instantiate(envLoader); return _instance; } /** * Create a new uninitialized instance of this sequence. */ - protected Seq instantiate() { + protected Seq instantiate(ClassLoader envLoader) { if (NAME_SYSTEM.equals(_name)) return _repos.getConfiguration().getSequenceInstance(); try { - PluginValue plugin = newPluginValue("sequence-plugin"); + PluginValue plugin = newPluginValue("sequence-plugin"); plugin.setString(_plugin); String clsName = plugin.getClassName(); - Class cls = Class.forName(clsName, true, _repos.getConfiguration().getClassLoader()); + Class cls = Class.forName(clsName, true, + AccessController.doPrivileged( + J2DoPrivHelper.getClassLoaderAction(Seq.class))); StringBuilder props = new StringBuilder(); if (plugin.getProperties() != null) props.append(plugin.getProperties()); @@ -285,8 +288,10 @@ public class SequenceMetaData // interface or a factory class Seq seq; if (Seq.class.isAssignableFrom(cls)) { - seq = (Seq) AccessController.doPrivileged(J2DoPrivHelper.newInstanceAction(cls)); - Configurations.configureInstance(seq, _repos.getConfiguration(), props.toString()); + seq = (Seq) AccessController.doPrivileged( + J2DoPrivHelper.newInstanceAction(cls)); + Configurations.configureInstance(seq, + _repos.getConfiguration(), props.toString()); if(_type != Seq.TYPE_DEFAULT) seq.setType(_type); } else if (_factory != null) @@ -331,7 +336,7 @@ public class SequenceMetaData * Create a new plugin value for sequences. Returns a standard * {@link SeqValue} by default. */ - protected PluginValue newPluginValue(String property) { + protected PluginValue newPluginValue(String property) { return new SeqValue(property); } diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/meta/ValueMetaDataImpl.java b/openjpa-kernel/src/main/java/org/apache/openjpa/meta/ValueMetaDataImpl.java index c2d01aeb4..71bc845ad 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/meta/ValueMetaDataImpl.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/meta/ValueMetaDataImpl.java @@ -106,7 +106,8 @@ public class ValueMetaDataImpl return getDeclaredTypeMetaData(); if (_typeMeta == null && _code == JavaTypes.PC) { ClassMetaData meta = _owner.getDefiningMetaData(); - _typeMeta = meta.getRepository().getMetaData(_type, true); + _typeMeta = meta.getRepository().getMetaData(_type, + meta.getEnvClassLoader(), true); } return _typeMeta; } @@ -141,7 +142,8 @@ public class ValueMetaDataImpl _decTypeMeta = getEmbeddedMetaData(); else { ClassMetaData meta = _owner.getDefiningMetaData(); - _decTypeMeta = meta.getRepository().getMetaData(_decType, true); + _decTypeMeta = meta.getRepository().getMetaData(_decType, + meta.getEnvClassLoader(), true); } } return _decTypeMeta; @@ -296,7 +298,8 @@ public class ValueMetaDataImpl if (_mappedBy == MAPPED_BY_PK) { // use this instead of getting meta from element b/c that // requires element to be resolved - ClassMetaData meta = getRepository().getMetaData(_owner.getElement().getType(), false); + ClassMetaData meta = getRepository().getMetaData + (_owner.getElement().getType(), null, false); if (meta == null) throw new MetaDataException(_loc.get("val-not-pc", _owner)); if (meta.getPrimaryKeyFields().length != 1) @@ -406,7 +409,8 @@ public class ValueMetaDataImpl // see if actual type is pc if (JavaTypes.maybePC(_code, _type)) { - _typeMeta = _owner.getRepository().getMetaData(_type, false); + _typeMeta = _owner.getRepository().getMetaData(_type, + _owner.getDefiningMetaData().getEnvClassLoader(), false); if (_typeMeta != null) _code = JavaTypes.PC; } @@ -442,7 +446,8 @@ public class ValueMetaDataImpl * Resolve the declared type. */ private void resolveDeclaredType(Class type) { - ClassMetaData meta = _owner.getRepository().getMetaData(type, false); + ClassMetaData meta = _owner.getRepository().getMetaData(type, + _owner.getDefiningMetaData().getEnvClassLoader(), false); if (meta != null) _decCode = JavaTypes.PC; diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/util/Id.java b/openjpa-kernel/src/main/java/org/apache/openjpa/util/Id.java index 07918c947..2188858d8 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/util/Id.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/util/Id.java @@ -67,7 +67,8 @@ public final class Id * instance. */ public Id(String str, OpenJPAConfiguration conf, ClassLoader brokerLoader) { - this(str, (conf == null) ? brokerLoader : conf.getClassLoader()); + this(str, (conf == null) ? brokerLoader : conf. + getClassResolverInstance().getClassLoader(Id.class, brokerLoader)); } /** diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/util/ImplHelper.java b/openjpa-kernel/src/main/java/org/apache/openjpa/util/ImplHelper.java index 542992671..bda6e6166 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/util/ImplHelper.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/util/ImplHelper.java @@ -146,7 +146,7 @@ public class ImplHelper { } /** - * Generate a value for the given metadata. + * Generate a value for the given metadaa. */ private static Object generateValue(StoreContext ctx, ClassMetaData meta, FieldMetaData fmd, int typeCode) { @@ -157,7 +157,8 @@ public class ImplHelper { SequenceMetaData smd = (fmd == null) ? meta.getIdentitySequenceMetaData() : fmd.getValueSequenceMetaData(); - return JavaTypes.convert(smd.getInstance().next(ctx, meta), typeCode); + return JavaTypes.convert(smd.getInstance(ctx.getClassLoader()). + next(ctx, meta), typeCode); case ValueStrategies.UUID_STRING: return UUIDGenerator.nextString(UUIDGenerator.TYPE1); case ValueStrategies.UUID_HEX: diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/util/Serialization.java b/openjpa-kernel/src/main/java/org/apache/openjpa/util/Serialization.java index 09b3adfab..63591e344 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/util/Serialization.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/util/Serialization.java @@ -48,7 +48,8 @@ import org.apache.openjpa.lib.util.MultiClassLoader; */ public class Serialization { - private static final Localizer _loc = Localizer.forPackage(Serialization.class); + private static final Localizer _loc = Localizer.forPackage + (Serialization.class); /** * Serialize a value that might contain persistent objects. Replaces @@ -57,7 +58,8 @@ public class Serialization { public static byte[] serialize(Object val, StoreContext ctx) { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); try { - ObjectOutputStream objs = new PersistentObjectOutputStream(bytes, ctx); + ObjectOutputStream objs = new PersistentObjectOutputStream(bytes, + ctx); objs.writeObject(val); objs.flush(); return bytes.toByteArray(); @@ -98,7 +100,8 @@ public class Serialization { /** * Constructor; supply underlying stream. */ - public PersistentObjectOutputStream(OutputStream delegate, StoreContext ctx) + public PersistentObjectOutputStream(OutputStream delegate, + StoreContext ctx) throws IOException { super(delegate); _ctx = ctx; @@ -152,7 +155,8 @@ public class Serialization { * Constructor; supply source stream and broker to * use for persistent object lookups. */ - public PersistentObjectInputStream(InputStream delegate, StoreContext ctx) + public PersistentObjectInputStream(InputStream delegate, + StoreContext ctx) throws IOException { super(delegate); _ctx = ctx; @@ -166,7 +170,7 @@ public class Serialization { protected void addContextClassLoaders(MultiClassLoader loader) { super.addContextClassLoaders(loader); - loader.addClassLoader(_ctx.getConfiguration().getClassLoader()); + loader.addClassLoader(_ctx.getClassLoader()); } protected Object resolveObject(Object obj) { diff --git a/openjpa-kernel/src/main/resources/org/apache/openjpa/kernel/localizer.properties b/openjpa-kernel/src/main/resources/org/apache/openjpa/kernel/localizer.properties index cd6f58bfb..d5354809c 100644 --- a/openjpa-kernel/src/main/resources/org/apache/openjpa/kernel/localizer.properties +++ b/openjpa-kernel/src/main/resources/org/apache/openjpa/kernel/localizer.properties @@ -206,8 +206,7 @@ bad-brokerfactory: Could not invoke the static getInstance method on the \ named factory class "{0}". bad-new-brokerfactory: Could not invoke the static newInstance method on the \ named factory class "{0}". -bad-brokerfactory-class: The named BrokerFactory "{0}" can not be loaded by \ - classloader "{1}". +bad-brokerfactory-class: The named BrokerFactory "{0}" is not valid. instantiate-abstract: Cannot instantiate abstract class of type "{0}" with \ object id "{1}"; this may indicate that the inheritance discriminator \ for the class is not configured correctly. diff --git a/openjpa-lib/src/main/java/org/apache/openjpa/lib/ant/AbstractTask.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/ant/AbstractTask.java index 771d937f0..5c15eca53 100644 --- a/openjpa-lib/src/main/java/org/apache/openjpa/lib/ant/AbstractTask.java +++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/ant/AbstractTask.java @@ -53,7 +53,8 @@ import org.apache.tools.ant.types.Path; */ public abstract class AbstractTask extends MatchingTask { - private static final Localizer _loc = Localizer.forPackage(AbstractTask.class); + private static final Localizer _loc = Localizer.forPackage + (AbstractTask.class); protected final List fileSets = new ArrayList(); protected boolean haltOnError = true; @@ -81,7 +82,7 @@ public abstract class AbstractTask extends MatchingTask { /** * Whether we want to delegate to the parent ClassLoader - * for resolving classes. This may "taint" classes. + * for resolveing classes. This may "taint" classes. */ public void setUseParentClassloader(boolean useParent) { this.useParent = useParent; @@ -114,12 +115,11 @@ public abstract class AbstractTask extends MatchingTask { if (_cl != null) return _cl; - if (classpath != null) { + if (classpath != null) _cl = new AntClassLoader(getProject(), classpath, useParent); - } else { + else _cl = new AntClassLoader(getProject().getCoreLoader(), getProject(), new Path(getProject()), useParent); - } _cl.setIsolated(isolate); return _cl; @@ -159,7 +159,9 @@ public abstract class AbstractTask extends MatchingTask { if (_conf == null) _conf = newConfiguration(); if (_conf.getPropertiesResource() == null) { - ConfigurationProvider cp = ProductDerivations.loadDefaults(); + ConfigurationProvider cp = ProductDerivations.loadDefaults + (AccessController.doPrivileged( + J2DoPrivHelper.getClassLoaderAction(_conf.getClass()))); if (cp != null) cp.setInto(_conf); } @@ -185,10 +187,11 @@ public abstract class AbstractTask extends MatchingTask { String[] dsFiles = ds.getIncludedFiles(); for (int j = 0; j < dsFiles.length; j++) { File f = new File(dsFiles[j]); - if (!( AccessController.doPrivileged(J2DoPrivHelper.isFileAction(f))).booleanValue()) { + if (!( AccessController.doPrivileged(J2DoPrivHelper + .isFileAction(f))).booleanValue()) f = new File(ds.getBasedir(), dsFiles[j]); - } - files.add(AccessController.doPrivileged(J2DoPrivHelper.getAbsolutePathAction(f))); + files.add(AccessController.doPrivileged( + J2DoPrivHelper.getAbsolutePathAction(f))); } } return (String[]) files.toArray(new String[files.size()]); diff --git a/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/AbstractProductDerivation.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/AbstractProductDerivation.java index dc26d3422..d43f33069 100644 --- a/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/AbstractProductDerivation.java +++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/AbstractProductDerivation.java @@ -40,17 +40,18 @@ public abstract class AbstractProductDerivation throws Exception { } - public ConfigurationProvider loadGlobals() + public ConfigurationProvider loadGlobals(ClassLoader loader) throws Exception { return null; } - public ConfigurationProvider loadDefaults() + public ConfigurationProvider loadDefaults(ClassLoader loader) throws Exception { return null; } - public ConfigurationProvider load(String resource, String anchor) + public ConfigurationProvider load(String resource, String anchor, + ClassLoader loader) throws Exception { return null; } diff --git a/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/BooleanValue.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/BooleanValue.java index dd0cbc255..7ead667ea 100644 --- a/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/BooleanValue.java +++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/BooleanValue.java @@ -23,15 +23,19 @@ package org.apache.openjpa.lib.conf; * * @author Marc Prud'hommeaux */ -public class BooleanValue extends Value { +public class BooleanValue extends Value { private boolean value; public BooleanValue(String prop) { - super(Boolean.class, prop); + super(prop); setAliasListComprehensive(true); } + public Class getValueType() { + return boolean.class; + } + /** * The internal value. */ @@ -55,10 +59,13 @@ public class BooleanValue extends Value { } protected void setInternalString(String val) { - set(Boolean.valueOf(val)); + set(Boolean.valueOf(val).booleanValue()); } protected void setInternalObject(Object obj) { - set(obj == null ? false : (Boolean)obj); + if (obj == null) + set(false); + else + set(((Boolean) obj).booleanValue()); } } diff --git a/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/BootstrapException.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/BootstrapException.java index b3b092de4..48a9b277c 100644 --- a/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/BootstrapException.java +++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/BootstrapException.java @@ -24,7 +24,6 @@ package org.apache.openjpa.lib.conf; * @since 0.4.1.4 * */ -@SuppressWarnings("serial") public class BootstrapException extends RuntimeException { private boolean _fatal = false; diff --git a/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/Configuration.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/Configuration.java index a349f28ee..dc9749d63 100644 --- a/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/Configuration.java +++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/Configuration.java @@ -33,14 +33,10 @@ import org.apache.openjpa.lib.util.Closeable; /** * Interface for generic configuration objects. Includes the ability * to write configuration to and from {@link Properties} instances. Instances - * are thread-safe for reads, but not for writes. - *
- * A configuration comprises of {@link Value values}. The configuration is - * responsible for loading the values. + * are threadsafe for reads, but not for writes. * * @author Marc Prud'hommeaux * @author Abe White - * @author Pinaki Poddar */ public interface Configuration extends BeanInfo, Serializable, Closeable, Cloneable { @@ -151,23 +147,24 @@ public interface Configuration /** * Return the {@link Value} for the given property, or null if none. */ - public Value getValue(String property); + public Value getValue(String property); /** * Return the set of all {@link Value}s. */ - public Value[] getValues(); + public Value[] getValues(); /** * Add the given value to the set of configuration properties. This * method replaces any existing value under the same property. */ - public Value addValue(Value val); + public T addValue(T val); + //public Value addValue(Value val); /** * Remove the given value from the set of configuration properties. */ - public boolean removeValue(Value val); + public boolean removeValue(Value val); /** * A properties representation of this Configuration. @@ -248,23 +245,33 @@ public interface Configuration * Free the resources used by this object. */ public void close(); - - /** - * Adds a class loader for loading plug-ins by class name. - * - * @param loader - */ - public ClassLoader addClassLoader(ClassLoader loader); - - /** - * Gets the class loader for loading plug-ins by class name. - * - */ - public ClassLoader getClassLoader(); /** * Return a copy of this configuration. */ public Object clone(); + /** + * Modifies a dynamic property of this receiver even when + * {@link #setReadOnly(boolean) frozen}. + * + * @since 1.0.0 + */ +// public void modifyDynamic(String property, Object newValue); +// +// /** +// * Affirms if the given property can be modified dynamically i.e. +// * even after the receiver is {@link #setReadOnly(boolean) frozen}. +// * +// * @since 1.0.0 +// */ +// public boolean isDynamic(String property); +// +// /** +// * Gets the values that can be modified dynamically i.e. +// * even after the receiver is {@link #setReadOnly(boolean) frozen}. +// * +// * @since 1.0.0 +// */ +// public Value[] getDynamicValues(); } diff --git a/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/ConfigurationImpl.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/ConfigurationImpl.java index ede77864a..d8ca88898 100644 --- a/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/ConfigurationImpl.java +++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/ConfigurationImpl.java @@ -76,7 +76,6 @@ import serp.util.Strings; * provides base configuration functionality, including serialization, * the equals and hashCode contracts, and default * property loading. - *
* Property descriptors for {@link Value} instances are constructed from * the {@link Localizer} for the package of the configuration class. The * following localized strings will be used for describing a value, where @@ -99,8 +98,6 @@ import serp.util.Strings; *
  • name-displayorder: The order in which the property should * be displayer.
  • * - *

    - * * * @author Abe White */ @@ -109,10 +106,10 @@ public class ConfigurationImpl private static final String SEP = J2DoPrivHelper.getLineSeparator(); - private static final Localizer _loc = Localizer.forPackage(ConfigurationImpl.class); + private static final Localizer _loc = Localizer.forPackage + (ConfigurationImpl.class); - public ObjectValue logFactoryPlugin; - private final MultiClassLoader _pluginLoader; + public ObjectValue logFactoryPlugin; public StringValue id; private String _product = null; @@ -120,7 +117,7 @@ public class ConfigurationImpl private Map _props = null; private boolean _globals = false; private String _auto = null; - private final List> _vals = new ArrayList>(); + private final List _vals = new ArrayList(); private Set _supportedKeys; // property listener helper @@ -144,14 +141,9 @@ public class ConfigurationImpl * @param loadGlobals whether to attempt to load the global properties */ public ConfigurationImpl(boolean loadGlobals) { - _pluginLoader = AccessController.doPrivileged(J2DoPrivHelper.newMultiClassLoaderAction()); - _pluginLoader.addClassLoader(MultiClassLoader.THREAD_LOADER); - _pluginLoader.addClassLoader(getClass().getClassLoader()); - _pluginLoader.addClassLoader(MultiClassLoader.SYSTEM_LOADER); - setProductName("openjpa"); - logFactoryPlugin = addPlugin(LogFactory.class, "Log", true); + logFactoryPlugin = addPlugin("Log", true); String[] aliases = new String[]{ "true", LogFactoryImpl.class.getName(), "openjpa", LogFactoryImpl.class.getName(), @@ -177,13 +169,20 @@ public class ConfigurationImpl * {@link ProductDerivation}s, and from System properties. */ public boolean loadGlobals() { - ConfigurationProvider provider = ProductDerivations.loadGlobals(); - if (provider != null) { + MultiClassLoader loader = AccessController + .doPrivileged(J2DoPrivHelper.newMultiClassLoaderAction()); + loader.addClassLoader(AccessController.doPrivileged( + J2DoPrivHelper.getContextClassLoaderAction())); + loader.addClassLoader(getClass().getClassLoader()); + ConfigurationProvider provider = ProductDerivations.loadGlobals(loader); + if (provider != null) provider.setInto(this); - } + // let system properties override other globals try { - fromProperties(new HashMap(AccessController.doPrivileged(J2DoPrivHelper.getPropertiesAction()))); + fromProperties(new HashMap( + AccessController.doPrivileged( + J2DoPrivHelper.getPropertiesAction()))); } catch (SecurityException se) { // security manager might disallow } @@ -208,8 +207,8 @@ public class ConfigurationImpl public LogFactory getLogFactory() { if (logFactoryPlugin.get() == null) - logFactoryPlugin.instantiate(this); - return logFactoryPlugin.get(); + logFactoryPlugin.instantiate(LogFactory.class, this); + return (LogFactory) logFactoryPlugin.get(); } public void setLogFactory(LogFactory logFactory) { @@ -243,8 +242,8 @@ public class ConfigurationImpl return getLog("openjpa.Runtime"); } - public Value[] getValues() { - return _vals.toArray(new Value[_vals.size()]); + public Value[] getValues() { + return (Value[]) _vals.toArray(new Value[_vals.size()]); } /** @@ -254,12 +253,12 @@ public class ConfigurationImpl * with which the value has been registered. A value may have multiple * equivalent names and this method searches with all equivalent names. */ - public Value getValue(String property) { + public Value getValue(String property) { if (property == null) return null; // search backwards so that custom values added after construction - // are found quickly, since this will be the standard way of accessing them + // are found quickly, since this will be the std way of accessing them for (int i = _vals.size()-1; i >= 0; i--) { if (_vals.get(i).matches(property)) return _vals.get(i); @@ -279,7 +278,7 @@ public class ConfigurationImpl String getterName; Method getter; Object getterTarget; - for (Value val : _vals) { + for(Value val : _vals) { getterName = val.getInstantiatingGetter(); if (getterName == null) continue; @@ -307,7 +306,8 @@ public class ConfigurationImpl } } if (errs != null) - throw new RuntimeException(_loc.get("get-prop-errs", errs.toString()).getMessage()); + throw new RuntimeException(_loc.get("get-prop-errs", + errs.toString()).getMessage()); } public boolean isReadOnly() { @@ -325,7 +325,7 @@ public class ConfigurationImpl _changeSupport.removePropertyChangeListener(listener); } - public void valueChanged(Value val) { + public void valueChanged(Value val) { if (_changeSupport == null && _props == null) return; @@ -352,8 +352,8 @@ public class ConfigurationImpl preClose(); - ObjectValue val; - for (Value v : _vals) { + ObjectValue val; + for(Value v : _vals) { if (v instanceof Closeable) { try { ((Closeable)v).close(); } catch (Exception e) {} @@ -363,7 +363,7 @@ public class ConfigurationImpl if (!(v instanceof ObjectValue)) continue; - val = (ObjectValue) v; + val = (ObjectValue) v; if (val.get() instanceof Closeable) { try { ((Closeable) val.get()).close(); @@ -437,9 +437,9 @@ public class ConfigurationImpl _pds = new PropertyDescriptor[_vals.size()]; List failures = null; - Value val; + Value val; for (int i = 0; i < _vals.size(); i++) { - val = (Value) _vals.get(i); + val = (Value) _vals.get(i); try { _pds[i] = getPropertyDescriptor(val); } catch (MissingResourceException mre) { @@ -462,7 +462,7 @@ public class ConfigurationImpl /** * Create a property descriptor for the given value. */ - private PropertyDescriptor getPropertyDescriptor(Value val) + private PropertyDescriptor getPropertyDescriptor(Value val) throws IntrospectionException { String prop = val.getProperty(); prop = prop.substring(prop.lastIndexOf('.') + 1); @@ -546,6 +546,7 @@ public class ConfigurationImpl /** * Find the given localized string, or return null if not found. */ + @SuppressWarnings("unchecked") private String findLocalized(String key, boolean fatal, Class scope) { // find the localizer package that contains this key Localizer loc = null; @@ -560,7 +561,8 @@ public class ConfigurationImpl } } - for (Class cls = getClass(); cls != Object.class; cls = cls.getSuperclass()) { + for (Class cls = getClass(); cls != Object.class; + cls = cls.getSuperclass()) { loc = Localizer.forPackage(cls); try { return loc.getFatal(key).getMessage(); @@ -589,7 +591,7 @@ public class ConfigurationImpl public Map toProperties(boolean storeDefaults) { // clone properties before making any modifications; we need to keep // the internal properties instance consistent to maintain equals and - // hash code contracts + // hashcode contracts Map clone; if (_props == null) clone = new TreeMap(); @@ -602,7 +604,7 @@ public class ConfigurationImpl // with default values, add values to properties if (_props == null || storeDefaults) { String str; - for (Value val : _vals) { + for (Value val : _vals) { // NOTE: Following was removed to hide Value.INVISIBLE properties, like connectionPassword // if key in existing properties, we already know value is up to date //if (_props != null && Configurations.containsProperty(val, _props) && val.isVisible()) @@ -633,13 +635,13 @@ public class ConfigurationImpl } // copy the input to avoid mutation issues - if (map instanceof HashMap) { + if (map instanceof HashMap) map = (Map) ((HashMap) map).clone(); - } else if (map instanceof Properties) { + else if (map instanceof Properties) map = (Map) ((Properties) map).clone(); - } else { + else map = new LinkedHashMap(map); - } + Map remaining = new HashMap(map); boolean ser = true; Object o; @@ -666,9 +668,9 @@ public class ConfigurationImpl // now warn if there are any remaining properties that there // is an unhandled prop, and remove the unknown properties - Map.Entry entry; - for (Iterator itr = remaining.entrySet().iterator(); itr.hasNext();) { - entry = (Map.Entry) itr.next(); + Map.Entry entry; + for (Iterator itr = remaining.entrySet().iterator(); itr.hasNext();) { + entry = (Map.Entry) itr.next(); Object key = entry.getKey(); if (key != null) { warnInvalidProperty((String) key); @@ -682,7 +684,7 @@ public class ConfigurationImpl } public List getPropertyKeys(String propertyName) { - Value value = getValue(propertyName); + Value value = getValue(propertyName); return value == null ? Collections.EMPTY_LIST : value.getPropertyKeys(); } @@ -698,7 +700,7 @@ public class ConfigurationImpl return _supportedKeys; _supportedKeys = new TreeSet(); - for (Value val : _vals) { + for (Value val : _vals) { if (val.isPrivate()) continue; List keys = val.getPropertyKeys(); @@ -732,7 +734,7 @@ public class ConfigurationImpl * Use this method instead of attempting to add the value directly because * this will account for the property prefix. */ - private void setValue(Map map, Value val) { + private void setValue(Map map, Value val) { Object key = val.getLoadKey(); if (key == null) { List keys = val.getPropertyKeys(); @@ -746,7 +748,9 @@ public class ConfigurationImpl key = "openjpa." + val.getProperty(); } } - map.put(key, val.getExternal()); + Object external = val.isHidden() ? Value.INVISIBLE : + val instanceof ObjectValue ? val.getString() : val.get(); + map.put(key, external); } /** @@ -754,11 +758,12 @@ public class ConfigurationImpl * property names. Detects if the given map contains multiple keys that * are equivalent names for the given value. */ - private Object findValue(Map map, Value val) { + private Object findValue(Map map, Value val) { Object result = null; List partialKeys = val.getPropertyKeys(); for (String partialKey : partialKeys) { - String key = ProductDerivations.getConfigurationKey(partialKey, map); + String key = ProductDerivations.getConfigurationKey( + partialKey, map); if (map.containsKey(key)) { // do not return immediately. Looping through all equivalent // property names will detect if the Map contains multiple keys @@ -775,9 +780,7 @@ public class ConfigurationImpl */ private void warnInvalidProperty(String propName) { if (propName != null && - (propName.startsWith("java.") || - propName.startsWith("javax.persistence") || - propName.startsWith("sun."))) + (propName.startsWith("java.") || propName.startsWith("javax.persistence")|| propName.startsWith("sun."))) return; if (!isInvalidProperty(propName)) return; @@ -802,7 +805,7 @@ public class ConfigurationImpl private Collection newPropertyList() { String[] prefixes = ProductDerivations.getConfigurationPrefixes(); List l = new ArrayList(_vals.size() * prefixes.length); - for(Value v : _vals) { + for(Value v : _vals) { for (int j = 0; j < prefixes.length; j++) l.add(prefixes[j] + "." + v.getProperty()); } @@ -840,12 +843,14 @@ public class ConfigurationImpl */ public void setProperties(String resourceName) throws IOException { String anchor = null; - if (resourceName.indexOf("#") != -1) { + if (resourceName.indexOf("#") != -1) + { anchor = resourceName.substring(resourceName.lastIndexOf("#") + 1); resourceName = resourceName.substring(0, resourceName.length() - anchor.length() - 1); } - ProductDerivations.load(resourceName, anchor).setInto(this); + ProductDerivations.load(resourceName, anchor, + getClass().getClassLoader()).setInto(this); _auto = resourceName; } @@ -855,7 +860,8 @@ public class ConfigurationImpl * propertiesFile value with the name of a file. */ public void setPropertiesFile(File file) throws IOException { - ProductDerivations.load(file, null).setInto(this); + ProductDerivations.load(file, null, getClass().getClassLoader()). + setInto(this); _auto = file.toString(); } @@ -888,10 +894,10 @@ public class ConfigurationImpl ConfigurationImpl conf = (ConfigurationImpl) other; if (_vals.size() != conf.getValues().length) return false; - for(Value v : _vals) { + for(Value v : _vals) { String propName = v.getProperty(); - Value thisV = this.getValue(propName); - Value thatV = conf.getValue(propName); + Value thisV = this.getValue(propName); + Value thatV = conf.getValue(propName); if (!thisV.equals(thatV)) { return false; } @@ -906,7 +912,7 @@ public class ConfigurationImpl */ public int hashCode() { int hash = 0; - for(Value v : _vals) { + for(Value v : _vals) { hash += v.hashCode(); } return hash; @@ -938,8 +944,10 @@ public class ConfigurationImpl // surround sequences of digits with dashes. if (i != 0 - && ((!Character.isLetter(c) && Character.isLetter(propName.charAt(i - 1))) - || (Character.isLetter(c) && !Character.isLetter(propName.charAt(i - 1))))) + && ((!Character.isLetter(c) && Character.isLetter(propName + .charAt(i - 1))) + || (Character.isLetter(c) && !Character.isLetter(propName + .charAt(i - 1))))) buf.append('-'); buf.append(Character.toLowerCase(c)); @@ -951,6 +959,7 @@ public class ConfigurationImpl * Implementation of the {@link Externalizable} interface to read from * the properties written by {@link #writeExternal}. */ + @SuppressWarnings("unchecked") public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { fromProperties((Map) in.readObject()); @@ -974,8 +983,10 @@ public class ConfigurationImpl */ public Object clone() { try { - Constructor cons = getClass().getConstructor(new Class[]{ boolean.class }); - ConfigurationImpl clone = (ConfigurationImpl)cons.newInstance(new Object[]{ Boolean.FALSE }); + Constructor cons = getClass().getConstructor + (new Class[]{ boolean.class }); + ConfigurationImpl clone = (ConfigurationImpl) cons.newInstance + (new Object[]{ Boolean.FALSE }); clone.fromProperties(toProperties(true)); clone._props = (_props == null) ? null : new HashMap(_props); clone._globals = _globals; @@ -987,14 +998,14 @@ public class ConfigurationImpl } } - public boolean removeValue(Value val) { + public boolean removeValue(Value val) { if (!_vals.remove(val)) return false; val.removeListener(this); return true; } - public Value addValue(Value val) { + public T addValue(T val) { _vals.add(val); val.addListener(this); return val; @@ -1058,93 +1069,27 @@ public class ConfigurationImpl /** * Add the given value to the set of configuration properties. */ - public ObjectValue addObject(Class type, String property) { - ObjectValue val = new ObjectValue(type, property); + public ObjectValue addObject(String property) { + ObjectValue val = new ObjectValue(property); addValue(val); return val; } - /** - * Creates and adds a non-singleton {@link PluginValue plug-in value} of the given type. - * Property name of the plug-in is the simple name of the given type. - * - * @param type of the plug-in - * @param type class of the plug-in, often an interface - * @return the plug-in created - */ - public PluginValue addPlugin(Class type) { - return addPlugin(type, false); - } - - /** - * Creates and adds a {@link PluginValue plug-in value} of the given type. - * Property name of the plug-in is the simple name of the given type. - * - * @param type of the plug-in - * @param type class of the plug-in, often an interface - * @param singleton whether this plug-in is a singleton for this configuration - * @return the plug-in created - */ - public PluginValue addPlugin(Class type, boolean singleton) { - return addPlugin(type, type.getSimpleName(), singleton); - } - - /** - * Creates and adds a {@link PluginValue plug-in value} of the given type of the given property name. - * If the plug-in is a singleton set the instantiating getter method as get<property>Instance. - * - * @param type of the plug-in - * @param type class of the plug-in, often an interface - * @param property name of the plug-in - * @param singleton whether this plug-in is a singleton for this configuration - * @return the plug-in created - */ - public PluginValue addPlugin(Class type, String property, boolean singleton) { - PluginValue val = new PluginValue(type, property, singleton); - addValue(val); - if (singleton) { - val.setInstantiatingGetter("get" + removePrefix(property) + "Instance"); - } - return val; - } - /** * Add the given value to the set of configuration properties. */ - public PluginListValue addPluginList(Class type, String property) { - PluginListValue val = new PluginListValue(type, property); + public PluginValue addPlugin(String property, boolean singleton) { + PluginValue val = new PluginValue(property, singleton); addValue(val); return val; } - + /** * Add the given value to the set of configuration properties. */ - public > EnumValue addEnum(Class type, String property) { - EnumValue val = new EnumValue(type, property); + public PluginListValue addPluginList(String property) { + PluginListValue val = new PluginListValue(property); addValue(val); return val; } - - /** - * Adds an additional class loader to load the plug-in values. - */ - @Override - public MultiClassLoader addClassLoader(ClassLoader loader) { - _pluginLoader.addClassLoader(loader); - return _pluginLoader; - } - - /** - * Gets the {@link MultiClassLoader special class loader} to load plug-in values. - */ - @Override - public MultiClassLoader getClassLoader() { - return _pluginLoader; - } - - private String removePrefix(String s) { - int index = s.lastIndexOf('.'); - return index == -1 ? s : s.substring(index+1); - } } diff --git a/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/ConfigurationProvider.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/ConfigurationProvider.java index 2417ec2d1..d432ffc25 100644 --- a/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/ConfigurationProvider.java +++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/ConfigurationProvider.java @@ -20,21 +20,12 @@ package org.apache.openjpa.lib.conf; import java.util.Map; -import org.apache.openjpa.lib.util.MultiClassLoader; - /** - * Implementations of this interface populates {@link Configuration}s in - * some {@link ProductDerivation environment-specific} way. Implementations must implement the + * Implementations of this interface can populate {@link Configuration}s in + * some environment-specific way. Implementations must implement the * equals and hashCode methods so that equivalent * configurations compare equal. - *
    - * A provider looks up resources and resolves classes by their names before - * runtime is initialized. The class loader used by a provider eventually is - * {@link #setInto(Configuration) set} in the {@link Configuration configuration} for runtime. - * * - * @author Abe White - * @author Pinaki Poddar * @nojavadoc * @since 0.4.0.0 */ @@ -61,12 +52,4 @@ public interface ConfigurationProvider { * Set loaded information into the given configuration. */ public void setInto(Configuration conf); - - - /** - * Gets the loader to load plug-in and resources by class name. - * - * @since 2.2.0 - */ - public MultiClassLoader getClassLoader(); } diff --git a/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/Configurations.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/Configurations.java index 4f0b1c4fd..b2891c20a 100644 --- a/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/Configurations.java +++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/Configurations.java @@ -28,6 +28,8 @@ import java.util.List; import java.util.Map; import java.util.MissingResourceException; import java.util.Properties; +import java.util.TreeSet; +import java.util.concurrent.ConcurrentHashMap; import javax.naming.Context; import javax.naming.InitialContext; @@ -38,9 +40,11 @@ import org.apache.commons.lang.exception.NestableRuntimeException; import org.apache.openjpa.lib.log.Log; 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.lib.util.Options; import org.apache.openjpa.lib.util.ParseException; import org.apache.openjpa.lib.util.StringDistance; +import org.apache.openjpa.lib.util.concurrent.ConcurrentReferenceHashMap; import serp.util.Strings; @@ -52,8 +56,15 @@ import serp.util.Strings; */ public class Configurations { - private static final Localizer _loc = Localizer.forPackage(Configurations.class); + private static final Localizer _loc = Localizer.forPackage + (Configurations.class); + private static final ConcurrentReferenceHashMap _loaders = new + ConcurrentReferenceHashMap(ConcurrentReferenceHashMap.WEAK, + ConcurrentReferenceHashMap.HARD); + + private static final Object NULL_LOADER = "null-loader"; + /** * Return the class name from the given plugin string, or null if none. */ @@ -90,7 +101,8 @@ public class Configurations { // clsName(props) form if (clsName) return plugin.substring(0, openParen).trim(); - String prop = plugin.substring(openParen + 1, plugin.length() - 1).trim(); + String prop = plugin.substring(openParen + 1, + plugin.length() - 1).trim(); return (prop.length() == 0) ? null : prop; } @@ -140,17 +152,33 @@ public class Configurations { return getPlugin(cls, serializeProperties(props)); } - - public static Object newInstance(String clsName, Configuration conf, String props) { - return newInstance(clsName, conf, parseProperties(props)); - } /** - * Create and configure an instance with the given class name and properties. - * The class name is loaded using the {@link Configuration#getClassLoader() class loader} of - * the given configuration. + * Create the instance with the given class name, using the given + * class loader. No configuration of the instance is performed by + * this method. */ - public static Object newInstance(String clsName, Configuration conf, Properties props) { - Object obj = newInstance(clsName, null, conf, conf.getClassLoader(), true); + public static Object newInstance(String clsName, ClassLoader loader) { + return newInstance(clsName, null, null, loader, true); + } + + /** + * Create and configure an instance with the given class name and + * properties as a String. + */ + public static Object newInstance(String clsName, Configuration conf, + String props, ClassLoader loader) { + Object obj = newInstance(clsName, null, conf, loader, true); + configureInstance(obj, conf, props); + return obj; + } + + /** + * Create and configure an instance with the given class name and + * properties. + */ + public static Object newInstance(String clsName, Configuration conf, + Properties props, ClassLoader loader) { + Object obj = newInstance(clsName, null, conf, loader, true); configureInstance(obj, conf, props); return obj; } @@ -159,30 +187,52 @@ public class Configurations { * Helper method used by members of this package to instantiate plugin * values. */ - static T newInstance(String clsName, Value val, Configuration conf, ClassLoader loader, boolean fatal) { + static Object newInstance(String clsName, Value val, Configuration conf, + ClassLoader loader, boolean fatal) { if (StringUtils.isEmpty(clsName)) return null; - Class cls = null; + + Class cls = null; + while (cls == null) { - try { - cls = (Class)Class.forName(clsName, true, loader); - } catch (Exception e) { - if (loader != null) { // Try one more time with loader=null - loader = null; - } else { - RuntimeException re = getCreateException(clsName, val, loader, e); - if (fatal) - throw re; - Log log = (conf == null) ? null : conf.getConfigurationLog(); - if (log != null && log.isErrorEnabled()) - log.error(_loc.get("plugin-creation-exception", val), e); - return null; + // can't have a null reference in the map, so use symbolic + // constant as key + Object key = loader == null ? NULL_LOADER : loader; + Map loaderCache = (Map) _loaders.get(key); + if (loaderCache == null) { // We don't have a cache for this loader. + loaderCache = new ConcurrentHashMap(); + _loaders.put(key, loaderCache); + } else { // We have a cache for this loader. + cls = (Class) loaderCache.get(clsName); + } + + if (cls == null) { + try { + cls = Strings.toClass(clsName, findDerivedLoader(conf, + loader)); + loaderCache.put(clsName, cls); + } catch (RuntimeException re) { + if (loader != null) // Try one more time with loader=null + loader = null; + else { + if (val != null) + re = getCreateException(clsName, val, re); + if (fatal) + throw re; + Log log = (conf == null) ? null : conf + .getConfigurationLog(); + if (log != null && log.isErrorEnabled()) + log.error(_loc + .get("plugin-creation-exception", val), re); + return null; + } } } } try { - return (T) AccessController.doPrivileged(J2DoPrivHelper.newInstanceAction(cls)); + return AccessController.doPrivileged( + J2DoPrivHelper.newInstanceAction(cls)); } catch (Exception e) { if (e instanceof PrivilegedActionException) { e = ((PrivilegedActionException) e).getException(); @@ -198,7 +248,48 @@ public class Configurations { } } - + /** + * Attempt to find a derived loader that delegates to our target loader. + * This allows application loaders that delegate appropriately for known + * classes first crack at class names. + */ + private static ClassLoader findDerivedLoader(Configuration conf, + ClassLoader loader) { + // we always prefer the thread loader, because it's the only thing we + // can access that isn't bound to the OpenJPA classloader, unless + // the conf object is of a custom class + ClassLoader ctxLoader = AccessController.doPrivileged( + J2DoPrivHelper.getContextClassLoaderAction()); + if (loader == null) { + if (ctxLoader != null) + return ctxLoader; + if (conf != null) + return AccessController.doPrivileged( + J2DoPrivHelper.getClassLoaderAction(conf.getClass())); + return Configurations.class.getClassLoader(); + } + + for (ClassLoader parent = ctxLoader; parent != null; + parent = AccessController.doPrivileged( + J2DoPrivHelper.getParentAction(parent))) { + if (parent == loader) + return ctxLoader; + } + if (conf != null) { + for (ClassLoader parent = (ClassLoader) + AccessController.doPrivileged( + J2DoPrivHelper.getClassLoaderAction(conf.getClass())); + parent != null; + parent = AccessController.doPrivileged( + J2DoPrivHelper.getParentAction(parent))) { + if (parent == loader) + return AccessController.doPrivileged( + J2DoPrivHelper.getClassLoaderAction(conf.getClass())); + } + } + return loader; + } + /** * Return a List of all the fully-qualified anchors specified in the * properties location listed in opts. If no properties @@ -224,7 +315,8 @@ public class Configurations { return Arrays.asList(new String[] { props }); } - return ProductDerivations.getFullyQualifiedAnchorsInPropertiesLocation(props); + return ProductDerivations.getFullyQualifiedAnchorsInPropertiesLocation( + props); } /** @@ -255,14 +347,14 @@ public class Configurations { File file = new File(path); if ((AccessController.doPrivileged(J2DoPrivHelper .isFileAction(file))).booleanValue()) - provider = ProductDerivations.load(file, anchor); + provider = ProductDerivations.load(file, anchor, null); else { file = new File("META-INF" + File.separatorChar + path); if ((AccessController.doPrivileged(J2DoPrivHelper .isFileAction(file))).booleanValue()) - provider = ProductDerivations.load(file, anchor); + provider = ProductDerivations.load(file, anchor, null); else - provider = ProductDerivations.load(path, anchor); + provider = ProductDerivations.load(path, anchor, null); } if (provider != null) provider.setInto(conf); @@ -271,7 +363,7 @@ public class Configurations { props).getMessage(), Configurations.class.getName(), props); } else { - provider = ProductDerivations.loadDefaults(); + provider = ProductDerivations.loadDefaults(null); if (provider != null) provider.setInto(conf); } @@ -281,7 +373,8 @@ public class Configurations { /** * Helper method to throw an informative description on instantiation error. */ - private static RuntimeException getCreateException(String clsName, Value val, ClassLoader loader, Exception e) { + private static RuntimeException getCreateException(String clsName, + Value val, Exception e) { // re-throw the exception with some better information final String msg; final Object[] params; @@ -289,27 +382,30 @@ public class Configurations { String alias = val.alias(clsName); String[] aliases = val.getAliases(); String[] keys; - if (aliases.length == 0) { + if (aliases.length == 0) keys = aliases; - } else { + else { keys = new String[aliases.length / 2]; - for (int i = 0; i < aliases.length; i += 2) { + for (int i = 0; i < aliases.length; i += 2) keys[i / 2] = aliases[i]; - } - Arrays.sort(keys); } + String closest; if (keys.length == 0) { msg = "invalid-plugin"; - params = new Object[]{val.getProperty(), alias, e.toString(), loader}; - } else if ((closest = StringDistance.getClosestLevenshteinDistance(alias, keys, 0.5f)) == null) { + params = new Object[]{ val.getProperty(), alias, e.toString(), }; + } else if ((closest = StringDistance.getClosestLevenshteinDistance + (alias, keys, 0.5f)) == null) { msg = "invalid-plugin-aliases"; - params = new Object[]{val.getProperty(), alias, e.toString(), keys, loader}; + params = new Object[]{ + val.getProperty(), alias, e.toString(), + new TreeSet(Arrays.asList(keys)), }; } else { msg = "invalid-plugin-aliases-hint"; - params = new Object[]{val.getProperty(), alias, e.toString(), keys, closest, loader}; + params = new Object[]{ + val.getProperty(), alias, e.toString(), + new TreeSet(Arrays.asList(keys)), closest, }; } - e.printStackTrace(); return new ParseException(_loc.get(msg, params), e); } diff --git a/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/DoubleValue.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/DoubleValue.java index 0846b9d26..29b653379 100644 --- a/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/DoubleValue.java +++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/DoubleValue.java @@ -25,14 +25,17 @@ import org.apache.commons.lang.StringUtils; * * @author Marc Prud'hommeaux */ -public class DoubleValue extends Value { +public class DoubleValue extends Value { private double value; public DoubleValue(String prop) { - super(Double.class, prop); + super(prop); } + public Class getValueType() { + return double.class; + } /** * The internal value. @@ -57,10 +60,16 @@ public class DoubleValue extends Value { } protected void setInternalString(String val) { - set (StringUtils.isEmpty(val) ? 0D : Double.parseDouble(val)); + if (StringUtils.isEmpty(val)) + set(0D); + else + set(Double.parseDouble(val)); } protected void setInternalObject(Object obj) { - set (obj == null ? 0D : ((Number)obj).doubleValue()); + if (obj == null) + set(0D); + else + set(((Number) obj).doubleValue()); } } diff --git a/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/EnumValue.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/EnumValue.java deleted file mode 100644 index 8060aa7dc..000000000 --- a/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/EnumValue.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.openjpa.lib.conf; - -import java.util.EnumSet; - -public class EnumValue> extends ObjectValue { - - public EnumValue(Class type, String prop) { - super(type, prop); - setAliasListComprehensive(true); - EnumSet all = EnumSet.allOf(type); - for (T v : all) { - setAlias(v.toString(), v.toString().toLowerCase()); - } - } - - @Override - protected void setInternalString(String str) { - set(Enum.valueOf(getValueType(), str)); - } -} diff --git a/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/FileValue.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/FileValue.java index db673b84a..96bf7491e 100644 --- a/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/FileValue.java +++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/FileValue.java @@ -29,12 +29,16 @@ import org.apache.openjpa.lib.util.J2DoPrivHelper; * * @author Marc Prud'hommeaux */ -public class FileValue extends Value { +public class FileValue extends Value { private File value; public FileValue(String prop) { - super(File.class, prop); + super(prop); + } + + public Class getValueType() { + return File.class; } /** @@ -65,7 +69,7 @@ public class FileValue extends Value { } protected void setInternalObject(Object obj) { - set((File)obj); + set((File) obj); } } diff --git a/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/IntValue.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/IntValue.java index 006780034..d4c09cca0 100644 --- a/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/IntValue.java +++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/IntValue.java @@ -25,12 +25,16 @@ import org.apache.commons.lang.StringUtils; * * @author Marc Prud'hommeaux */ -public class IntValue extends Value { +public class IntValue extends Value { private int value; public IntValue(String prop) { - super(Number.class, prop); + super(prop); + } + + public Class getValueType() { + return int.class; } /** @@ -56,10 +60,16 @@ public class IntValue extends Value { } protected void setInternalString(String val) { - set (StringUtils.isEmpty(val) ? 0 : Integer.parseInt(val)); + if (StringUtils.isEmpty(val)) + set(0); + else + set(Integer.parseInt(val)); } - protected void setInternalObject(Object num) { - set (num == null ? 0 : ((Number)num).intValue()); + protected void setInternalObject(Object obj) { + if (obj == null) + set(0); + else + set(((Number) obj).intValue()); } } diff --git a/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/MapConfigurationProvider.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/MapConfigurationProvider.java index 267056dc2..90c7f0169 100644 --- a/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/MapConfigurationProvider.java +++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/MapConfigurationProvider.java @@ -18,51 +18,37 @@ */ package org.apache.openjpa.lib.conf; -import java.security.AccessController; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.apache.openjpa.lib.log.Log; -import org.apache.openjpa.lib.util.J2DoPrivHelper; import org.apache.openjpa.lib.util.Localizer; -import org.apache.openjpa.lib.util.MultiClassLoader; /** * Simple configuration provider that sets configuration based on a * provided map. - *
    - * This provider uses a {@link MultiClassLoader flat class loader} comprised - * of system class loader, context class loader and the loader that loaded - * this class itself. * * @author Abe White - * @author Pinaki Poddar * @nojavadoc */ public class MapConfigurationProvider implements ConfigurationProvider { - private Map _props; - private final MultiClassLoader _loader; - private static final Localizer _loc = Localizer.forPackage(MapConfigurationProvider.class); + + private static final Localizer _loc = Localizer.forPackage + (MapConfigurationProvider.class); + + private Map _props = null; /** - * Constructs a provider with default class loading scheme that employs - * system class loader, current thread context class loader and the - * class loader that loaded this class itself. + * Construct with null properties. */ public MapConfigurationProvider() { - _loader = AccessController.doPrivileged(J2DoPrivHelper.newMultiClassLoaderAction()); - _loader.addClassLoader(MultiClassLoader.SYSTEM_LOADER); - _loader.addClassLoader(MultiClassLoader.THREAD_LOADER); - _loader.addClassLoader(this.getClass().getClassLoader()); } - /** * Constructor; supply properties map. */ public MapConfigurationProvider(Map props) { - this(); addProperties(props); } @@ -89,18 +75,13 @@ public class MapConfigurationProvider implements ConfigurationProvider { } /** - * Set properties and class loader into configuration. + * Set properties into configuration. If the log is non-null, will log + * a TRACE message about the set. */ protected void setInto(Configuration conf, Log log) { - conf.addClassLoader(getClassLoader()); if (log != null && log.isTraceEnabled()) log.trace(_loc.get("conf-load", getProperties())); if (_props != null) conf.fromProperties(_props); } - - @Override - public MultiClassLoader getClassLoader() { - return _loader; - } } diff --git a/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/ObjectValue.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/ObjectValue.java index 08d86c211..eba5098ec 100644 --- a/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/ObjectValue.java +++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/ObjectValue.java @@ -18,72 +18,45 @@ */ package org.apache.openjpa.lib.conf; +import java.security.AccessController; + import org.apache.commons.lang.ObjectUtils; +import org.apache.openjpa.lib.util.J2DoPrivHelper; import org.apache.openjpa.lib.util.Localizer; +import org.apache.openjpa.lib.util.ReferenceMap; +import org.apache.openjpa.lib.util.concurrent.ConcurrentReferenceHashMap; /** * An object {@link Value}. * * @author Abe White - * @author Pinaki Poddar */ -public class ObjectValue extends Value { +public class ObjectValue extends Value { - private static final Localizer _loc = Localizer.forPackage(ObjectValue.class); + private static final Localizer _loc = Localizer.forPackage + (ObjectValue.class); // cache the types' classloader -// private static ConcurrentReferenceHashMap _classloaderCache = -// new ConcurrentReferenceHashMap(ReferenceMap.HARD, ReferenceMap.WEAK); + private static ConcurrentReferenceHashMap _classloaderCache = + new ConcurrentReferenceHashMap(ReferenceMap.HARD, ReferenceMap.WEAK); - private T _value = null; + private Object _value = null; - public ObjectValue(Class type, String prop) { - super(type, prop); - } - - public void setAlias(String key, Class value) { - setAlias(key, value.getName()); - } - - /** - * Sets the fully-qualified name of the given class as the value for an alias with fixed - * name "default". - * Also set the string value to the key i.e. value of this plug-in is set to its - * default value. - * - * @param value value for the alias. also the value set to this plug-in. - * - * @see #setDefaultAlias(String, Class) - */ - public void setDefaultAlias(Class value) { - setDefaultAlias("default", value); - } - - /** - * Sets the given key as the default alias for the fully-qualified name of the given class. - * Also set the string value to the key i.e. value of this plug-in is set to its - * default value. - * - * @param key alias which is also the default - * @param value value for the alias. also the value set to this plug-in. - */ - public void setDefaultAlias(String key, Class value) { - setAlias(key, value == null ? null : value.getName()); - setDefault(key); - setString(key); + public ObjectValue(String prop) { + super(prop); } /** * The internal value. */ - public T get() { + public Object get() { return _value; } /** * The internal value. */ - public void set(T obj) { + public void set(Object obj) { set(obj, false); } @@ -92,7 +65,7 @@ public class ObjectValue extends Value { * * @param derived if true, this value was derived from other properties */ - public void set(T obj, boolean derived) { + public void set(Object obj, boolean derived) { if (!derived) assertChangeable(); Object oldValue = _value; _value = obj; @@ -106,28 +79,29 @@ public class ObjectValue extends Value { * Instantiate the object as an instance of the given class. Equivalent * to instantiate(type, conf, true). */ - public T instantiate(Configuration conf) { - return instantiate(conf, true); + public Object instantiate(Class type, Configuration conf) { + return instantiate(type, conf, true); } /** * Instantiate the object as an instance of the given class. */ - public T instantiate(Configuration conf, boolean fatal) { + public Object instantiate(Class type, Configuration conf, boolean fatal) + { throw new UnsupportedOperationException(); } /** * Configure the given object. */ - public Object configure(T obj, Configuration conf) { + public Object configure(Object obj, Configuration conf) { return configure(obj, conf, true); } /** * Configure the given object. */ - public Object configure(T obj, Configuration conf, boolean fatal) { + public Object configure(Object obj, Configuration conf, boolean fatal) { throw new UnsupportedOperationException(); } @@ -135,10 +109,25 @@ public class ObjectValue extends Value { * Allow subclasses to instantiate additional plugins. This method does * not perform configuration. */ - public T newInstance(String clsName, Configuration conf, boolean fatal) { - return Configurations.newInstance(clsName, this, conf, conf.getClassLoader(), fatal); + public Object newInstance(String clsName, Class type, Configuration conf, + boolean fatal) { + ClassLoader cl = (ClassLoader) _classloaderCache.get(type); + if (cl == null) { + cl = AccessController.doPrivileged( + J2DoPrivHelper.getClassLoaderAction(type)); + if (cl == null) { // System classloader is returned as null + cl = AccessController.doPrivileged( + J2DoPrivHelper.getSystemClassLoaderAction()); + } + _classloaderCache.put(type, cl); + } + return Configurations.newInstance(clsName, this, conf, cl, fatal); } - + + public Class getValueType() { + return Object.class; + } + /** * Implement this method to synchronize internal data with the new * object value. @@ -154,15 +143,11 @@ public class ObjectValue extends Value { if (str == null) set(null); else - throw new IllegalArgumentException(_loc.get("cant-set-string", getProperty()).getMessage()); + throw new IllegalArgumentException(_loc.get("cant-set-string", + getProperty()).getMessage()); } protected void setInternalObject(Object obj) { - set((T)obj); + set(obj); } - - public Object getExternal() { - return isHidden() ? Value.INVISIBLE : getString(); - } - } diff --git a/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/PluginListValue.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/PluginListValue.java index 261f95cda..60df32452 100644 --- a/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/PluginListValue.java +++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/PluginListValue.java @@ -31,18 +31,15 @@ import org.apache.commons.lang.StringUtils; * @author Abe White * @see PluginValue */ -public class PluginListValue extends ObjectValue { +public class PluginListValue extends ObjectValue { private static final String[] EMPTY = new String[0]; private String[] _names = EMPTY; private String[] _props = EMPTY; - - private final Class elemType; - public PluginListValue(Class cls, String prop) { - super(cls, prop); - elemType = (Class)cls.getComponentType(); + public PluginListValue(String prop) { + super(prop); } /** @@ -84,16 +81,17 @@ public class PluginListValue extends ObjectValue { /** * Instantiate the plugins as instances of the given class. */ - public T[] instantiate(Configuration conf, boolean fatal) { - T[] ret; - if (_names.length == 0) { - ret = (T[])Array.newInstance(elemType, 0); - } else { - ret = (T[]) Array.newInstance(elemType, _names.length); + public Object instantiate(Class elemType, Configuration conf, + boolean fatal) { + Object[] ret; + if (_names.length == 0) + ret = (Object[]) Array.newInstance(elemType, 0); + else { + ret = (Object[]) Array.newInstance(elemType, _names.length); for (int i = 0; i < ret.length; i++) { - PluginValue elem = new PluginValue(elemType, "element", false); - ret[i] = elem.newInstance(_names[i], conf, fatal); - Configurations.configureInstance(ret[i], conf, _props[i], getProperty()); + ret[i] = newInstance(_names[i], elemType, conf, fatal); + Configurations.configureInstance(ret[i], conf, _props[i], + getProperty()); } } set(ret, true); @@ -184,6 +182,10 @@ public class PluginListValue extends ObjectValue { valueChanged(); } + public Class getValueType() { + return Object[].class; + } + protected void objectChanged() { Object[] vals = (Object[]) get(); if (vals == null || vals.length == 0) diff --git a/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/PluginValue.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/PluginValue.java index 117077694..10d68d4f7 100644 --- a/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/PluginValue.java +++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/PluginValue.java @@ -33,16 +33,17 @@ import org.apache.openjpa.lib.util.Localizer; * * @author Abe White */ -public class PluginValue extends ObjectValue { +public class PluginValue extends ObjectValue { - private static final Localizer _loc = Localizer.forPackage(PluginValue.class); + private static final Localizer _loc = Localizer.forPackage + (PluginValue.class); private final boolean _singleton; private String _name = null; private String _props = null; - public PluginValue(Class type, String prop, boolean singleton) { - super(type, prop); + public PluginValue(String prop, boolean singleton) { + super(prop); _singleton = singleton; } @@ -97,25 +98,32 @@ public class PluginValue extends ObjectValue { /** * Instantiate the plugin as an instance of the given class. */ - public T instantiate(Configuration conf, boolean fatal) { - T obj = newInstance(_name, conf, fatal); - return configure(obj, conf, fatal); + public Object instantiate(Class type, Configuration conf, boolean fatal) + { + Object obj = newInstance(_name, type, conf, fatal); + Configurations.configureInstance(obj, conf, _props, + (fatal) ? getProperty() : null); + if (_singleton) + set(obj, true); + return obj; } /** * Configure the given object. */ - public T configure(T obj, Configuration conf, boolean fatal) { - Configurations.configureInstance(obj, conf, _props, fatal ? getProperty() : null); + public Object configure(Object obj, Configuration conf, boolean fatal) { + Configurations.configureInstance(obj, conf, _props, + (fatal) ? getProperty() : null); if (_singleton) set(obj, true); return obj; } - public void set(T obj, boolean derived) { + public void set(Object obj, boolean derived) { if (!_singleton) - throw new IllegalStateException(_loc.get("not-singleton", getProperty()).getMessage()); + throw new IllegalStateException(_loc.get("not-singleton", + getProperty()).getMessage()); super.set(obj, derived); } @@ -133,6 +141,10 @@ public class PluginValue extends ObjectValue { valueChanged(); } + public Class getValueType() { + return Object.class; + } + protected void objectChanged() { Object obj = get(); _name = (obj == null) ? unalias(null) : obj.getClass().getName(); diff --git a/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/ProductDerivation.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/ProductDerivation.java index 38aa0e5e2..1034e66de 100644 --- a/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/ProductDerivation.java +++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/ProductDerivation.java @@ -25,12 +25,10 @@ import java.util.Set; /** * Hooks for deriving products with additional functionality. - * Parses configuration information from global, default or explicitly-specified + * Parses configuration information from global, default or explictly-specified * resources. All implementations of this interface will have a chance to mutate * a {@link Configuration} both before and after the user-specified - * configuration data is loaded. - *
    - * The order in which the product derivations are + * configuration data is loaded. The order in which the product derivations are * evaluated is determined by the specificity of the derivation type. * * @author Abe White @@ -57,21 +55,23 @@ public interface ProductDerivation { * loading classes for the product this derivation represents to be sure * they exist. Throw any throwable to indicate an invalid derivation. * Invalid derivations will not be used. - * Throw non-fatal {@link BootstrapException} to supress error reporting. */ - public void validate() throws Exception; + public void validate() + throws Exception; /** * Load globals into the returned ConfigurationProvider, or return null if * no globals are found. */ - public ConfigurationProvider loadGlobals() throws Exception; + public ConfigurationProvider loadGlobals(ClassLoader loader) + throws Exception; /** * Load defaults into the returned ConfigurationProvider, or return null if * no defaults are found. */ - public ConfigurationProvider loadDefaults() throws Exception; + public ConfigurationProvider loadDefaults(ClassLoader loader) + throws Exception; /** * Load the given given resource into the returned ConfigurationProvider, @@ -81,7 +81,9 @@ public interface ProductDerivation { * @param anchor optional named anchor within a multiple-configuration * resource */ - public ConfigurationProvider load(String resource, String anchor) throws Exception; + public ConfigurationProvider load(String resource, String anchor, + ClassLoader loader) + throws Exception; /** * Load given file, or return null if it is not a file this receiver @@ -89,7 +91,8 @@ public interface ProductDerivation { * * @param anchor optional named anchor within a multiple-configuration file */ - public ConfigurationProvider load(File file, String anchor) throws Exception; + public ConfigurationProvider load(File file, String anchor) + throws Exception; /** * Return a string identifying the default resource location for this @@ -110,7 +113,8 @@ public interface ProductDerivation { * * @since 1.1.0 */ - public List getAnchorsInFile(File file) throws IOException, Exception; + public List getAnchorsInFile(File file) throws IOException, + Exception; /** * Return a List of all the anchors defined in diff --git a/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/ProductDerivations.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/ProductDerivations.java index 3067d7f06..b9cd4a5a1 100644 --- a/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/ProductDerivations.java +++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/ProductDerivations.java @@ -34,6 +34,7 @@ import java.util.TreeSet; import org.apache.commons.lang.StringUtils; import org.apache.openjpa.lib.util.J2DoPrivHelper; +import org.apache.openjpa.lib.util.JavaVersions; import org.apache.openjpa.lib.util.Localizer; import org.apache.openjpa.lib.util.MultiClassLoader; import org.apache.openjpa.lib.util.Services; @@ -47,7 +48,8 @@ import org.apache.openjpa.lib.util.Services; */ public class ProductDerivations { - private static final Localizer _loc = Localizer.forPackage(ProductDerivations.class); + private static final Localizer _loc = Localizer.forPackage + (ProductDerivations.class); private static final ProductDerivation[] _derivations; private static final String[] _derivationNames; @@ -60,25 +62,22 @@ public class ProductDerivations { l.addClassLoader(1, AccessController.doPrivileged(J2DoPrivHelper.getContextClassLoaderAction())); _derivationNames = Services.getImplementors(ProductDerivation.class, l); _derivationErrors = new Throwable[_derivationNames.length]; - List derivations = new ArrayList(_derivationNames.length); + List derivations = + new ArrayList(_derivationNames.length); boolean errors = false; for (int i = 0; i < _derivationNames.length; i++) { try { ProductDerivation d = (ProductDerivation) - AccessController.doPrivileged(J2DoPrivHelper.newInstanceAction( + AccessController.doPrivileged( + J2DoPrivHelper.newInstanceAction( Class.forName(_derivationNames[i], true, l))); d.validate(); derivations.add(d); } catch (Throwable t) { - if (t instanceof BootstrapException && !((BootstrapException)t).isFatal()) { - // do nothing - } else { - if (t instanceof PrivilegedActionException) { - t = ((PrivilegedActionException) t).getException(); - } - _derivationErrors[i] = t; - errors = true; - } + if (t instanceof PrivilegedActionException) + t = ((PrivilegedActionException) t).getException(); + _derivationErrors[i] = t; + errors = true; } } @@ -93,11 +92,14 @@ public class ProductDerivations { // if some derivations weren't instantiable, warn if (errors) - System.err.println(_loc.get("bad-product-derivations", ProductDerivations.class.getName())); + System.err.println(_loc.get("bad-product-derivations", + ProductDerivations.class.getName())); for (int i = 0; i < _derivationErrors.length; i++) { - if (_derivationErrors[i] != null) { - System.err.println(_derivationNames[i] + ":" + _derivationErrors[i]); - } + if (_derivationErrors[i] == null) + continue; + System.err.println(_derivationNames[i] + ":" + + _derivationErrors[i]); + break; } Collections.sort(derivations, new ProductDerivationComparator()); @@ -158,18 +160,22 @@ public class ProductDerivations { for (int i = 0; map != null && i < _prefixes.length; i++) { String fullKey = _prefixes[i] + "." + partialKey; if (map.containsKey(fullKey)) { - if (firstKey == null) { + if (firstKey == null) firstKey = fullKey; - } else { + else { // if we've already found a property with a previous // prefix, then this is a collision. - throw new IllegalStateException(_loc.get("dup-with-different-prefixes", firstKey, fullKey) + throw new IllegalStateException(_loc.get( + "dup-with-different-prefixes", firstKey, fullKey) .getMessage()); } } } - return (firstKey == null) ? _prefixes[0] + "." + partialKey : firstKey; + if (firstKey == null) + return _prefixes[0] + "." + partialKey; + else + return firstKey; } /** @@ -252,16 +258,20 @@ public class ProductDerivations { * @param anchor optional named anchor within a multiple-configuration * resource */ - public static ConfigurationProvider load(String resource, String anchor) { + public static ConfigurationProvider load(String resource, String anchor, + ClassLoader loader) { if (StringUtils.isEmpty(resource)) return null; + if (loader == null) + loader = AccessController.doPrivileged( + J2DoPrivHelper.getContextClassLoaderAction()); ConfigurationProvider provider = null; StringBuilder errs = null; // most specific to least Throwable err = null; for (int i = _derivations.length - 1; i >= 0; i--) { try { - provider = _derivations[i].load(resource, anchor); + provider = _derivations[i].load(resource, anchor, loader); if (provider != null) return provider; } catch (Throwable t) { @@ -284,9 +294,13 @@ public class ProductDerivations { * * @param anchor optional named anchor within a multiple-configuration file */ - public static ConfigurationProvider load(File file, String anchor) { + public static ConfigurationProvider load(File file, String anchor, + ClassLoader loader) { if (file == null) return null; + if (loader == null) + loader = AccessController.doPrivileged( + J2DoPrivHelper.getContextClassLoaderAction()); ConfigurationProvider provider = null; StringBuilder errs = null; Throwable err = null; @@ -315,21 +329,26 @@ public class ProductDerivations { /** * Return a {@link ConfigurationProvider} that has parsed system defaults. */ - public static ConfigurationProvider loadDefaults() { - return load(false); + public static ConfigurationProvider loadDefaults(ClassLoader loader) { + return load(loader, false); } /** * Return a {@link ConfigurationProvider} that has parsed system globals. */ - public static ConfigurationProvider loadGlobals() { - return load(true); + public static ConfigurationProvider loadGlobals(ClassLoader loader) { + return load(loader, true); } /** * Load a built-in resource location. */ - private static ConfigurationProvider load(boolean globals) { + private static ConfigurationProvider load(ClassLoader loader, + boolean globals) { + if (loader == null) + loader = AccessController.doPrivileged( + J2DoPrivHelper.getContextClassLoaderAction()); + ConfigurationProvider provider = null; StringBuilder errs = null; String type = (globals) ? "globals" : "defaults"; @@ -337,8 +356,8 @@ public class ProductDerivations { // most specific to least for (int i = _derivations.length - 1; i >= 0; i--) { try { - provider = (globals) ? _derivations[i].loadGlobals() - : _derivations[i].loadDefaults(); + provider = (globals) ? _derivations[i].loadGlobals(loader) + : _derivations[i].loadDefaults(loader); if (provider != null) return provider; } catch (Throwable t) { @@ -379,39 +398,47 @@ public class ProductDerivations { StringBuilder errs = null; Throwable err = null; for (int i = _derivations.length - 1; i >= 0; i--) { - ProductDerivation d = _derivations[i]; try { if (propertiesLocation == null) { - String loc = d.getDefaultResourceLocation(); - addAll(fqAnchors, loc, d.getAnchorsInResource(loc)); + String loc = _derivations[i].getDefaultResourceLocation(); + addAll(fqAnchors, loc, + _derivations[i].getAnchorsInResource(loc)); continue; } File f = new File(propertiesLocation); - if (J2DoPrivHelper.isFileAction(f).run().booleanValue()) { - addAll(fqAnchors, propertiesLocation, d.getAnchorsInFile(f)); + if (((Boolean) J2DoPrivHelper.isFileAction(f).run()) + .booleanValue()) { + addAll(fqAnchors, propertiesLocation, + _derivations[i].getAnchorsInFile(f)); } else { - f = new File("META-INF" + File.separatorChar + propertiesLocation); - if (J2DoPrivHelper.isFileAction(f).run().booleanValue()) { - addAll(fqAnchors, propertiesLocation, d.getAnchorsInFile(f)); + f = new File("META-INF" + File.separatorChar + + propertiesLocation); + if (((Boolean) J2DoPrivHelper.isFileAction(f).run()) + .booleanValue()) { + addAll(fqAnchors, propertiesLocation, + _derivations[i].getAnchorsInFile(f)); } else { - addAll(fqAnchors, propertiesLocation, d.getAnchorsInResource(propertiesLocation)); + addAll(fqAnchors, propertiesLocation, + _derivations[i].getAnchorsInResource( + propertiesLocation)); } } } catch (Throwable t) { err = t; errs = (errs == null) ? new StringBuilder() : errs.append("\n"); - errs.append(d.getClass().getName() + ":" + t); + errs.append(_derivations[i].getClass().getName() + ":" + t); } } reportErrors(errs, propertiesLocation, err); return fqAnchors; } - private static void addAll(Collection collection, String base, Collection newMembers) { + private static void addAll(Collection collection, String base, + Collection newMembers) { if (newMembers == null || collection == null) return; - for (Iterator iter = newMembers.iterator(); iter.hasNext(); ) { + for (Iterator iter = newMembers.iterator(); iter.hasNext(); ) { String fqLoc = base + "#" + iter.next(); if (!collection.contains(fqLoc)) collection.add(fqLoc); diff --git a/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/StringListValue.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/StringListValue.java index 3326da430..bdc7b9219 100644 --- a/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/StringListValue.java +++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/StringListValue.java @@ -32,7 +32,7 @@ import serp.util.Strings; * * @author Abe White */ -public class StringListValue extends Value { +public class StringListValue extends Value { public static final String[] EMPTY = new String[0]; private static final Localizer s_loc = Localizer.forPackage @@ -41,7 +41,7 @@ public class StringListValue extends Value { private String[] _values = EMPTY; public StringListValue(String prop) { - super(String[].class, prop); + super(prop); } /** @@ -60,6 +60,10 @@ public class StringListValue extends Value { return _values; } + public Class getValueType() { + return String[].class; + } + /** * Unalias the value list. This method defers to super.unalias() * UNLESS the string passed is a list of values for a property that @@ -130,7 +134,7 @@ public class StringListValue extends Value { } protected void setInternalObject(Object obj) { - set((String[])obj); + set((String[]) obj); } protected List getAliasList() { diff --git a/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/StringValue.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/StringValue.java index d4f0713ed..61e5ffddc 100644 --- a/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/StringValue.java +++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/StringValue.java @@ -25,12 +25,16 @@ import org.apache.commons.lang.StringUtils; * * @author Marc Prud'hommeaux */ -public class StringValue extends Value { +public class StringValue extends Value { private String value; public StringValue(String prop) { - super(String.class, prop); + super(prop); + } + + public Class getValueType() { + return String.class; } /** @@ -60,7 +64,11 @@ public class StringValue extends Value { } protected void setInternalObject(Object obj) { - set(obj == null ? null : obj.toString()); + if (obj instanceof String) { + set((String) obj); + } else { + set(obj == null ? null : obj.toString()); + } } } diff --git a/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/Value.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/Value.java index 01c5806aa..ebba45513 100644 --- a/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/Value.java +++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/Value.java @@ -31,69 +31,44 @@ import org.apache.openjpa.lib.util.Localizer; import org.apache.openjpa.lib.util.ParseException; /** - * A value of a user-configurable property. - * The runtime {@link Configuration configuration} is essentially comprised of a set of values. - *
    - * Each Value is identified by a property key. A value can also have other {@link #getEquivalentKeys() equivalent - * keys}. The user can configure using either the primary or the equivalent keys. For example, the user can configure - * the JDBC driver either by openjpa.ConnectionDriverName or javax.persistence.jdbc.driver. - *
    - * A Value can be aliased. For example, a value of a fully qualified class name - * org.apache.openjpa.ee.ManagedRuntime can be aliased simply as managed. - * Some values can have a {@link #isAliasListComprehensive() fixed} set of aliases such as values that represents - * an enumeration. - *
    - * A Value may have a {@link #getDefault() default} value. Setting a default value does not imply that the vale is - * set to the default value. The value is explicitly set by {@link #setObject(Object) set} method. - *
    - * The values are often printed on console etc. hence the values that carry sensitive information such as - * password can be {@link #hide() hidden}. - *
    - * Most values get frozen after an OpenJPA runtime is initialized. However, a value can be modified at runtime - * only if it is declared as {@link #setDynamic(boolean) dynamic}. Dynamic change of a value is significant because - * the identity of a OpenJPA runtime is hash code of {@link Configuration configuration} which, in turn, is hash code - * of its values. This identity is critical to locate a OpenJPA runtime. The dynamic values remember their original - * value and that original value is used its hash code computation. - *
    - * Listeners can be {@link #addListener(ValueListener) added} to a value to be notified of changes. - *

    - * Value is made generic since version 2.2.0. The generic type implies the type of value e.g. Value<Integer> - * holds integer value. + * A configuration value. * * @author Marc Prud'hommeaux * @author Pinaki Poddar */ -public abstract class Value implements Cloneable { +public abstract class Value implements Cloneable { - private static final String[] EMPTY_ALIASES = new String[0]; - private static final Set EMPTY_SET = Collections.emptySet(); - - public static final String INVISIBLE = "******"; + private static final String[] EMPTY_ALIASES = new String[0]; private static final Localizer s_loc = Localizer.forPackage(Value.class); + public static final String INVISIBLE = "******"; - private final String _prop; - private final Class _type; - private String loadKey; - private String def; - private String[] aliases; - private String getter; - private List listeners; - private boolean aliasListComprehensive; - private Class scope; - private boolean isDynamic; - private String originalValue; - private Set otherNames; - private boolean _hidden; - private boolean _private; + private String prop = null; + private String loadKey = null; + private String def = null; + private String[] aliases = null; + private String getter = null; + private List listeners = null; + private boolean aliasListComprehensive = false; + private Class scope = null; + private boolean isDynamic = false; + private String originalValue = null; + private Set otherNames = null; + private boolean _hidden = false; + private boolean _private = false; + /** + * Default constructor. + */ + public Value() { + } + /** * Constructor. Supply the property name. * * @see #setProperty */ - public Value(Class type, String prop) { - _type = type; - _prop = prop; + public Value(String prop) { + setProperty(prop); } /** @@ -101,9 +76,17 @@ public abstract class Value implements Cloneable { * getting this value in a {@link Map}. */ public String getProperty() { - return _prop; + return prop; } + /** + * The property name that will be used when setting or + * getting this value in a {@link Map}. + */ + public void setProperty(String prop) { + this.prop = prop; + } + /** * Adds a moniker that is equivalent to the original property key used * during construction. @@ -123,7 +106,8 @@ public abstract class Value implements Cloneable { * @since 2.0.0 */ public Set getEquivalentKeys() { - return otherNames == null ? EMPTY_SET : Collections.unmodifiableSet(otherNames); + return otherNames == null ? Collections.EMPTY_SET + : Collections.unmodifiableSet(otherNames); } /** @@ -134,7 +118,8 @@ public abstract class Value implements Cloneable { * @since 2.0.0 */ public List getPropertyKeys() { - List result = new ArrayList(1 + (otherNames ==null ? 0 : otherNames.size())); + List result = new ArrayList(1 + + (otherNames ==null ? 0 : otherNames.size())); result.add(getProperty()); if (otherNames != null) result.addAll(otherNames); @@ -164,8 +149,9 @@ public abstract class Value implements Cloneable { * already loaded key. */ public void setLoadKey(String key) { - if (loadKey != null && key != null && !loadKey.equals(key)) - throw new ParseException(s_loc.get("multiple-load-key", loadKey, key)); + if (this.loadKey != null && key != null && !this.loadKey.equals(key)) + throw new ParseException(s_loc.get("multiple-load-key", + loadKey, key)); loadKey = key; } @@ -197,7 +183,7 @@ public abstract class Value implements Cloneable { public void setAlias(String key, String value) { aliases = setAlias(key, value, aliases); } - + /** * Set an alias into a current alias list, returning the new list. */ @@ -224,7 +210,7 @@ public abstract class Value implements Cloneable { * value. If so, an error will be generated when attempting to invoke * any method on this value with an unknown option. */ - public final boolean isAliasListComprehensive() { + public boolean isAliasListComprehensive() { return aliasListComprehensive; } @@ -233,7 +219,7 @@ public abstract class Value implements Cloneable { * value. If so, an error will be generated when attempting to invoke * any method on this value with an unknown option. */ - public final void setAliasListComprehensive(boolean aliasListIsComprehensive) { + public void setAliasListComprehensive(boolean aliasListIsComprehensive) { this.aliasListComprehensive = aliasListIsComprehensive; } @@ -309,7 +295,7 @@ public abstract class Value implements Cloneable { /** * The name of the getter method for the instantiated value of this - * property (as opposed to the string value) + * property(as opposed to the string value) */ public String getInstantiatingGetter() { return getter; @@ -331,7 +317,7 @@ public abstract class Value implements Cloneable { * be used by the configuration framework to look up metadata about * the value. */ - public Class getScope() { + public Class getScope() { return scope; } @@ -340,7 +326,7 @@ public abstract class Value implements Cloneable { * be used by the configuration framework to look up metadata about * the value. */ - public void setScope(Class cls) { + public void setScope(Class cls) { scope = cls; } @@ -355,7 +341,7 @@ public abstract class Value implements Cloneable { /** * Set this value from the given string. If the given string is null or * empty and a default is defined, the default is used. If the given - * string (or default) is an alias key, it will be converted to the + * string(or default) is an alias key, it will be converted to the * corresponding value internally. *
    * If this Value is being set to a non-default value for the first time @@ -376,7 +362,7 @@ public abstract class Value implements Cloneable { } catch (ParseException pe) { throw pe; } catch (RuntimeException re) { - throw new ParseException(_prop + ": " + val, re); + throw new ParseException(prop + ": " + val, re); } } @@ -390,11 +376,11 @@ public abstract class Value implements Cloneable { * {@link #isDynamic() dynamic}. * */ - public void setObject(T obj) { + public void setObject(Object obj) { // if setting to null set as string to get defaults into play - if (obj == null && def != null) { + if (obj == null && def != null) setString(null); - } else { + else { try { setInternalObject(obj); if (originalValue == null && obj != null && !isDefault(obj)) { @@ -403,7 +389,7 @@ public abstract class Value implements Cloneable { } catch (ParseException pe) { throw pe; } catch (RuntimeException re) { - throw new ParseException(_prop + ": " + obj, re); + throw new ParseException(prop + ": " + obj, re); } } } @@ -427,12 +413,25 @@ public abstract class Value implements Cloneable { /** * Returns the type of the property that this Value represents. */ - public final Class getValueType() { - return _type; - } + public abstract Class getValueType(); /** - * Gets unmodifiable list of listeners for value changes. + * Return the internal string form of this value. + */ + protected abstract String getInternalString(); + + /** + * Set this value from the given string. + */ + protected abstract void setInternalString(String str); + + /** + * Set this value from an object. + */ + protected abstract void setInternalObject(Object obj); + + /** + * Gets unmodifable list of listeners for value changes. */ public List getListeners() { return Collections.unmodifiableList(this.listeners); @@ -500,7 +499,7 @@ public abstract class Value implements Cloneable { * * @since 1.1.0 */ - public final void setDynamic(boolean flag) { + public void setDynamic(boolean flag) { isDynamic = flag; } @@ -510,7 +509,7 @@ public abstract class Value implements Cloneable { * * @since 1.1.0 */ - public final boolean isDynamic() { + public boolean isDynamic() { return isDynamic; } @@ -523,7 +522,7 @@ public abstract class Value implements Cloneable { public int hashCode() { String str = (isDynamic()) ? getOriginalValue() : getString(); int strHash = (str == null) ? 0 : str.hashCode(); - int propHash = (_prop == null) ? 0 : _prop.hashCode(); + int propHash = (prop == null) ? 0 : prop.hashCode(); return strHash ^ propHash; } @@ -539,11 +538,11 @@ public abstract class Value implements Cloneable { if (!(other instanceof Value)) return false; - Value o = (Value) other; + Value o = (Value) other; String thisStr = (isDynamic()) ? getOriginalValue() : getString(); String thatStr = (isDynamic()) ? o.getOriginalValue() : o.getString(); return (isDynamic() == o.isDynamic()) - && StringUtils.equals(_prop, o.getProperty()) + && StringUtils.equals(prop, o.getProperty()) && StringUtils.equals(thisStr, thatStr); } @@ -567,7 +566,7 @@ public abstract class Value implements Cloneable { /** * Hides the value of this Value from being output to the caller. */ - public final void hide() { + public void hide() { _hidden = true; } @@ -575,49 +574,23 @@ public abstract class Value implements Cloneable { * Affirms if this Value is used for internal purpose only and not exposed as a supported property. * @see Configuration#getPropertyKeys() */ - public final boolean isPrivate() { + public boolean isPrivate() { return _private; } /** * Marks this Value for internal purpose only. */ - public final void makePrivate() { + public void makePrivate() { _private = true; } - /** - * Gets the external visible form of this value. - * @return - */ - public Object getExternal() { - return _hidden ? INVISIBLE : get(); - } - - public String toString() { - return getProperty() + "<" + getValueType().getSimpleName() + ">:" + get(); - } - - /** * Get the actual data stored in this value. */ - public abstract T get(); + public abstract Object get(); - /** - * Return the internal string form of this value. - */ - protected abstract String getInternalString(); - - /** - * Set this value from the given string. - */ - protected abstract void setInternalString(String str); - - /** - * Set this value from an object. - */ - protected abstract void setInternalObject(Object obj); - - + public String toString() { + return getProperty()+ ":" + get() + "[" + getValueType().getName() + "]"; + } } diff --git a/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/ValueListener.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/ValueListener.java index 5d272807a..a73a39a2d 100644 --- a/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/ValueListener.java +++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/ValueListener.java @@ -28,5 +28,5 @@ public interface ValueListener { /** * Callback used by {@link Value} objects to notify listener of change. */ - public void valueChanged(Value val); + public void valueChanged(Value val); } diff --git a/openjpa-lib/src/main/java/org/apache/openjpa/lib/instrumentation/AbstractInstrumentationProvider.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/instrumentation/AbstractInstrumentationProvider.java index 478c88665..8c8b36941 100644 --- a/openjpa-lib/src/main/java/org/apache/openjpa/lib/instrumentation/AbstractInstrumentationProvider.java +++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/instrumentation/AbstractInstrumentationProvider.java @@ -38,7 +38,7 @@ public abstract class AbstractInstrumentationProvider implements Instrumentation private Map _instruments = new ConcurrentHashMap(); private boolean _started = false; - private PluginListValue _instrumentValues; + private PluginListValue _instrumentValues; private String _options; private Configuration _config; @@ -57,13 +57,13 @@ public abstract class AbstractInstrumentationProvider implements Instrumentation } public void setInstrument(String instrument) { - _instrumentValues = new PluginListValue(Instrument[].class, "Instrument"); + _instrumentValues = new PluginListValue("Instrument"); if (getInstrumentAliases() != null) { _instrumentValues.setAliases(getInstrumentAliases()); } _instrumentValues.setString(instrument); - Instrument[] instruments = _instrumentValues.instantiate(_config); + Instrument[] instruments = (Instrument[])_instrumentValues.instantiate(Instrument.class, _config); for (Instrument inst : instruments) { inst.setProvider(this); _instruments.put(inst.getName(), inst); diff --git a/openjpa-lib/src/main/java/org/apache/openjpa/lib/meta/CFMetaDataParser.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/meta/CFMetaDataParser.java index ca7374b8b..a0c2d056d 100644 --- a/openjpa-lib/src/main/java/org/apache/openjpa/lib/meta/CFMetaDataParser.java +++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/meta/CFMetaDataParser.java @@ -36,15 +36,16 @@ import serp.util.Strings; */ public class CFMetaDataParser extends XMLMetaDataParser { - static final String[] PACKAGES = new String[]{"java.lang.", "java.util.", "java.math." }; - private static final Localizer _loc = Localizer.forPackage(CFMetaDataParser.class); + static final String[] PACKAGES = new String[]{ + "java.lang.", "java.util.", "java.math." }; + private static final Localizer _loc = Localizer.forPackage + (CFMetaDataParser.class); // the current package and class being parsed private String _package = null; private String _class = null; - public CFMetaDataParser(ClassLoader loader) { - super(loader); + public CFMetaDataParser() { setParseText(false); } @@ -281,7 +282,8 @@ public class CFMetaDataParser extends XMLMetaDataParser { throws SAXException { if (name == null) return null; - Class cls = classForName(name, _package, resolve, getClassLoader()); + Class cls = + classForName(name, _package, resolve, currentClassLoader()); if (cls == null) throw getException(_loc.get("invalid-class", name).getMessage()); return cls; @@ -296,6 +298,9 @@ public class CFMetaDataParser extends XMLMetaDataParser { if (StringUtils.isEmpty(name)) return null; + if (loader == null) + loader = AccessController.doPrivileged( + J2DoPrivHelper.getContextClassLoaderAction()); boolean fullName = name.indexOf('.') != -1; boolean noPackage = StringUtils.isEmpty(pkg); try { diff --git a/openjpa-lib/src/main/java/org/apache/openjpa/lib/meta/ClassArgParser.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/meta/ClassArgParser.java index 6ef7915d7..642fd1a25 100644 --- a/openjpa-lib/src/main/java/org/apache/openjpa/lib/meta/ClassArgParser.java +++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/meta/ClassArgParser.java @@ -66,13 +66,15 @@ public class ClassArgParser { private static final int TOKEN_PACKAGE_NOATTR = 3; private static final int TOKEN_CLASS_NOATTR = 4; - private static final Localizer _loc = Localizer.forPackage(ClassArgParser.class); + private static final Localizer _loc = Localizer.forPackage + (ClassArgParser.class); private ClassLoader _loader = null; private char[] _packageAttr = "name".toCharArray(); private char[] _classAttr = "name".toCharArray(); private char[][] _beginElements = { { 'p' }, { 'c' } }; - private char[][] _endElements = { "ackage".toCharArray(), "lass".toCharArray() }; + private char[][] _endElements = { "ackage".toCharArray(), + "lass".toCharArray() }; /** * The class loader with which to load parsed classes. @@ -104,14 +106,14 @@ public class ClassArgParser { for (; true; charIdx++) { for (int i = 0; i < buf.length; i++) { if (i == 0) { - if (charIdx == packageElementName.length()) { - throw new UnsupportedOperationException(_loc.get("cant-diff-elems").getMessage()); - } + if (charIdx == packageElementName.length()) + throw new UnsupportedOperationException(_loc.get + ("cant-diff-elems").getMessage()); buf[i] = packageElementName.charAt(charIdx); } else { - if (charIdx == classElementNames[i - 1].length()) { - throw new UnsupportedOperationException(_loc.get("cant-diff-elems").getMessage()); - } + if (charIdx == classElementNames[i - 1].length()) + throw new UnsupportedOperationException(_loc.get + ("cant-diff-elems").getMessage()); buf[i] = classElementNames[i - 1].charAt(charIdx); } } @@ -119,15 +121,21 @@ public class ClassArgParser { break; } - _packageAttr = (packageAttributeName == null) ? null : packageAttributeName.toCharArray(); - _classAttr = (classAttributeName == null) ? null : classAttributeName.toCharArray(); + _packageAttr = (packageAttributeName == null) ? null + : packageAttributeName.toCharArray(); + _classAttr = (classAttributeName == null) ? null + : classAttributeName.toCharArray(); _beginElements = new char[classElementNames.length + 1][]; _endElements = new char[classElementNames.length + 1][]; - _beginElements[0] = packageElementName.substring(0, charIdx + 1).toCharArray(); - _endElements[0] = packageElementName.substring(charIdx + 1).toCharArray(); + _beginElements[0] = packageElementName.substring(0, charIdx + 1). + toCharArray(); + _endElements[0] = packageElementName.substring(charIdx + 1). + toCharArray(); for (int i = 0; i < classElementNames.length; i++) { - _beginElements[i + 1] = classElementNames[i].substring(0, charIdx + 1).toCharArray(); - _endElements[i + 1] = classElementNames[i].substring(charIdx + 1).toCharArray(); + _beginElements[i + 1] = classElementNames[i]. + substring(0, charIdx + 1).toCharArray(); + _endElements[i + 1] = classElementNames[i]. + substring(charIdx + 1).toCharArray(); } } @@ -205,12 +213,10 @@ public class ClassArgParser { try { File file = Files.getFile(arg, _loader); - if (arg.endsWith(".class")) { + if (arg.endsWith(".class")) return new String[]{ getFromClassFile(file) }; - } - if (arg.endsWith(".java")) { + if (arg.endsWith(".java")) return new String[]{ getFromJavaFile(file) }; - } if ((AccessController.doPrivileged( J2DoPrivHelper.existsAction(file))).booleanValue()) { Collection col = getFromMetaDataFile(file); diff --git a/openjpa-lib/src/main/java/org/apache/openjpa/lib/meta/ClassMetaDataIterator.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/meta/ClassMetaDataIterator.java index 6c9d45187..7922c27f0 100644 --- a/openjpa-lib/src/main/java/org/apache/openjpa/lib/meta/ClassMetaDataIterator.java +++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/meta/ClassMetaDataIterator.java @@ -21,7 +21,6 @@ package org.apache.openjpa.lib.meta; import java.io.File; import java.io.IOException; import java.io.InputStream; -import java.net.URI; import java.net.URL; import java.net.URLDecoder; import java.security.AccessController; @@ -56,7 +55,16 @@ public class ClassMetaDataIterator implements MetaDataIterator { * Constructor; supply the class whose metadata to find, the suffix * of metadata files, and whether to parse top-down or bottom-up. */ - public ClassMetaDataIterator(Class cls, String suffix, ClassLoader loader, boolean topDown) { + public ClassMetaDataIterator(Class cls, String suffix, boolean topDown) { + this(cls, suffix, null, topDown); + } + + /** + * Constructor; supply the class whose metadata to find, the suffix + * of metadata files, and whether to parse top-down or bottom-up. + */ + public ClassMetaDataIterator(Class cls, String suffix, + ClassLoader loader, boolean topDown) { // skip classes that can't have metadata if (cls != null && (cls.isPrimitive() || cls.getName().startsWith("java.") @@ -72,8 +80,11 @@ public class ClassMetaDataIterator implements MetaDataIterator { multi.addClassLoader(MultiClassLoader.SYSTEM_LOADER); multi.addClassLoader(MultiClassLoader.THREAD_LOADER); multi.addClassLoader(getClass().getClassLoader()); - if (cls != null) { - ClassLoader clsLoader = AccessController.doPrivileged(J2DoPrivHelper.getClassLoaderAction(cls)); + if (cls != null) + { + ClassLoader clsLoader = (ClassLoader) + AccessController.doPrivileged( + J2DoPrivHelper.getClassLoaderAction(cls)); if (clsLoader != null) multi.addClassLoader(clsLoader); } diff --git a/openjpa-lib/src/main/java/org/apache/openjpa/lib/meta/MetaDataParser.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/meta/MetaDataParser.java index ca88e581d..8c53b2530 100644 --- a/openjpa-lib/src/main/java/org/apache/openjpa/lib/meta/MetaDataParser.java +++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/meta/MetaDataParser.java @@ -32,6 +32,12 @@ import java.util.List; */ public interface MetaDataParser { + /** + * The classloader to use to resolve resources, or null for impl-defined + * default. + */ + public void setClassLoader(ClassLoader loader); + /** * Return the results from the last parse. */ diff --git a/openjpa-lib/src/main/java/org/apache/openjpa/lib/meta/ResourceMetaDataIterator.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/meta/ResourceMetaDataIterator.java index 1e9d5a113..d2f3321bc 100644 --- a/openjpa-lib/src/main/java/org/apache/openjpa/lib/meta/ResourceMetaDataIterator.java +++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/meta/ResourceMetaDataIterator.java @@ -44,17 +44,33 @@ public class ResourceMetaDataIterator implements MetaDataIterator { private List _urls = null; private int _url = -1; + /** + * Constructor; supply the resource to parse. + */ + public ResourceMetaDataIterator(String rsrc) throws IOException { + this(rsrc, null); + } + /** * Constructor; supply the resource to parse. */ public ResourceMetaDataIterator(String rsrc, ClassLoader loader) throws IOException { + if (loader == null) { + MultiClassLoader multi = AccessController + .doPrivileged(J2DoPrivHelper.newMultiClassLoaderAction()); + multi.addClassLoader(MultiClassLoader.SYSTEM_LOADER); + multi.addClassLoader(MultiClassLoader.THREAD_LOADER); + multi.addClassLoader(getClass().getClassLoader()); + loader = multi; + } + try { - Enumeration e = AccessController.doPrivileged(J2DoPrivHelper.getResourcesAction(loader, rsrc)); + Enumeration e = AccessController.doPrivileged( + J2DoPrivHelper.getResourcesAction(loader, rsrc)); while (e.hasMoreElements()) { - if (_urls == null) { + if (_urls == null) _urls = new ArrayList(3); - } _urls.add(e.nextElement()); } } catch (PrivilegedActionException pae) { @@ -87,7 +103,8 @@ public class ResourceMetaDataIterator implements MetaDataIterator { if (_url == -1 || _url >= _urls.size()) throw new IllegalStateException(); File file = new File(URLDecoder.decode((_urls.get(_url)).getFile())); - return ((AccessController.doPrivileged(J2DoPrivHelper.existsAction(file))).booleanValue()) ? file :null; + return ((AccessController.doPrivileged( + J2DoPrivHelper.existsAction(file))).booleanValue()) ? file :null; } public void close() { diff --git a/openjpa-lib/src/main/java/org/apache/openjpa/lib/meta/SourceTracker.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/meta/SourceTracker.java index fa8989158..be7a2c5e4 100644 --- a/openjpa-lib/src/main/java/org/apache/openjpa/lib/meta/SourceTracker.java +++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/meta/SourceTracker.java @@ -22,7 +22,7 @@ import java.io.File; /** * Interface that can optionally be implemented by metadata - * to include the source URL from which the metadata was originally parsed. + * to include the source file from which the metadata was originally parsed. * * @author Abe White */ @@ -33,7 +33,7 @@ public interface SourceTracker { public static final int SRC_XML = 2; /** - * Return the URL from which this instance was parsed. + * Return the file from which this instance was parsed. */ public File getSourceFile(); diff --git a/openjpa-lib/src/main/java/org/apache/openjpa/lib/meta/XMLMetaDataParser.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/meta/XMLMetaDataParser.java index 651a3a94e..423f8d310 100644 --- a/openjpa-lib/src/main/java/org/apache/openjpa/lib/meta/XMLMetaDataParser.java +++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/meta/XMLMetaDataParser.java @@ -55,9 +55,6 @@ import org.apache.openjpa.lib.xml.XMLFactory; /** * Custom SAX parser used by the system to quickly parse metadata files. * Subclasses should handle the processing of the content. - *
    - * The parsers may need to resolve parsed strings to actual class instances. - * * * @author Abe White * @nojavadoc @@ -65,7 +62,8 @@ import org.apache.openjpa.lib.xml.XMLFactory; public abstract class XMLMetaDataParser extends DefaultHandler implements LexicalHandler, MetaDataParser { - private static final Localizer _loc = Localizer.forPackage(XMLMetaDataParser.class); + private static final Localizer _loc = Localizer.forPackage + (XMLMetaDataParser.class); private static boolean _schemaBug; static { @@ -73,8 +71,9 @@ public abstract class XMLMetaDataParser extends DefaultHandler // check for Xerces version 2.0.2 to see if we need to disable // schema validation, which works around the bug reported at: // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4708859 - _schemaBug = "Xerces-J 2.0.2".equals(Class.forName("org.apache.xerces.impl.Version") - .getField("fVersion").get(null)); + _schemaBug = "Xerces-J 2.0.2".equals(Class.forName + ("org.apache.xerces.impl.Version").getField("fVersion"). + get(null)); } catch (Throwable t) { // Xerces might not be available _schemaBug = false; @@ -83,8 +82,8 @@ public abstract class XMLMetaDataParser extends DefaultHandler // map of classloaders to sets of parsed locations, so that we don't parse // the same resource multiple times for the same class - private Set _parsed = null; - + private Map> _parsed = null; + private Log _log = null; private boolean _validating = true; private boolean _systemId = true; @@ -92,8 +91,8 @@ public abstract class XMLMetaDataParser extends DefaultHandler private boolean _parseText = true; private boolean _parseComments = true; private String _suffix = null; -// private ClassLoader _loader = null; -// private ClassLoader _curLoader = null; + private ClassLoader _loader = null; + private ClassLoader _curLoader = null; // state for current parse private final Collection _curResults = new LinkedList(); @@ -108,12 +107,17 @@ public abstract class XMLMetaDataParser extends DefaultHandler private int _ignore = Integer.MAX_VALUE; private boolean _parsing = false; - private final ClassLoader _loader; - protected XMLMetaDataParser(ClassLoader loader) { - _loader = loader; + private boolean _overrideContextClassloader = false; + + public boolean getOverrideContextClassloader() { + return _overrideContextClassloader; } - + + public void setOverrideContextClassloader(boolean overrideCCL) { + _overrideContextClassloader = overrideCCL; + } + /* * Whether the parser is currently parsing. */ @@ -263,16 +267,16 @@ public abstract class XMLMetaDataParser extends DefaultHandler /** * Classloader to use for class name resolution. */ -// public ClassLoader getClassLoader() { -// return _loader; -// } + public ClassLoader getClassLoader() { + return _loader; + } /** * Classloader to use for class name resolution. */ -// public void setClassLoader(ClassLoader loader) { -// _loader = loader; -// } + public void setClassLoader(ClassLoader loader) { + _loader = loader; + } public List getResults() { if (_results == null) @@ -293,7 +297,8 @@ public abstract class XMLMetaDataParser extends DefaultHandler public void parse(File file) throws IOException { if (file == null) return; - if (!(AccessController.doPrivileged(J2DoPrivHelper.isDirectoryAction(file))).booleanValue()) + if (!(AccessController.doPrivileged(J2DoPrivHelper + .isDirectoryAction(file))).booleanValue()) parse(new FileMetaDataIterator(file)); else { String suff = (_suffix == null) ? "" : _suffix; @@ -302,9 +307,9 @@ public abstract class XMLMetaDataParser extends DefaultHandler } } - public void parse(Class cls, boolean topDown) throws IOException { + public void parse(Class cls, boolean topDown) throws IOException { String suff = (_suffix == null) ? "" : _suffix; - parse(new ClassMetaDataIterator(cls, suff, _loader, topDown), !topDown); + parse(new ClassMetaDataIterator(cls, suff, topDown), !topDown); } public void parse(Reader xml, String sourceName) throws IOException { @@ -364,7 +369,8 @@ public abstract class XMLMetaDataParser extends DefaultHandler _log.trace(_loc.get("parser-schema-bug")); schemaSource = null; } - boolean validating = _validating && (getDocType() != null || schemaSource != null); + boolean validating = _validating && (getDocType() != null + || schemaSource != null); // parse the metadata with a SAX parser try { @@ -372,8 +378,22 @@ public abstract class XMLMetaDataParser extends DefaultHandler _sourceName = sourceName; SAXParser parser = null; + boolean overrideCL = _overrideContextClassloader; + ClassLoader oldLoader = null; + ClassLoader newLoader = null; try { + if (overrideCL == true) { + oldLoader = + (ClassLoader) AccessController.doPrivileged(J2DoPrivHelper.getContextClassLoaderAction()); + newLoader = XMLMetaDataParser.class.getClassLoader(); + AccessController.doPrivileged(J2DoPrivHelper.setContextClassLoaderAction(newLoader)); + + if (_log != null && _log.isTraceEnabled()) { + _log.trace(_loc.get("override-contextclassloader-begin", oldLoader, newLoader)); + } + } + parser = XMLFactory.getSAXParser(validating, true); Object schema = null; if (validating) { @@ -383,12 +403,16 @@ public abstract class XMLMetaDataParser extends DefaultHandler } if (_parseComments || _lh != null) - parser.setProperty("http://xml.org/sax/properties/lexical-handler", this); + parser.setProperty + ("http://xml.org/sax/properties/lexical-handler", this); if (schema != null) { - parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage", + parser.setProperty + ("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema"); - parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", schema); + parser.setProperty + ("http://java.sun.com/xml/jaxp/properties/schemaSource", + schema); } InputSource is = new InputSource(xml); @@ -401,6 +425,19 @@ public abstract class XMLMetaDataParser extends DefaultHandler ioe.initCause(se); throw ioe; } finally { + if (overrideCL == true) { + // Restore the old ContextClassloader + try { + if (_log != null && _log.isTraceEnabled()) { + _log.trace(_loc.get("override-contextclassloader-end", newLoader, oldLoader)); + } + AccessController.doPrivileged(J2DoPrivHelper.setContextClassLoaderAction(oldLoader)); + } catch (Throwable t) { + if (_log != null && _log.isWarnEnabled()) { + _log.warn(_loc.get("restore-contextclassloader-failed")); + } + } + } } } finally { reset(); @@ -415,9 +452,15 @@ public abstract class XMLMetaDataParser extends DefaultHandler if (!_caching) return false; if (_parsed == null) - _parsed = new HashSet(); + _parsed = new HashMap>(); - boolean added = _parsed.add(src); + ClassLoader loader = currentClassLoader(); + Set set = _parsed.get(loader); + if (set == null) { + set = new HashSet(); + _parsed.put(loader, set); + } + boolean added = set.add(src); if (!added && _log != null && _log.isTraceEnabled()) _log.trace(_loc.get("already-parsed", src)); return !added; @@ -551,7 +594,7 @@ public abstract class XMLMetaDataParser extends DefaultHandler */ protected void reset() { _curResults.clear(); -// _curLoader = null; + _curLoader = null; _sourceName = null; _sourceFile = null; _depth = -1; @@ -647,13 +690,14 @@ public abstract class XMLMetaDataParser extends DefaultHandler * Return the class loader to use when resolving resources and loading * classes. */ -// protected ClassLoader currentClassLoader() { -// if (_loader != null) -// return _loader; -// if (_curLoader == null) -// _curLoader = AccessController.doPrivileged(J2DoPrivHelper.getContextClassLoaderAction()); -// return _curLoader; -// } + protected ClassLoader currentClassLoader() { + if (_loader != null) + return _loader; + if (_curLoader == null) + _curLoader = AccessController.doPrivileged( + J2DoPrivHelper.getContextClassLoaderAction()); + return _curLoader; + } /** * Ignore all content below the current element. @@ -700,12 +744,4 @@ public abstract class XMLMetaDataParser extends DefaultHandler protected void clearDeferredMetaData() { } - - /** - * Gets the class loader used by this parser to resolve classes - * or locate resources. - */ - protected final ClassLoader getClassLoader() { - return _loader; - } } diff --git a/openjpa-lib/src/main/java/org/apache/openjpa/lib/meta/XMLVersionParser.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/meta/XMLVersionParser.java index d67642a3e..1ae225f1b 100644 --- a/openjpa-lib/src/main/java/org/apache/openjpa/lib/meta/XMLVersionParser.java +++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/meta/XMLVersionParser.java @@ -18,9 +18,6 @@ */ package org.apache.openjpa.lib.meta; -import java.util.LinkedHashSet; -import java.util.Set; - import org.xml.sax.Attributes; import org.xml.sax.SAXException; @@ -37,18 +34,16 @@ public class XMLVersionParser extends XMLMetaDataParser { public static final String VERSION_2_0 = "2.0"; static private final String VERSION_ATTR = "version"; - static private final String XSI_NS = "http://www.w3.org/2001/XMLSchema-instance"; + static private final String XSI_NS = + "http://www.w3.org/2001/XMLSchema-instance"; static private final String SCHEMA_LOCATION = "schemaLocation"; private String _rootElement; private String _version; private String _schemaLocation; - private Set _unitNames; public XMLVersionParser(String rootElement) { - super(null); _rootElement = rootElement; - _unitNames = new LinkedHashSet(); setCaching(false); setValidating(false); setParseText(false); @@ -66,10 +61,8 @@ public class XMLVersionParser extends XMLMetaDataParser { // save the version and schema location attributes _version = attrs.getValue("", VERSION_ATTR); _schemaLocation = attrs.getValue(XSI_NS, SCHEMA_LOCATION); - } else if (name.equals("persistence-unit")) { - _unitNames.add(attrs.getValue("name")); - // ignore remaining content - ignoreContent(true); + // ignore remaining content + ignoreContent(true); } return false; } @@ -89,8 +82,4 @@ public class XMLVersionParser extends XMLMetaDataParser { public String getSchemaLocation() { return _schemaLocation; } - - public Set unitNames() { - return _unitNames; - } } diff --git a/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/JavaVendors.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/JavaVendors.java index 39a2ea909..cda67568e 100644 --- a/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/JavaVendors.java +++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/JavaVendors.java @@ -24,8 +24,7 @@ import java.security.AccessController; * Utilities for dealing with different Java vendors. */ public enum JavaVendors { - IBM("com.ibm.tools.attach.VirtualMachine"), - SUN("com.sun.tools.attach.VirtualMachine"), + IBM("com.ibm.tools.attach.VirtualMachine"), SUN("com.sun.tools.attach.VirtualMachine"), // When in doubt, try the Sun implementation. OTHER("com.sun.tools.attach.VirtualMachine"); diff --git a/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/MultiClassLoader.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/MultiClassLoader.java index ec1317be8..98f71031f 100644 --- a/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/MultiClassLoader.java +++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/MultiClassLoader.java @@ -23,7 +23,6 @@ import java.net.URL; import java.security.AccessController; import java.security.PrivilegedActionException; import java.util.ArrayList; -import java.util.Arrays; import java.util.Enumeration; import java.util.Iterator; import java.util.List; @@ -48,10 +47,11 @@ public class MultiClassLoader extends ClassLoader { /** * The standard system class loader. */ - public static final ClassLoader SYSTEM_LOADER = AccessController.doPrivileged( + public static final ClassLoader SYSTEM_LOADER = + AccessController.doPrivileged( J2DoPrivHelper.getSystemClassLoaderAction()); - private List _loaders = new ArrayList(5); + private List _loaders = new ArrayList(5); /** * Constructor; initializes the loader with an empty list of delegates. @@ -81,12 +81,12 @@ public class MultiClassLoader extends ClassLoader { public ClassLoader[] getClassLoaders() { ClassLoader[] loaders = new ClassLoader[size()]; ClassLoader loader; - Iterator itr = _loaders.iterator(); + Iterator itr = _loaders.iterator(); for (int i = 0; i < loaders.length; i++) { - loader = itr.next(); - if (loader == THREAD_LOADER) { - loader = AccessController.doPrivileged(J2DoPrivHelper.getContextClassLoaderAction()); - } + loader = (ClassLoader) itr.next(); + if (loader == THREAD_LOADER) + loader = AccessController.doPrivileged( + J2DoPrivHelper.getContextClassLoaderAction()); loaders[i] = loader; } return loaders; @@ -96,10 +96,10 @@ public class MultiClassLoader extends ClassLoader { * Return the class loader at the given index. */ public ClassLoader getClassLoader(int index) { - ClassLoader loader = _loaders.get(index); - if (loader == THREAD_LOADER) { - loader = AccessController.doPrivileged(J2DoPrivHelper.getContextClassLoaderAction()); - } + ClassLoader loader = (ClassLoader) _loaders.get(index); + if (loader == THREAD_LOADER) + loader = AccessController.doPrivileged( + J2DoPrivHelper.getContextClassLoaderAction()); return loader; } @@ -125,7 +125,7 @@ public class MultiClassLoader extends ClassLoader { _loaders.add(index, loader); return true; } - + /** * Set the class loaders of this loader to those of the given loader. */ @@ -146,8 +146,8 @@ public class MultiClassLoader extends ClassLoader { // use iterator so that the thread loader is not resolved boolean added = false; - for (Iterator itr = multi._loaders.iterator(); itr.hasNext();) { - if (addClassLoader(index, itr.next())) { + for (Iterator itr = multi._loaders.iterator(); itr.hasNext();) { + if (addClassLoader(index, (ClassLoader) itr.next())) { index++; added = true; } @@ -166,8 +166,8 @@ public class MultiClassLoader extends ClassLoader { // use iterator so that the thread loader is not resolved boolean added = false; - for (Iterator itr = multi._loaders.iterator(); itr.hasNext();) - added = addClassLoader(itr.next()) || added; + for (Iterator itr = multi._loaders.iterator(); itr.hasNext();) + added = addClassLoader((ClassLoader) itr.next()) || added; return added; } @@ -195,18 +195,19 @@ public class MultiClassLoader extends ClassLoader { } /** - * Return true if there are no internal class loaders. + * Return true if there are no internal class laoders. */ public boolean isEmpty() { return _loaders.isEmpty(); } - protected Class findClass(String name) throws ClassNotFoundException { + protected Class findClass(String name) throws ClassNotFoundException { ClassLoader loader; - for (Iterator itr = _loaders.iterator(); itr.hasNext();) { - loader = itr.next(); + for (Iterator itr = _loaders.iterator(); itr.hasNext();) { + loader = (ClassLoader) itr.next(); if (loader == THREAD_LOADER) - loader = AccessController.doPrivileged(J2DoPrivHelper.getContextClassLoaderAction()); + loader = AccessController.doPrivileged( + J2DoPrivHelper.getContextClassLoaderAction()); try { return Class.forName(name, false, loader); } catch (Throwable t) { @@ -218,15 +219,17 @@ public class MultiClassLoader extends ClassLoader { protected URL findResource(String name) { ClassLoader loader; URL rsrc; - for (Iterator itr = _loaders.iterator(); itr.hasNext();) { - loader = itr.next(); + for (Iterator itr = _loaders.iterator(); itr.hasNext();) { + loader = (ClassLoader) itr.next(); if (loader == THREAD_LOADER) - loader = AccessController.doPrivileged(J2DoPrivHelper.getContextClassLoaderAction()); + loader = AccessController.doPrivileged( + J2DoPrivHelper.getContextClassLoaderAction()); if (loader == null) // skip continue; - rsrc = AccessController.doPrivileged(J2DoPrivHelper.getResourceAction(loader, name)); + rsrc = AccessController.doPrivileged( + J2DoPrivHelper.getResourceAction(loader, name)); if (rsrc != null) return rsrc; } @@ -235,19 +238,21 @@ public class MultiClassLoader extends ClassLoader { protected Enumeration findResources(String name) throws IOException { ClassLoader loader; - Enumeration rsrcs; + Enumeration rsrcs; Object rsrc; - Vector all = new Vector(); - for (Iterator itr = _loaders.iterator(); itr.hasNext();) { - loader = itr.next(); + Vector all = new Vector(); + for (Iterator itr = _loaders.iterator(); itr.hasNext();) { + loader = (ClassLoader) itr.next(); if (loader == THREAD_LOADER) - loader = AccessController.doPrivileged(J2DoPrivHelper.getContextClassLoaderAction()); + loader = AccessController.doPrivileged( + J2DoPrivHelper.getContextClassLoaderAction()); if (loader == null) // skip continue; try { - rsrcs = AccessController.doPrivileged(J2DoPrivHelper.getResourcesAction(loader, name)); + rsrcs = AccessController.doPrivileged( + J2DoPrivHelper.getResourcesAction(loader, name)); while (rsrcs.hasMoreElements()) { rsrc = rsrcs.nextElement(); if (!all.contains(rsrc)) @@ -271,8 +276,4 @@ public class MultiClassLoader extends ClassLoader { public int hashCode() { return _loaders.hashCode(); } - - public String toString() { - return _loaders.toString(); - } } diff --git a/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/Services.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/Services.java index b58a157c9..73471aa7d 100644 --- a/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/Services.java +++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/Services.java @@ -59,7 +59,7 @@ public class Services { * Return an array of Strings of class names of all known service * implementors of the specified interface or class. */ - public static String[] getImplementors(Class serviceClass) { + public static String[] getImplementors(Class serviceClass) { return getImplementors(serviceClass, null); } @@ -67,7 +67,8 @@ public class Services { * Return an array of Strings of class names of all known service * implementors of the specified interface or class. */ - public static String[] getImplementors(Class serviceClass, ClassLoader loader) { + public static String[] getImplementors(Class serviceClass, + ClassLoader loader) { return getImplementors(serviceClass.getName(), loader); } @@ -85,15 +86,22 @@ public class Services { * implementors of the specified class name, as resolved by the specified * {@link ClassLoader}. */ - public static String[] getImplementors(String serviceName, ClassLoader loader) { + public static String[] getImplementors(String serviceName, + ClassLoader loader) { + if (loader == null) + loader = AccessController.doPrivileged( + J2DoPrivHelper.getContextClassLoaderAction()); + try { - Set resourceList = new TreeSet(); - Enumeration resources = AccessController.doPrivileged(J2DoPrivHelper.getResourcesAction(loader, + Set resourceList = new TreeSet(); + Enumeration resources = AccessController.doPrivileged( + J2DoPrivHelper.getResourcesAction(loader, PREFIX + serviceName)); - while (resources.hasMoreElements()) { + while (resources.hasMoreElements()) addResources((URL) resources.nextElement(), resourceList); - } - return resourceList.toArray(new String[resourceList.size()]); + + return (String[]) resourceList.toArray(new String[resourceList + .size()]); } catch (PrivilegedActionException pae) { // silently swallow all exceptions. } catch (IOException ioe) { @@ -107,10 +115,11 @@ public class Services { * Set. Class names are separated by lines. Lines starting with '#' are * ignored. */ - private static void addResources(URL url, Set set) throws IOException { + private static void addResources(URL url, Set set) throws IOException { InputStream in = null; BufferedReader reader = null; URLConnection urlCon = null; + try { urlCon = url.openConnection(); urlCon.setUseCaches(false); @@ -128,10 +137,8 @@ public class Services { String next = tok.nextToken(); if (next != null) { next = next.trim(); - if (next.length() > 0 && !next.startsWith("#")) { + if (next.length() > 0 && !next.startsWith("#")) set.add(next); - } - } } } diff --git a/openjpa-lib/src/main/resources/org/apache/openjpa/lib/conf/localizer.properties b/openjpa-lib/src/main/resources/org/apache/openjpa/lib/conf/localizer.properties index 01c84e3e1..a05b320eb 100644 --- a/openjpa-lib/src/main/resources/org/apache/openjpa/lib/conf/localizer.properties +++ b/openjpa-lib/src/main/resources/org/apache/openjpa/lib/conf/localizer.properties @@ -51,17 +51,15 @@ invalid-property-hint: The configuration property named "{0}" was not \ property called "{1}". invalid-plugin: Instantiation of plugin "{0}" with value "{1}" caused an \ error "{2}". The alias or class name may have been misspelled, or the \ - class may not be available in the class path. The classloader used is \ - "{3}" + class may not be available in the class path. invalid-plugin-aliases: Instantiation of plugin "{0}" with value "{1}" caused \ an error "{2}". The alias or class name may have been misspelled, or the \ class may not have be available in the class path. Valid aliases for this \ - plugin are: {3}. The classloader used is "{4}". + plugin are: {3} invalid-plugin-aliases-hint: Instantiation of plugin "{0}" with value "{1}" \ caused an error "{2}". The alias or class name may have been misspelled \ (as it closely matches the valid plugin alias "{4}"), or the class may \ - not be available in the class path. Valid aliases for this plugin are: {3}.\ - The classloader used is "{5}" + not be available in the class path. Valid aliases for this plugin are: {3} not-singleton: You cannot set the value of property "{0}" as an object. The \ property cannot use a single value; it must be recreated on each request. cant-set-string: Configuration property "{0}" cannot be set from a string. \ diff --git a/openjpa-lib/src/test/java/org/apache/openjpa/lib/conf/TestValue.java b/openjpa-lib/src/test/java/org/apache/openjpa/lib/conf/TestValue.java index f39233c90..bcbaf7ea1 100644 --- a/openjpa-lib/src/test/java/org/apache/openjpa/lib/conf/TestValue.java +++ b/openjpa-lib/src/test/java/org/apache/openjpa/lib/conf/TestValue.java @@ -22,13 +22,13 @@ import junit.framework.TestCase; public class TestValue extends TestCase { - private static class SimpleValue extends Value { + private static class SimpleValue extends Value { - public SimpleValue(String prop) { - super(String.class, prop); - } + protected String getInternalString() { + return null; + } - protected String getInternalString() { + public Class getValueType() { return null; } @@ -39,7 +39,7 @@ public class TestValue extends TestCase { protected void setInternalString(String str) { } - public String get() { + public Object get() { return null; } @@ -51,7 +51,7 @@ public class TestValue extends TestCase { String bName = "Pete"; String [] aStrings = { alias, aName }; - SimpleValue sValue = new SimpleValue("test"); + SimpleValue sValue = new SimpleValue(); sValue.setAliases(aStrings); sValue.setAlias(alias, bName); assertEquals("Did not set the new alias", bName, @@ -60,7 +60,8 @@ public class TestValue extends TestCase { } public void testEquivalentValueCanBeSet() { - SimpleValue v = new SimpleValue("main"); + SimpleValue v = new SimpleValue(); + v.setProperty("main"); v.addEquivalentKey("eqivalent1"); v.addEquivalentKey("eqivalent2"); assertEquals(2, v.getEquivalentKeys().size()); @@ -74,7 +75,8 @@ public class TestValue extends TestCase { } public void testEquivalentValuesAreUnmodifable() { - SimpleValue v = new SimpleValue("main"); + SimpleValue v = new SimpleValue(); + v.setProperty("main"); v.addEquivalentKey("eqivalent1"); v.addEquivalentKey("eqivalent2"); diff --git a/openjpa-lib/src/test/java/org/apache/openjpa/lib/conf/test/ConfigurationTestProductDerivation.java b/openjpa-lib/src/test/java/org/apache/openjpa/lib/conf/test/ConfigurationTestProductDerivation.java index 301c31b65..e06648dc6 100644 --- a/openjpa-lib/src/test/java/org/apache/openjpa/lib/conf/test/ConfigurationTestProductDerivation.java +++ b/openjpa-lib/src/test/java/org/apache/openjpa/lib/conf/test/ConfigurationTestProductDerivation.java @@ -21,7 +21,6 @@ package org.apache.openjpa.lib.conf.test; import java.io.InputStream; import java.io.IOException; import java.net.URL; -import java.security.AccessController; import java.util.MissingResourceException; import java.util.Properties; @@ -30,7 +29,6 @@ import org.apache.openjpa.lib.conf.Configuration; import org.apache.openjpa.lib.conf.ConfigurationProvider; import org.apache.openjpa.lib.conf.MapConfigurationProvider; import org.apache.openjpa.lib.conf.ProductDerivation; -import org.apache.openjpa.lib.util.J2DoPrivHelper; /** * A Product Derivation to test loading of global and default configuration with @@ -53,18 +51,19 @@ public class ConfigurationTestProductDerivation closed = true; } - public ConfigurationProvider loadGlobals() + public ConfigurationProvider loadGlobals(ClassLoader loader) throws IOException { - return load(null); + return load(null, loader); } - public ConfigurationProvider load(String rsrc) throws IOException { + public ConfigurationProvider load(String rsrc, ClassLoader loader) + throws IOException { if (rsrc == null) rsrc = System.getProperty("openjpatest.properties"); if (rsrc == null || !rsrc.endsWith(".properties")) return null; - URL url = findResource(rsrc); + URL url = findResource(rsrc, loader); if (url == null) throw new MissingResourceException(rsrc, getClass().getName(), rsrc); @@ -85,9 +84,8 @@ public class ConfigurationTestProductDerivation /** * Locate the given resource. */ - private URL findResource(String rsrc) + private URL findResource(String rsrc, ClassLoader loader) throws IOException { - ClassLoader loader = Thread.currentThread().getContextClassLoader(); if (loader != null) return loader.getResource(rsrc); @@ -97,6 +95,7 @@ public class ConfigurationTestProductDerivation if (loader != null) url = loader.getResource(rsrc); if (url == null) { + loader = Thread.currentThread().getContextClassLoader(); if (loader != null) url = loader.getResource(rsrc); } diff --git a/openjpa-lib/src/test/java/org/apache/openjpa/lib/conf/test/TestConfigurationImpl.java b/openjpa-lib/src/test/java/org/apache/openjpa/lib/conf/test/TestConfigurationImpl.java index 01974c626..ea4d300bf 100644 --- a/openjpa-lib/src/test/java/org/apache/openjpa/lib/conf/test/TestConfigurationImpl.java +++ b/openjpa-lib/src/test/java/org/apache/openjpa/lib/conf/test/TestConfigurationImpl.java @@ -256,8 +256,8 @@ public class TestConfigurationImpl extends AbstractTestCase { private final StringValue _testKey; private final StringValue _sysKey; - private final PluginValue _pluginKey; - private final ObjectValue _objectKey; + private final PluginValue _pluginKey; + private final ObjectValue _objectKey; public ConfigurationTest() { this(true); @@ -267,8 +267,8 @@ public class TestConfigurationImpl extends AbstractTestCase { super(false); _testKey = addString("testKey"); _sysKey = addString("sysKey"); - _pluginKey = addPlugin(Object.class, "pluginKey", canSetPlugin); - _objectKey = addObject(Object.class, "objectKey"); + _pluginKey = addPlugin("pluginKey", canSetPlugin); + _objectKey = addObject("objectKey"); } public String getTestKey() { @@ -297,7 +297,7 @@ public class TestConfigurationImpl extends AbstractTestCase { public Object getPluginKeyInstance() { if (_pluginKey.get() == null) - return _pluginKey.instantiate(this); + return _pluginKey.instantiate(Object.class, this); return _pluginKey.get(); } diff --git a/openjpa-lib/src/test/java/org/apache/openjpa/lib/conf/test/TestPluginValue.java b/openjpa-lib/src/test/java/org/apache/openjpa/lib/conf/test/TestPluginValue.java index f3b027e04..e894e2338 100644 --- a/openjpa-lib/src/test/java/org/apache/openjpa/lib/conf/test/TestPluginValue.java +++ b/openjpa-lib/src/test/java/org/apache/openjpa/lib/conf/test/TestPluginValue.java @@ -38,9 +38,9 @@ public class TestPluginValue extends AbstractTestCase { public void testDefault() { defaultTest(new StringValue("testKey")); - defaultTest(new PluginValue(String.class, "testKey", true)); - defaultTest(new PluginListValue(String[].class, "testKey")); - pluginDefaultTest(new PluginValue(String.class, "testKey", true)); + defaultTest(new PluginValue("testKey", true)); + defaultTest(new PluginListValue("testKey")); + pluginDefaultTest(new PluginValue("testKey", true)); } private void defaultTest(Value val) { @@ -76,13 +76,13 @@ public class TestPluginValue extends AbstractTestCase { public void testAlias() { aliasTest(new StringValue("testKey")); - aliasTest(new PluginValue(String.class, "testKey", true)); - aliasTest(new PluginListValue(String[].class, "testKey")); + aliasTest(new PluginValue("testKey", true)); + aliasTest(new PluginListValue("testKey")); emptyAliasTest(new StringValue("testKey")); emptyAliasTest(new StringValue("testKey")); - pluginAliasTest(new PluginValue(String.class, "testKey", true)); - pluginAliasTest(new PluginListValue(String[].class, "testKey")); - pluginListAliasTest(new PluginListValue(String[].class, "testKey")); + pluginAliasTest(new PluginValue("testKey", true)); + pluginAliasTest(new PluginListValue("testKey")); + pluginListAliasTest(new PluginListValue("testKey")); } private void aliasTest(Value val) { @@ -132,7 +132,7 @@ public class TestPluginValue extends AbstractTestCase { } public void testPluginListParsing() { - PluginListValue val = new PluginListValue(String[].class, "testKey"); + PluginListValue val = new PluginListValue("testKey"); assertEquals(0, val.getClassNames().length); val.setString("foo"); assertEquals(1, val.getClassNames().length); diff --git a/openjpa-persistence-jdbc/src/main/java/org/apache/openjpa/persistence/jdbc/JDBCPersistenceProductDerivation.java b/openjpa-persistence-jdbc/src/main/java/org/apache/openjpa/persistence/jdbc/JDBCPersistenceProductDerivation.java index 30072befc..f6447d440 100644 --- a/openjpa-persistence-jdbc/src/main/java/org/apache/openjpa/persistence/jdbc/JDBCPersistenceProductDerivation.java +++ b/openjpa-persistence-jdbc/src/main/java/org/apache/openjpa/persistence/jdbc/JDBCPersistenceProductDerivation.java @@ -77,14 +77,20 @@ public class JDBCPersistenceProductDerivation Specification jpa = PersistenceProductDerivation.SPEC_JPA; Specification ejb = PersistenceProductDerivation.ALIAS_EJB; - conf.metaFactoryPlugin.setAlias(ejb.getName(), PersistenceMappingFactory.class.getName()); - conf.metaFactoryPlugin.setAlias(jpa.getName(), PersistenceMappingFactory.class.getName()); + conf.metaFactoryPlugin.setAlias(ejb.getName(), + PersistenceMappingFactory.class.getName()); + conf.metaFactoryPlugin.setAlias(jpa.getName(), + PersistenceMappingFactory.class.getName()); - conf.mappingFactoryPlugin.setAlias(ejb.getName(), PersistenceMappingFactory.class.getName()); - conf.mappingFactoryPlugin.setAlias(jpa.getName(), PersistenceMappingFactory.class.getName()); + conf.mappingFactoryPlugin.setAlias(ejb.getName(), + PersistenceMappingFactory.class.getName()); + conf.mappingFactoryPlugin.setAlias(jpa.getName(), + PersistenceMappingFactory.class.getName()); - conf.mappingDefaultsPlugin.setAlias(ejb.getName(), PersistenceMappingDefaults.class.getName()); - conf.mappingDefaultsPlugin.setAlias(jpa.getName(), PersistenceMappingDefaults.class.getName()); + conf.mappingDefaultsPlugin.setAlias(ejb.getName(), + PersistenceMappingDefaults.class.getName()); + conf.mappingDefaultsPlugin.setAlias(jpa.getName(), + PersistenceMappingDefaults.class.getName()); conf.lockManagerPlugin.setAlias("mixed", "org.apache.openjpa.jdbc.kernel.MixedLockManager"); diff --git a/openjpa-persistence-jdbc/src/main/java/org/apache/openjpa/persistence/jdbc/XMLPersistenceMappingParser.java b/openjpa-persistence-jdbc/src/main/java/org/apache/openjpa/persistence/jdbc/XMLPersistenceMappingParser.java index 0e20d223a..7a1da8b8a 100644 --- a/openjpa-persistence-jdbc/src/main/java/org/apache/openjpa/persistence/jdbc/XMLPersistenceMappingParser.java +++ b/openjpa-persistence-jdbc/src/main/java/org/apache/openjpa/persistence/jdbc/XMLPersistenceMappingParser.java @@ -418,7 +418,7 @@ public class XMLPersistenceMappingParser */ private boolean startSecondaryTable(Attributes attrs) throws SAXException { - _secondaryTable = toTableIdentifier(getSchemaName(attrs), + _secondaryTable = toTableIdentifier(attrs.getValue("schema"), attrs.getValue("name")).getName(); ((ClassMapping)currentElement()).getMappingInfo() .addSecondaryTable(DBIdentifier.newTable(_secondaryTable)); @@ -458,7 +458,7 @@ public class XMLPersistenceMappingParser SequenceMapping seq = (SequenceMapping) getRepository(). addSequenceMetaData(name); seq.setSequencePlugin(SequenceMapping.IMPL_VALUE_TABLE); - seq.setTableIdentifier(toTableIdentifier(getSchemaName(attrs), + seq.setTableIdentifier(toTableIdentifier(attrs.getValue("schema"), attrs.getValue("table"))); seq.setPrimaryKeyColumnIdentifier(DBIdentifier.newColumn(attrs.getValue("pk-column-name"), delimit())); seq.setSequenceColumnIdentifier(DBIdentifier.newColumn(attrs.getValue("value-column-name"), delimit())); @@ -486,21 +486,6 @@ public class XMLPersistenceMappingParser private void endTableGenerator() { popElement(); } - - /** - * Gets the name of the schema from the given attribute value "schema". - * If the value is unspecified and a default schema is specified, then - * gets the default schema name. - * @param attrs attributes of an XML element - * @return the schema name - */ - String getSchemaName(Attributes attrs) { - String name = attrs.getValue("schema"); - if (StringUtils.isEmpty(name) && _schema != null) { - return _schema; - } - return name; - } /** * Parse inheritance. @@ -811,7 +796,7 @@ public class XMLPersistenceMappingParser ClassMapping mapping = (ClassMapping) currentElement(); if (mapping.isAbstract()) throw new UserException(_loc.get("table-not-allowed", mapping)); - DBIdentifier table = toTableIdentifier(attrs.getValue(getSchemaName(attrs)), + DBIdentifier table = toTableIdentifier(attrs.getValue("schema"), attrs.getValue("name")); if (!DBIdentifier.isNull(table)) mapping.getMappingInfo().setTableIdentifier(table); @@ -823,7 +808,7 @@ public class XMLPersistenceMappingParser */ private boolean startJoinTable(Attributes attrs) throws SAXException { - DBIdentifier sTable = toTableIdentifier(getSchemaName(attrs), + DBIdentifier sTable = toTableIdentifier(attrs.getValue("schema"), attrs.getValue("name")); if (!DBIdentifier.isNull(sTable)) { Object elem = currentElement(); @@ -1071,7 +1056,7 @@ public class XMLPersistenceMappingParser private DBIdentifier parseCollectionTable(Attributes attrs) { String tVal = attrs.getValue("name"); - String sVal = getSchemaName(attrs); + String sVal = attrs.getValue("schema"); return toTableIdentifier(sVal, tVal); } diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/enhance/AbstractUnenhancedClassTest.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/enhance/AbstractUnenhancedClassTest.java index c62b6ef26..a62569b9b 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/enhance/AbstractUnenhancedClassTest.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/enhance/AbstractUnenhancedClassTest.java @@ -51,12 +51,11 @@ public abstract class AbstractUnenhancedClassTest // * Java 6 // * Java 5 with javaagent // * Java 5 without javaagent - OpenJPAConfiguration _conf; + public void setUp() { setUp(getUnenhancedClass(), getUnenhancedSubclass(), CLEAR_TABLES); // trigger class redefinition emf.createEntityManager().close(); - _conf = emf.getConfiguration(); _log = emf.getConfiguration().getLog(OpenJPAConfiguration.LOG_ENHANCE); } @@ -77,7 +76,7 @@ public abstract class AbstractUnenhancedClassTest public void testMetaData() { ClassMetaData meta = JPAFacadeHelper.getMetaData(emf, getUnenhancedClass()); - assertEquals(ClassRedefiner.canRedefineClasses(_conf), meta + assertEquals(ClassRedefiner.canRedefineClasses(_log), meta .isIntercepting()); } @@ -265,7 +264,7 @@ public abstract class AbstractUnenhancedClassTest public void testEnhancer() throws IOException { List> subs = ManagedClassSubclasser.prepareUnenhancedClasses( - emf.getConfiguration(), Collections.singleton(getUnenhancedClass())); + emf.getConfiguration(), Collections.singleton(getUnenhancedClass()), null); Class sub = subs.get(0); assertNotNull(sub); assertEquals("org.apache.openjpa.enhance." @@ -312,7 +311,7 @@ public abstract class AbstractUnenhancedClassTest // we only expect lazy loading to work when we can redefine classes // or when accessing a property-access record that OpenJPA created. - if (ClassRedefiner.canRedefineClasses(_conf) + if (ClassRedefiner.canRedefineClasses(_log) || (!userDefined && AccessCode.isProperty(sm.getMetaData().getAccessType()))) { @@ -364,7 +363,7 @@ public abstract class AbstractUnenhancedClassTest // we only expect lazy loading to work when we can redefine classes // or when accessing a property-access record that OpenJPA created. - if (ClassRedefiner.canRedefineClasses(_conf) + if (ClassRedefiner.canRedefineClasses(_log) || AccessCode.isProperty(sm.getMetaData().getAccessType())) { assertFalse(sm.getLoaded() .get(sm.getMetaData().getField("lazyField").getIndex())); @@ -589,13 +588,14 @@ public abstract class AbstractUnenhancedClassTest ClassMetaData meta = JPAFacadeHelper.getMetaData(emf, getUnenhancedClass()); List> subs = ManagedClassSubclasser.prepareUnenhancedClasses( - emf.getConfiguration(), Collections.singleton(getUnenhancedClass())); + emf.getConfiguration(), Collections.singleton(getUnenhancedClass()), + null); assertSame(meta, JPAFacadeHelper.getMetaData(emf, subs.get(0))); meta = JPAFacadeHelper.getMetaData(emf, getUnenhancedSubclass()); subs = ManagedClassSubclasser.prepareUnenhancedClasses( emf.getConfiguration(), - Collections.singleton(getUnenhancedSubclass())); + Collections.singleton(getUnenhancedSubclass()), null); assertSame(meta, JPAFacadeHelper.getMetaData(emf, subs.get(0))); } diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/enhance/RestrictedMetaDataRepository.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/enhance/RestrictedMetaDataRepository.java index f3b21b7eb..2b0d4462c 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/enhance/RestrictedMetaDataRepository.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/enhance/RestrictedMetaDataRepository.java @@ -48,8 +48,8 @@ public class RestrictedMetaDataRepository extends MetaDataRepository { } } - public Set getPersistentTypeNames(boolean devpath) { - Set types = super.getPersistentTypeNames(devpath); + public Set getPersistentTypeNames(boolean devpath, ClassLoader envLoader) { + Set types = super.getPersistentTypeNames(devpath, envLoader); String[] typeArray = types.toArray(new String[types.size()]); for (String type : typeArray) { if(_excludedTypes.contains(type)) { diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/enhance/TestEnhancementWithMultiplePUs.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/enhance/TestEnhancementWithMultiplePUs.java index a3bf49dc4..0a0f5a697 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/enhance/TestEnhancementWithMultiplePUs.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/enhance/TestEnhancementWithMultiplePUs.java @@ -26,7 +26,6 @@ import java.util.List; import org.apache.openjpa.conf.OpenJPAConfiguration; import org.apache.openjpa.conf.OpenJPAConfigurationImpl; -import org.apache.openjpa.enhance.PCEnhancer.Flags; import org.apache.openjpa.lib.conf.Configurations; import org.apache.openjpa.lib.util.BytecodeWriter; import org.apache.openjpa.lib.util.J2DoPrivHelper; @@ -47,13 +46,13 @@ public class TestEnhancementWithMultiplePUs ClassLoader loader = AccessController .doPrivileged(J2DoPrivHelper.newTemporaryClassLoaderAction( getClass().getClassLoader())); - conf.addClassLoader(loader); Project project = new Project(); - String className = "org.apache.openjpa.enhance.UnenhancedBootstrapInstance"; + String className = + "org.apache.openjpa.enhance.UnenhancedBootstrapInstance"; BCClass bc = assertNotPC(loader, project, className); - PCEnhancer enhancer = new PCEnhancer(conf, bc, repos); + PCEnhancer enhancer = new PCEnhancer(conf, bc, repos, loader); assertEquals(PCEnhancer.ENHANCE_PC, enhancer.run()); assertTrue(Arrays.asList(bc.getInterfaceNames()).contains( @@ -80,11 +79,11 @@ public class TestEnhancementWithMultiplePUs ClassLoader loader = AccessController .doPrivileged(J2DoPrivHelper.newTemporaryClassLoaderAction( getClass().getClassLoader())); - conf.addClassLoader(loader); Project project = new Project(); // make sure that the class is not already enhanced for some reason - String className = "org.apache.openjpa.enhance.UnenhancedBootstrapInstance"; + String className = + "org.apache.openjpa.enhance.UnenhancedBootstrapInstance"; BCClass bc = assertNotPC(loader, project, className); // build up a writer that just stores to a list so that we don't @@ -99,7 +98,8 @@ public class TestEnhancementWithMultiplePUs } }; - PCEnhancer.run(conf, null, new PCEnhancer.Flags(), repos, writer); + PCEnhancer.run(conf, null, new PCEnhancer.Flags(), repos, writer, + loader); // ensure that we don't attempt to process classes listed in other PUs assertEquals(1, written.size()); @@ -108,13 +108,7 @@ public class TestEnhancementWithMultiplePUs assertTrue(written.contains(className)); } - - - /** - * This test is retired due to - * classloading changes. - */ - public void xtestEnhancementOfAllPUsWithinAResource() + public void testEnhancementOfAllPUsWithinAResource() throws IOException { OpenJPAConfiguration conf = new OpenJPAConfigurationImpl(); Options opts = new Options(); @@ -124,7 +118,6 @@ public class TestEnhancementWithMultiplePUs ClassLoader loader = AccessController .doPrivileged(J2DoPrivHelper.newTemporaryClassLoaderAction( getClass().getClassLoader())); - conf.addClassLoader(loader); Project project = new Project(); // make sure that the classes is not already enhanced for some reason @@ -154,14 +147,8 @@ public class TestEnhancementWithMultiplePUs opts.setProperty("MetaDataRepository", "org.apache.openjpa.enhance.RestrictedMetaDataRepository(excludedTypes=" + "org.apache.openjpa.persistence.jdbc.annotations.UnenhancedMixedAccess)"); - RestrictedMetaDataRepository rmdr = new RestrictedMetaDataRepository(); - rmdr.setConfiguration(conf); - rmdr.setMetaDataFactory(repos.getMetaDataFactory()); - - rmdr.setExcludedTypes("org.apache.openjpa.persistence.jdbc.annotations.UnenhancedMixedAccess"); opts.put(PCEnhancer.class.getName() + "#bytecodeWriter", writer); - PCEnhancer.run(conf, null, new Flags(), rmdr, writer); -// PCEnhancer.run(null, opts); + PCEnhancer.run(null, opts); // ensure that we do process the classes listed in the PUs assertTrue(written.contains( diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/jdbc/kernel/TestJDBCStoreOptSelect.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/jdbc/kernel/TestJDBCStoreOptSelect.java index ceaca038b..d6b583870 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/jdbc/kernel/TestJDBCStoreOptSelect.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/jdbc/kernel/TestJDBCStoreOptSelect.java @@ -73,7 +73,7 @@ public class TestJDBCStoreOptSelect extends SQLListenerTestCase { // Check to see how many fks(intermediate fields) we selected. StateManagerImpl smi = ((StateManagerImpl) ((PersistenceCapable) ee1).pcGetStateManager()); ClassMetaData cmd = - em.getConfiguration().getMetaDataRepositoryInstance().getMetaData(OptSelectEntity.class, true); + em.getConfiguration().getMetaDataRepositoryInstance().getMetaData(OptSelectEntity.class, null, true); int fks = 0; for (FieldMetaData fmd : cmd.getFields()) { if (smi.getIntermediate(fmd.getIndex()) != null) { @@ -97,7 +97,7 @@ public class TestJDBCStoreOptSelect extends SQLListenerTestCase { FetchPlan fp = em.pushFetchPlan(); fp.removeFetchGroups(fp.getFetchGroups()); for (Class cls : new Class[] { OptSelectEntity.class }) { - ClassMetaData cmd = mdr.getMetaData(cls, true); + ClassMetaData cmd = mdr.getMetaData(cls, null, true); for (FieldMetaData fmd : cmd.getFields()) { fp.addField(cls, fmd.getName()); } diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/jdbc/meta/TestMappingToolTemporal.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/jdbc/meta/TestMappingToolTemporal.java index d96e397f9..fe0e6c5cc 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/jdbc/meta/TestMappingToolTemporal.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/jdbc/meta/TestMappingToolTemporal.java @@ -36,7 +36,8 @@ public class TestMappingToolTemporal extends SingleEMTestCase { ClassMapping mapping = (ClassMapping) ((OpenJPAEntityManagerFactorySPI) OpenJPAPersistence.cast(emf)) .getConfiguration().getMetaDataRepositoryInstance() - .getMetaData("TemporalFieldTypes", true); + .getMetaData("TemporalFieldTypes", getClass().getClassLoader(), + true); assertEquals(java.sql.Types.TIMESTAMP, mapping.getFieldMapping( "dateDefaultField").getValueMapping().getColumns()[0].getType()); diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/kernel/TestDynamicClassRegistration.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/kernel/TestDynamicClassRegistration.java index 574fa339a..72338de5c 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/kernel/TestDynamicClassRegistration.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/kernel/TestDynamicClassRegistration.java @@ -73,8 +73,8 @@ public class TestDynamicClassRegistration // trigger class initialization ManagedClassSubclasser.prepareUnenhancedClasses( emf1.getConfiguration(), - Collections.singleton(UnenhancedFieldAccess.class) - ); + Collections.singleton(UnenhancedFieldAccess.class), + null); ClassMetaData meta = JPAFacadeHelper.getMetaData(emf1, UnenhancedFieldAccess.class); diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/lib/conf/TestAnchorParsing.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/lib/conf/TestAnchorParsing.java index 2ccfd2c37..7e40e915b 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/lib/conf/TestAnchorParsing.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/lib/conf/TestAnchorParsing.java @@ -70,12 +70,16 @@ public class TestAnchorParsing extends TestCase { public void testProductDerivationsLoadResource() { ProductDerivations.load( "org/apache/openjpa/lib/conf/product-derivations-load.xml", - "foo"); + "foo", null); - ProductDerivations.load("org/apache/openjpa/lib/conf/product-derivations-load.xml", null); + ProductDerivations.load( + "org/apache/openjpa/lib/conf/product-derivations-load.xml", + null, null); try { - ProductDerivations.load("org/apache/openjpa/lib/conf/product-derivations-load.xml", "nonexistant"); + ProductDerivations.load( + "org/apache/openjpa/lib/conf/product-derivations-load.xml", + "nonexistant", null); fail("pu 'nonexistant' does not exist"); } catch (MissingResourceException mre) { // expected @@ -84,7 +88,7 @@ public class TestAnchorParsing extends TestCase { try { ProductDerivations.load( "org/apache/openjpa/lib/conf/product-derivations-load.xml", - ""); + "", null); fail("pu '' does not exist"); } catch (MissingResourceException mre) { // expected @@ -93,7 +97,7 @@ public class TestAnchorParsing extends TestCase { public void testNonexistantResourceLoad() { try { - ProductDerivations.load("nonexistant-resource", null); + ProductDerivations.load("nonexistant-resource", null, null); fail("resource 'nonexistant-resource' should not exist"); } catch (MissingResourceException e) { // expected @@ -104,19 +108,19 @@ public class TestAnchorParsing extends TestCase { File validFile = resourceToTemporaryFile( "org/apache/openjpa/lib/conf/product-derivations-load.xml"); - ProductDerivations.load(validFile, "foo"); + ProductDerivations.load(validFile, "foo", null); - ProductDerivations.load(validFile, null); + ProductDerivations.load(validFile, null, null); try { - ProductDerivations.load(validFile, "nonexistant"); + ProductDerivations.load(validFile, "nonexistant", null); fail("pu 'nonexistant' does not exist"); } catch (MissingResourceException mre) { // expected } try { - ProductDerivations.load(validFile, ""); + ProductDerivations.load(validFile, "", null); fail("pu '' does not exist"); } catch (MissingResourceException mre) { // expected @@ -128,7 +132,7 @@ public class TestAnchorParsing extends TestCase { File f = new File("this-should-not-exist"); assertFalse(f.exists()); try { - ProductDerivations.load(f, null); + ProductDerivations.load(f, null, null); fail(f.getName() + " does not exist"); } catch (MissingResourceException e) { // expected diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/access/TestExplicitAccess.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/access/TestExplicitAccess.java index 20cec265d..138531a42 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/access/TestExplicitAccess.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/access/TestExplicitAccess.java @@ -944,7 +944,7 @@ public class TestExplicitAccess extends SingleEMFTestCase { em.getConfiguration().getMetaDataRepositoryInstance(); ClassMetaData cmd = mdr.getMetaData(PropAccessFieldStratsEntity.class, - true); + null, true); // Assert expected persistent fields and properties were created assertNotNull(cmd.getField("embedId")); assertNotNull(cmd.getField("m2one")); @@ -1035,7 +1035,8 @@ public class TestExplicitAccess extends SingleEMFTestCase { MetaDataRepository mdr = em.getConfiguration().getMetaDataRepositoryInstance(); - ClassMetaData cmd = mdr.getMetaData(FieldAccessPropStratsEntity.class, true); + ClassMetaData cmd = mdr.getMetaData(FieldAccessPropStratsEntity.class, + null, true); // Assert expected persistent fields and properties were created assertNotNull(cmd.getField("eid")); assertNotNull(cmd.getField("elementCollection")); diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/annotations/TestVersion.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/annotations/TestVersion.java index b7aff0237..a2e4effc6 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/annotations/TestVersion.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/annotations/TestVersion.java @@ -229,7 +229,8 @@ public class TestVersion extends AnnotationTestCase ClassMapping cls = ((JDBCConfigurationImpl) ((OpenJPAEntityManagerSPI) OpenJPAPersistence.cast(pm)).getConfiguration()) - .getMappingRepositoryInstance().getMapping(EmbedOwner.class, true); + .getMappingRepositoryInstance().getMapping(EmbedOwner.class, + null, true); assertEquals(NoneVersionStrategy.getInstance(), cls.getVersion().getStrategy()); assertEquals(0, cls.getVersion().getColumns().length); @@ -242,7 +243,8 @@ public class TestVersion extends AnnotationTestCase (OpenJPAEntityManager) currentEntityManager(); ClassMapping cls = ((JDBCConfigurationImpl)((OpenJPAEntityManagerSPI) OpenJPAPersistence.cast(pm)).getConfiguration()) - .getMappingRepositoryInstance().getMapping(AnnoTest1.class, true); + .getMappingRepositoryInstance().getMapping(AnnoTest1.class, + null, true); assertTrue(NoneVersionStrategy.getInstance() != cls.getVersion().getStrategy()); assertEquals(1, cls.getVersion().getColumns().length); diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/annotations/xml/TestMetaDataComplete.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/annotations/xml/TestMetaDataComplete.java index 1da32f90b..2ccf3af63 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/annotations/xml/TestMetaDataComplete.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/annotations/xml/TestMetaDataComplete.java @@ -58,10 +58,10 @@ public class TestMetaDataComplete extends SingleEMFTestCase { MetaDataRepository repos = oemf.getConfiguration() .getMetaDataRepositoryInstance(); - entityA = repos.getMetaData(EntityA.class, true); - entityB = repos.getMetaData(EntityB.class, true); - derivedA = repos.getMetaData(DerivedA.class, true); - derivedB = repos.getMetaData(DerivedB.class, true); + entityA = repos.getMetaData(EntityA.class, null, true); + entityB = repos.getMetaData(EntityB.class, null, true); + derivedA = repos.getMetaData(DerivedA.class, null, true); + derivedB = repos.getMetaData(DerivedB.class, null, true); } } diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/cache/jpa/AbstractCacheModeTestCase.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/cache/jpa/AbstractCacheModeTestCase.java index bdc7380a7..80e2e00b4 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/cache/jpa/AbstractCacheModeTestCase.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/cache/jpa/AbstractCacheModeTestCase.java @@ -451,7 +451,7 @@ public abstract class AbstractCacheModeTestCase extends AbstractCacheTestCase { private String getAlias(Class cls) { ClassMapping mapping = (ClassMapping) getEntityManagerFactory().getConfiguration().getMetaDataRepositoryInstance().getMetaData( - cls, true); + cls, null, true); return mapping.getTypeAlias(); } } diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/cache/jpa/TestCacheModeInvalid.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/cache/jpa/TestCacheModeInvalid.java index 242ade94c..fce18afd8 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/cache/jpa/TestCacheModeInvalid.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/cache/jpa/TestCacheModeInvalid.java @@ -38,11 +38,13 @@ public class TestCacheModeInvalid extends AbstractCacheTestCase { "openjpa.jdbc.JDBCListeners", new JDBCListener [] { getListener() }); emf = (OpenJPAEntityManagerFactorySPI) OpenJPAPersistence.createEntityManagerFactory("cache-mode-invalid", "META-INF/caching-persistence-invalid.xml", propertiesMap ); - fail("Expected SAX parse error for invalid entry"); } catch (Throwable e) { + exceptionCaught = true; + assertException(e, org.apache.openjpa.util.GeneralException.class); String msg = e.getMessage(); assertTrue(msg.contains("org.xml.sax.SAXException")); } + assertTrue(exceptionCaught); } @Override diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/compat/TestEmbeddableSuperclass.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/compat/TestEmbeddableSuperclass.java index 1b20b06de..e64760608 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/compat/TestEmbeddableSuperclass.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/compat/TestEmbeddableSuperclass.java @@ -64,7 +64,7 @@ public class TestEmbeddableSuperclass public void testRelationMappings() { JDBCConfiguration conf = (JDBCConfiguration) emf.getConfiguration(); ClassMapping cls = conf.getMappingRepositoryInstance(). - getMapping(EmbeddableSuperSub.class, true); + getMapping(EmbeddableSuperSub.class, null, true); FieldMapping fm = cls.getFieldMapping("sub"); assertTrue(fm.getStrategy() instanceof RelationFieldStrategy); diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/datacache/CacheTest.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/datacache/CacheTest.java index d3b654147..45144b378 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/datacache/CacheTest.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/datacache/CacheTest.java @@ -384,14 +384,17 @@ public abstract class CacheTest extends AbstractTestCase { DataCache cache = cacheManager(factory).getSystemDataCache(); assertEquals(defaultCache, cache); - ClassMetaData aMeta = repos.getMetaData(CacheObjectA.class, true); - ClassMetaData aChild1Meta = repos.getMetaData(CacheObjectAChild1.class, true); - ClassMetaData aChild2Meta = repos.getMetaData(CacheObjectAChild2.class, true); - ClassMetaData bMeta = repos.getMetaData(CacheObjectB.class, true); - ClassMetaData bChild1Meta = repos.getMetaData(CacheObjectBChild1.class, true); - ClassMetaData cMeta = repos.getMetaData(CacheObjectC.class, true); - ClassMetaData dMeta = repos.getMetaData(CacheObjectD.class, true); - ClassMetaData eMeta = repos.getMetaData(CacheObjectE.class, true); + ClassMetaData aMeta = repos.getMetaData(CacheObjectA.class, null, true); + ClassMetaData aChild1Meta = repos.getMetaData(CacheObjectAChild1.class, + null, true); + ClassMetaData aChild2Meta = repos.getMetaData(CacheObjectAChild2.class, + null, true); + ClassMetaData bMeta = repos.getMetaData(CacheObjectB.class, null, true); + ClassMetaData bChild1Meta = repos.getMetaData(CacheObjectBChild1.class, + null, true); + ClassMetaData cMeta = repos.getMetaData(CacheObjectC.class, null, true); + ClassMetaData dMeta = repos.getMetaData(CacheObjectD.class, null, true); + ClassMetaData eMeta = repos.getMetaData(CacheObjectE.class, null, true); cache = aMeta.getDataCache(); assertEquals(defaultCache, cache); @@ -457,7 +460,7 @@ public abstract class CacheTest extends AbstractTestCase { Object relationOid = em.getObjectId(a.getRelatedObject()); relationOid = new Id(CacheObjectA.class, relationOid.toString()); - ClassMetaData meta = repos.getMetaData(CacheObjectA.class, true); + ClassMetaData meta = repos.getMetaData(CacheObjectA.class, null, true); DataCache cache = meta.getDataCache(); // drop the related data from the cache @@ -909,7 +912,7 @@ public abstract class CacheTest extends AbstractTestCase { ((((OpenJPAEntityManagerFactorySPI) factory2)) .getConfiguration()).getMetaDataRepositoryInstance(); ClassMetaData meta = repos2 - .getMetaData(CacheObjectA.class, true); + .getMetaData(CacheObjectA.class, em2.getClassLoader(), true); cache = meta.getDataCache(); assertTrue(cache.contains(oidwithclass)); @@ -1619,7 +1622,8 @@ public abstract class CacheTest extends AbstractTestCase { ClassMetaData meta = ((OpenJPAEntityManagerFactorySPI) OpenJPAPersistence .cast(factory)).getConfiguration() - .getMetaDataRepositoryInstance().getMetaData(a.getClass(), false); + .getMetaDataRepositoryInstance().getMetaData(a.getClass(), + null, false); FieldMetaData fmd = meta.getField("date"); d = (Date) data.getData(fmd.getIndex()); Broker broker = JPAFacadeHelper.toBroker(em1); diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/datacache/TestPartitionedDataCache.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/datacache/TestPartitionedDataCache.java index b3dc03bc1..ba7d62c32 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/datacache/TestPartitionedDataCache.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/datacache/TestPartitionedDataCache.java @@ -53,16 +53,7 @@ public class TestPartitionedDataCache extends SingleEMFTestCase { } catch (UserException e) { System.err.println(e); } - - } - - /** - * This test will not run because of Configuration is not assigned - * if a cache is directly instantiated in a test. - */ - public void xtestMisConfiguration() { - PartitionedDataCache cache = new PartitionedDataCache(); - String badProperty = "(cacheSize=100),(name=b,cacheSize=200)";// missing name + badProperty = "(cacheSize=100),(name=b,cacheSize=200)";// missing name try { cache.setPartitions(badProperty); fail("Expected parse error on " + badProperty); @@ -83,6 +74,7 @@ public class TestPartitionedDataCache extends SingleEMFTestCase { } catch (UserException e) { System.err.println(e); } + } public void testPolicyConfiguration() { diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/datacache/stats/TestStatistics.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/datacache/stats/TestStatistics.java index c758ecb5f..ba1d9dc5c 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/datacache/stats/TestStatistics.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/datacache/stats/TestStatistics.java @@ -48,7 +48,7 @@ public class TestStatistics extends SingleEMFTestCase { void startCaching(Class cls) { ClassMetaData meta = emf.getConfiguration() - .getMetaDataRepositoryInstance().getMetaData(cls, true); + .getMetaDataRepositoryInstance().getMetaData(cls, null, true); meta.setDataCacheName(DataCache.NAME_DEFAULT); } diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/dynamicschema/TestDynamicSchemas.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/dynamicschema/TestDynamicSchemas.java index de3363af0..d6e7290f7 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/dynamicschema/TestDynamicSchemas.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/dynamicschema/TestDynamicSchemas.java @@ -197,14 +197,16 @@ public class TestDynamicSchemas extends SingleEMFTestCase { DBDictionary dict = conf.getDBDictionaryInstance(); ClassMapping mapping = (ClassMapping)conf. getMetaDataRepositoryInstance(). - getMetaData(EntityVeryLongNames.class, true); + getMetaData(EntityVeryLongNames.class,getClass(). + getClassLoader(), true); Table table = mapping.getTable(); assertTrue(table.getName().length() > 0); assertTrue(table.getName().length() <= dict.maxTableNameLength); validateColumnNames(table, dict); mapping = (ClassMapping)conf. getMetaDataRepositoryInstance(). - getMetaData(EntityReservedWords.class, true); + getMetaData(EntityReservedWords.class,getClass(). + getClassLoader(), true); table = mapping.getTable(); assertTrue(table.getName().length() > 0); assertTrue(table.getName().length() <= dict.maxTableNameLength); diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/embed/TestEmbeddable.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/embed/TestEmbeddable.java index 382cb8af7..cbcf21576 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/embed/TestEmbeddable.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/embed/TestEmbeddable.java @@ -2828,7 +2828,8 @@ public class TestEmbeddable extends SQLListenerTestCase { conf, new String[] { "org.apache.openjpa.persistence.embed.Book" }, flags, - conf.getClassLoader()); + conf.getClassResolverInstance(). + getClassLoader(MappingTool.class, null)); } /* diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/enhance/TestNoNoArgs.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/enhance/TestNoNoArgs.java index e811043d1..c78838baf 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/enhance/TestNoNoArgs.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/enhance/TestNoNoArgs.java @@ -33,6 +33,7 @@ public class TestNoNoArgs OpenJPAConfiguration conf; MetaDataRepository repos; + ClassLoader loader; private PCEnhancer.Flags flags = new PCEnhancer.Flags(); public TestNoNoArgs(String s) { @@ -40,14 +41,19 @@ public class TestNoNoArgs } public void setUp() { - OpenJPAEntityManager em = (OpenJPAEntityManager) currentEntityManager(); + OpenJPAEntityManager em = + (OpenJPAEntityManager) currentEntityManager(); conf = ((OpenJPAEntityManagerSPI) em).getConfiguration(); repos = conf.newMetaDataRepositoryInstance(); + loader = em.getClassLoader(); endEm(em); } - public void testNoNoArgs() throws IOException { - PCEnhancer.run((OpenJPAConfiguration) conf, new String[]{ }, flags, repos, null); + public void testNoNoArgs() + throws IOException { + PCEnhancer.run((OpenJPAConfiguration) conf, + new String[]{ }, + flags, repos, null, loader); } public void testNo2NoArgs() @@ -55,7 +61,8 @@ public class TestNoNoArgs flags.addDefaultConstructor = false; boolean caughtException = false; try { - PCEnhancer.run((OpenJPAConfiguration) conf, new String[]{ }, flags, repos, null); + PCEnhancer.run((OpenJPAConfiguration) conf, new String[]{ }, + flags, repos, null, loader); } catch (OpenJPAException e) { caughtException = true; } @@ -65,6 +72,7 @@ public class TestNoNoArgs public void testNo3NoArgs() throws IOException { PCEnhancer.run((OpenJPAConfiguration) conf, - new String[]{ "persistence.enhance.common.apps.Entity1" }, flags, repos, null); + new String[]{ "persistence.enhance.common.apps.Entity1" }, + flags, repos, null, loader); } } diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/enhance/TestSubclassedBehavior.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/enhance/TestSubclassedBehavior.java index 50071c15c..f8fb49d2b 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/enhance/TestSubclassedBehavior.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/enhance/TestSubclassedBehavior.java @@ -541,7 +541,7 @@ public class TestSubclassedBehavior extends AbstractTestCase { // registry-parsing code. ClassMetaData meta = getConfiguration() .getMetaDataRepositoryInstance(). - getMetaData(DerivedEntity.class, false); + getMetaData(DerivedEntity.class, null, false); assertTrue("meta's access should be ACCESS_PROPERTY", AccessCode.isProperty(meta.getAccessType())); FieldMetaData[] fmds = meta.getFields(); diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/event/TestLifecycleEventManager.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/event/TestLifecycleEventManager.java index c5e232cff..cc703f09c 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/event/TestLifecycleEventManager.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/event/TestLifecycleEventManager.java @@ -52,7 +52,7 @@ public class TestLifecycleEventManager OpenJPAPersistence.createEntityManagerFactory("TestConv2", ""))) . getConfiguration().getMetaDataRepositoryInstance(); - ClassMetaData meta = repos.getMetaData(RuntimeTest2.class, true); + ClassMetaData meta = repos.getMetaData(RuntimeTest2.class, null, true); LifecycleEventManager mgr = new LifecycleEventManager(); RuntimeTest2 pc = new RuntimeTest2(); Listener listener = new Listener(); @@ -126,7 +126,7 @@ public class TestLifecycleEventManager OpenJPAPersistence.createEntityManagerFactory("TestConv2", ""))) . getConfiguration().getMetaDataRepositoryInstance(); - ClassMetaData meta = repos.getMetaData(RuntimeTest2.class, true); + ClassMetaData meta = repos.getMetaData(RuntimeTest2.class, null, true); LifecycleEventManager mgr = new LifecycleEventManager(); RuntimeTest2 pc = new RuntimeTest2(); diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/generationtype/TestTableGeneratorMultithreaded.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/generationtype/TestTableGeneratorMultithreaded.java index da898a6aa..9532815ba 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/generationtype/TestTableGeneratorMultithreaded.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/generationtype/TestTableGeneratorMultithreaded.java @@ -43,8 +43,8 @@ public class TestTableGeneratorMultithreaded extends SingleEMFTestCase { ClassLoader loader = Thread.currentThread().getContextClassLoader(); MetaDataRepository repo = emf.getConfiguration().getMetaDataRepositoryInstance(); // Initialize MetaData - repo.getMetaData(Dog.class, true); - repo.getSequenceMetaData("Dog_Gen", true); + repo.getMetaData(Dog.class, loader, true); + repo.getSequenceMetaData("Dog_Gen", loader, true); } @@ -82,14 +82,15 @@ public class TestTableGeneratorMultithreaded extends SingleEMFTestCase { } public void run() { - SequenceMetaData meta = _repo.getSequenceMetaData("Dog_Gen", true); + ClassLoader contextLoader = Thread.currentThread().getContextClassLoader(); + SequenceMetaData meta = _repo.getSequenceMetaData("Dog_Gen", contextLoader, true); meta.setInitialValue(1); meta.setIncrement(10000); _em = (EntityManagerImpl) emf.createEntityManager(); _ctx = (StoreContext) _em.getBroker(); - _cmd = _repo.getMetaData(Dog.class, true); + _cmd = _repo.getMetaData(Dog.class, contextLoader, true); - _seq = (TableJDBCSeq) meta.getInstance(); + _seq = (TableJDBCSeq) meta.getInstance(contextLoader); // Change defaults so this test doesn't take so long to run. _seq.setAllocate(ALLOC_SIZE); _seq.setInitialValue(1); diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/graph/TestPersistentGraph.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/graph/TestPersistentGraph.java index 0fd9cced3..2d24aa92d 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/graph/TestPersistentGraph.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/graph/TestPersistentGraph.java @@ -111,7 +111,7 @@ public class TestPersistentGraph extends SingleEMFTestCase { FieldMapping getFieldMapping(Class pcClass, String field) { MappingRepository repos = (MappingRepository) emf.getConfiguration() .getMetaDataRepositoryInstance(); - ClassMapping cmd = repos.getMapping(pcClass, true); + ClassMapping cmd = repos.getMapping(pcClass, null, true); assertNotNull("No metadata found for " + pcClass, cmd); FieldMapping fmd = cmd.getFieldMapping(field); assertNotNull("No metadata found for " + pcClass.getName() + "." + field + " Fields are " @@ -150,8 +150,8 @@ public class TestPersistentGraph extends SingleEMFTestCase { FieldStrategy getStrategy(Class cls, String field) { MetaDataRepository repos = emf.getConfiguration().getMetaDataRepositoryInstance(); - ClassMetaData cmd = repos.getMetaData(cls, true); - assertNotNull("No metadata found for " + cls, cmd); + ClassMetaData cmd = repos.getMetaData(cls, null, true); + assertNotNull("No metadat found for " + cls, cmd); FieldMetaData fmd = cmd.getField(field); assertNotNull("No metadata found for " + cls.getName() + "." + field + " Fields are " + Arrays.toString(cmd.getFieldNames()), fmd); diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/inheritance/TestSharedUnqualifiedClassNames.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/inheritance/TestSharedUnqualifiedClassNames.java index 242947f35..aaedc8225 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/inheritance/TestSharedUnqualifiedClassNames.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/inheritance/TestSharedUnqualifiedClassNames.java @@ -54,7 +54,7 @@ public class TestSharedUnqualifiedClassNames public void testMappedSuperclass() { ClassMetaData meta = emf.getConfiguration() .getMetaDataRepositoryInstance() - .getMetaData("SharedName1", true); + .getMetaData("SharedName1", getClass().getClassLoader(), true); assertEquals( org.apache.openjpa.persistence.inheritance.entity.SharedName1.class, meta.getDescribedType()); @@ -63,7 +63,7 @@ public class TestSharedUnqualifiedClassNames public void testEmbeddable() { ClassMetaData meta = emf.getConfiguration() .getMetaDataRepositoryInstance() - .getMetaData("SharedName2", true); + .getMetaData("SharedName2", getClass().getClassLoader(), true); assertEquals( org.apache.openjpa.persistence.inheritance.entity.SharedName2.class, meta.getDescribedType()); diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/TestFKColumnNames.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/TestFKColumnNames.java index 54808ae86..45a53bdaa 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/TestFKColumnNames.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/TestFKColumnNames.java @@ -52,10 +52,10 @@ public class TestFKColumnNames extends AbstractPersistenceTestCase { (MappingRepository) emf.getConfiguration() .getMetaDataRepositoryInstance(); - assertEquals("SELECT_ID", repos.getMapping(Inner1.class, true) + assertEquals("SELECT_ID", repos.getMapping(Inner1.class, null, true) .getFieldMapping("select").getColumns()[0].getName()); - assertEquals("FROM_ID", repos.getMapping(Inner2.class, true) + assertEquals("FROM_ID", repos.getMapping(Inner2.class, null, true) .getFieldMapping("from").getColumns()[0].getName()); closeEMF(emf); } diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/annotations/TestDiscriminator.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/annotations/TestDiscriminator.java index 6577e3c0f..59864080e 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/annotations/TestDiscriminator.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/annotations/TestDiscriminator.java @@ -62,7 +62,8 @@ public class TestDiscriminator public void testJoinedDiscriminatorWithColumn() { JDBCConfiguration conf = (JDBCConfiguration) emf.getConfiguration(); MappingRepository repo = conf.getMappingRepositoryInstance(); - ClassMapping cls = repo.getMapping(AnnoTest1.class, true); + ClassMapping cls = repo.getMapping(AnnoTest1.class, + null, true); assertTrue(cls.getDiscriminator().getStrategy() instanceof ValueMapDiscriminatorStrategy); assertEquals(1, cls.getDiscriminator().getColumns().length); diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/annotations/TestEJBEmbedded.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/annotations/TestEJBEmbedded.java index a92999a86..d35826c1d 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/annotations/TestEJBEmbedded.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/annotations/TestEJBEmbedded.java @@ -157,7 +157,8 @@ public class TestEJBEmbedded extends SingleEMFTestCase { public void testMappingTransferAndOverride() { JDBCConfiguration conf = (JDBCConfiguration) emf.getConfiguration(); - ClassMapping cls = conf.getMappingRepositoryInstance().getMapping(EmbedOwner.class, true); + ClassMapping cls = conf.getMappingRepositoryInstance().getMapping + (EmbedOwner.class, null, true); assertEquals("OWN_BASIC", cls.getFieldMapping("basic"). getColumns()[0].getName()); ClassMapping embed = cls.getFieldMapping("embed").getEmbeddedMapping(); diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/annotations/TestEmbeddableSuperclass.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/annotations/TestEmbeddableSuperclass.java index 0e1f4cba4..7ba4c3222 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/annotations/TestEmbeddableSuperclass.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/annotations/TestEmbeddableSuperclass.java @@ -49,7 +49,8 @@ public class TestEmbeddableSuperclass public void testSuperclassEmbeddedOnly() { ClassMapping cls = ((JDBCConfiguration) emf.getConfiguration()). - getMappingRepositoryInstance().getMapping(EmbeddableSuper.class, true); + getMappingRepositoryInstance().getMapping(EmbeddableSuper.class, + null, true); assertTrue(cls.isEmbeddedOnly()); assertEquals(NoneClassStrategy.getInstance(), cls.getStrategy()); } @@ -57,7 +58,7 @@ public class TestEmbeddableSuperclass public void testSubclassMappingDefaultsAndOverrides() { JDBCConfiguration conf = (JDBCConfiguration) emf.getConfiguration(); ClassMapping cls = conf.getMappingRepositoryInstance(). - getMapping(EmbeddableSuperSub.class, true); + getMapping(EmbeddableSuperSub.class, null, true); assertTrue(!cls.isEmbeddedOnly()); assertTrue(cls.getStrategy() instanceof FullClassStrategy); assertEquals(ClassMapping.ID_APPLICATION, cls.getIdentityType()); @@ -86,7 +87,7 @@ public class TestEmbeddableSuperclass public void testSubclassDiscriminatorMapping() { JDBCConfiguration conf = (JDBCConfiguration) emf.getConfiguration(); ClassMapping cls = conf.getMappingRepositoryInstance(). - getMapping(EmbeddableSuperSub.class, true); + getMapping(EmbeddableSuperSub.class, null, true); assertEquals("DISC", cls.getDiscriminator().getColumns()[0]. getName()); } @@ -94,14 +95,14 @@ public class TestEmbeddableSuperclass public void testVersionOverrideMapping() { JDBCConfiguration conf = (JDBCConfiguration) emf.getConfiguration(); ClassMapping cls = conf.getMappingRepositoryInstance(). - getMapping(EmbeddableSuperSub.class, true); + getMapping(EmbeddableSuperSub.class, null, true); assertEquals("VERSVAL", cls.getVersion().getColumns()[0].getName()); } public void testRelationMappings() { JDBCConfiguration conf = (JDBCConfiguration) emf.getConfiguration(); ClassMapping cls = conf.getMappingRepositoryInstance(). - getMapping(EmbeddableSuperSub.class, true); + getMapping(EmbeddableSuperSub.class, null, true); FieldMapping fm = cls.getFieldMapping("sub"); assertTrue(fm.getStrategy() instanceof RelationFieldStrategy); diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/annotations/TestEnumerated.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/annotations/TestEnumerated.java index cc14b47e8..98bbba5bd 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/annotations/TestEnumerated.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/annotations/TestEnumerated.java @@ -41,7 +41,7 @@ public class TestEnumerated public void testMapping() { ClassMapping cls = (ClassMapping) emf.getConfiguration(). getMetaDataRepositoryInstance().getMetaData(AnnoTest1.class, - true); + null, true); FieldMapping fm = cls.getDeclaredFieldMapping("enumeration"); assertNotNull(fm); assertEquals(FieldMapping.MANAGE_PERSISTENT, fm.getManagement()); diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/annotations/TestExtensionAnnotations.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/annotations/TestExtensionAnnotations.java index a59eabb80..bbd9f592a 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/annotations/TestExtensionAnnotations.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/annotations/TestExtensionAnnotations.java @@ -41,7 +41,8 @@ public class TestExtensionAnnotations public void setUp() { setUp(ExtensionsEntity.class); _mapping = ((JDBCConfiguration) emf.getConfiguration()). - getMappingRepositoryInstance().getMapping(ExtensionsEntity.class, true); + getMappingRepositoryInstance().getMapping(ExtensionsEntity.class, + null, true); } public void testDataStoreId() { diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/annotations/TestGenerators.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/annotations/TestGenerators.java index 48f42b865..3a011670b 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/annotations/TestGenerators.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/annotations/TestGenerators.java @@ -42,7 +42,7 @@ public class TestGenerators extends SingleEMFTestCase { public void testGet() { if (!PersistenceCapable.class.isAssignableFrom(Generator.class) - && !ClassRedefiner.canRedefineClasses(emf.getConfiguration())) + && !ClassRedefiner.canRedefineClasses(_log)) fail("This test requires a higher level of enhancement than" + " is available in the current environment."); diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/annotations/TestMapKey.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/annotations/TestMapKey.java index 84e1c2792..530824ad4 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/annotations/TestMapKey.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/annotations/TestMapKey.java @@ -46,33 +46,36 @@ public class TestMapKey public void testDefaultMapKeyMapping() { ClassMapping mapping = ((JDBCConfiguration) emf.getConfiguration()) - .getMappingRepositoryInstance().getMapping(AnnoTest1.class, true); + .getMappingRepositoryInstance().getMapping(AnnoTest1.class, + null, true); FieldMapping fm = mapping.getFieldMapping("defaultMapKey"); assertTrue(fm.getStrategy() instanceof RelationMapTableFieldStrategy); assertEquals("pk", fm.getKey().getValueMappedBy()); - assertEquals(mapping.getRepository().getMetaData(Flat1.class, true).getField("pk"), - fm.getKey().getValueMappedByMetaData()); + assertEquals(mapping.getRepository().getMetaData(Flat1.class, null, + true).getField("pk"), fm.getKey().getValueMappedByMetaData()); } public void testNamedMapKeyMapping() { ClassMapping mapping = ((JDBCConfiguration) emf.getConfiguration()) - .getMappingRepositoryInstance().getMapping(AnnoTest1.class, true); + .getMappingRepositoryInstance().getMapping(AnnoTest1.class, + null, true); FieldMapping fm = mapping.getFieldMapping("namedMapKey"); assertTrue(fm.getStrategy() instanceof RelationMapTableFieldStrategy); assertEquals("basic", fm.getKey().getValueMappedBy()); - assertEquals(mapping.getRepository().getMetaData(Flat1.class, true) - .getField("basic"), fm.getKey().getValueMappedByMetaData()); + assertEquals(mapping.getRepository().getMetaData(Flat1.class, null, + true).getField("basic"), fm.getKey().getValueMappedByMetaData()); } public void testInverseOwnerMapKeyMapping() { ClassMapping mapping = ((JDBCConfiguration) emf.getConfiguration()) - .getMappingRepositoryInstance().getMapping(AnnoTest1.class, true); + .getMappingRepositoryInstance().getMapping(AnnoTest1.class, + null, true); FieldMapping fm = mapping.getFieldMapping("inverseOwnerMapKey"); assertTrue(fm.getStrategy() instanceof RelationMapInverseKeyFieldStrategy); assertEquals("basic", fm.getKey().getValueMappedBy()); assertEquals(mapping.getRepository().getMetaData(AnnoTest2.class, - true).getField("basic"), fm.getKey(). + null, true).getField("basic"), fm.getKey(). getValueMappedByMetaData()); } diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/annotations/TestTablePerClassInheritance.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/annotations/TestTablePerClassInheritance.java index db7360a78..d2bf954af 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/annotations/TestTablePerClassInheritance.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/annotations/TestTablePerClassInheritance.java @@ -42,7 +42,8 @@ public class TestTablePerClassInheritance public void testMapping() { ClassMapping mapping = ((JDBCConfiguration) emf.getConfiguration()). - getMappingRepositoryInstance().getMapping(TablePerClass2.class, true); + getMappingRepositoryInstance().getMapping(TablePerClass2.class, + null, true); assertTrue(mapping.getStrategy() instanceof FullClassStrategy); assertTrue(mapping.getDiscriminator().getStrategy() instanceof NoneDiscriminatorStrategy); diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/annotations/TestVersion.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/annotations/TestVersion.java index 22f0929fa..dbd0c49e6 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/annotations/TestVersion.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/annotations/TestVersion.java @@ -180,7 +180,8 @@ public class TestVersion extends SingleEMFTestCase { public void testNoDefaultVersionWithoutFieldOrColumn() { ClassMapping cls = ((JDBCConfiguration) emf.getConfiguration()). - getMappingRepositoryInstance().getMapping(EmbedOwner.class, true); + getMappingRepositoryInstance().getMapping(EmbedOwner.class, + null, true); assertEquals(NoneVersionStrategy.getInstance(), cls.getVersion().getStrategy()); assertEquals(0, cls.getVersion().getColumns().length); @@ -188,7 +189,8 @@ public class TestVersion extends SingleEMFTestCase { public void testVersionWithField() { ClassMapping cls = ((JDBCConfiguration) emf.getConfiguration()). - getMappingRepositoryInstance().getMapping(AnnoTest1.class, true); + getMappingRepositoryInstance().getMapping(AnnoTest1.class, + null, true); assertTrue(NoneVersionStrategy.getInstance() != cls.getVersion().getStrategy()); assertEquals(1, cls.getVersion().getColumns().length); diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/kernel/JDBCTestCase.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/kernel/JDBCTestCase.java index e0356ebe4..6e03bd59b 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/kernel/JDBCTestCase.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/kernel/JDBCTestCase.java @@ -57,7 +57,8 @@ public abstract class JDBCTestCase extends BaseJDBCTest { public ClassMapping getClassMapping(Class c) { OpenJPAConfiguration jdoConf = getConfiguration(); - return ((JDBCConfiguration) jdoConf).getMappingRepositoryInstance().getMapping(c, true); + return ((JDBCConfiguration) jdoConf).getMappingRepositoryInstance(). + getMapping(c, getClass().getClassLoader(), true); } public FieldMapping getFieldMapping(Class c, String field) { @@ -65,6 +66,7 @@ public abstract class JDBCTestCase extends BaseJDBCTest { } public boolean isInheritanceStrategyVertical() { - return VerticalClassStrategy.class.isAssignableFrom(getDefaultInheritanceStrategy()); + return VerticalClassStrategy.class. + isAssignableFrom(getDefaultInheritanceStrategy()); } } diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/kernel/TestDataStoreTrips.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/kernel/TestDataStoreTrips.java index 8b74df11b..0d608abeb 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/kernel/TestDataStoreTrips.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/kernel/TestDataStoreTrips.java @@ -77,8 +77,10 @@ public class TestDataStoreTrips extends BaseJDBCTest{ (JDBCConfiguration) ((OpenJPAEntityManagerSPI) kem) .getConfiguration(); - ClassMapping mapping = conf.getMappingRepositoryInstance().getMapping(DataStoreTripsPC.class, true); - String table = conf.getDBDictionaryInstance().getFullName(mapping.getTable(), false); + ClassMapping mapping = conf.getMappingRepositoryInstance().getMapping + (DataStoreTripsPC.class, null, true); + String table = conf.getDBDictionaryInstance() + .getFullName(mapping.getTable(), false); // get factory with counter listener _factory = getEmf(); diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/kernel/TestEfficientAttach.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/kernel/TestEfficientAttach.java index 99c6effe6..c4a4bbb19 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/kernel/TestEfficientAttach.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/kernel/TestEfficientAttach.java @@ -73,7 +73,7 @@ public class TestEfficientAttach extends TestSQLListenerTestCase { MetaDataRepository repos = conf.getMappingRepositoryInstance(); ClassMetaData meta; for (int i = 0; i < clss.length; i++) { - meta = repos.getMetaData(clss[i], true); + meta = repos.getMetaData(clss[i], null, true); detachedStateFields[i] = meta.getDetachedState(); meta.setDetachedState(null); @@ -85,7 +85,7 @@ public class TestEfficientAttach extends TestSQLListenerTestCase { } finally { // set detached state back for (int i = 0; i < clss.length; i++) - repos.getMetaData(clss[i], true).setDetachedState + repos.getMetaData(clss[i], null, true).setDetachedState (detachedStateFields[i]); } } diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/kernel/TestIncrementalJDBCFlushes.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/kernel/TestIncrementalJDBCFlushes.java index ab867710e..749b556f6 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/kernel/TestIncrementalJDBCFlushes.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/kernel/TestIncrementalJDBCFlushes.java @@ -74,7 +74,8 @@ public class TestIncrementalJDBCFlushes JDBCStore store = (JDBCStore) getStoreManager(em, true); Connection conn = store.getConnection(); ClassMapping mapping = store.getConfiguration(). - getMappingRepositoryInstance().getMapping(RuntimeTest1.class, true); + getMappingRepositoryInstance().getMapping(RuntimeTest1.class, + null, true); FieldMapping fm = mapping.getFieldMapping("stringField"); String tableName = store.getConfiguration().getDBDictionaryInstance().getFullName( diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/mapping/bidi/TestOneSidedParentChildWithImplicitForeignKey.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/mapping/bidi/TestOneSidedParentChildWithImplicitForeignKey.java index 4c58da49b..e32a70207 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/mapping/bidi/TestOneSidedParentChildWithImplicitForeignKey.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/mapping/bidi/TestOneSidedParentChildWithImplicitForeignKey.java @@ -70,7 +70,8 @@ public class TestOneSidedParentChildWithImplicitForeignKey extends MetaDataRepository repos = emf.getConfiguration() .getMetaDataRepositoryInstance(); for (int i = 0; i < VALUE_STRATEGIES.length; i++) { - ClassMetaData meta = repos.getMetaData(PARENT_ID_TYPES[i], true); + ClassMetaData meta = repos.getMetaData(PARENT_ID_TYPES[i], null, + true); FieldMetaData fmd = meta.getPrimaryKeyFields()[0]; assertEquals(fmd + " strategy is " + fmd.getValueStrategy(), VALUE_STRATEGIES[i], fmd.getValueStrategy()); diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/meta/TestJDBCType.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/meta/TestJDBCType.java index ff00fb8ee..f586375bd 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/meta/TestJDBCType.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/meta/TestJDBCType.java @@ -70,7 +70,7 @@ public class TestJDBCType DBDictionary dict = conf.getDBDictionaryInstance(); MappingRepository repos = conf.getMappingRepositoryInstance(); repos.setStrategyInstaller(new RefreshStrategyInstaller(repos)); - ClassMapping mapping = repos.getMapping(Column.class, true); + ClassMapping mapping = repos.getMapping(Column.class, null, true); Class cls; if (dict.getPreferredType(JavaSQLTypes.CLOB) == JavaSQLTypes.CLOB) { diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/meta/TestJoinToBaseClass.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/meta/TestJoinToBaseClass.java index c9883a98f..87385ebdd 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/meta/TestJoinToBaseClass.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/meta/TestJoinToBaseClass.java @@ -60,7 +60,7 @@ public class TestJoinToBaseClass public void testMapping() { ClassMapping mapping = ((JDBCConfiguration) getConfiguration()). getMappingRepositoryInstance(). - getMapping(MappingTest5.class, true); + getMapping(MappingTest5.class, null, true); Table supTable = mapping.getPCSuperclassMapping().getTable(); assertTrue(mapping.getTable() != supTable); diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/meta/TestMappedByKeyMaps.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/meta/TestMappedByKeyMaps.java index 49150f97a..593113909 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/meta/TestMappedByKeyMaps.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/meta/TestMappedByKeyMaps.java @@ -58,10 +58,12 @@ public class TestMappedByKeyMaps public void testInverseKeyMapMapping() { JDBCConfiguration conf = (JDBCConfiguration) getConfiguration(); - ClassMapping pc = conf.getMappingRepositoryInstance().getMapping(InverseKeyMapPC.class, true); + ClassMapping pc = conf.getMappingRepositoryInstance().getMapping + (InverseKeyMapPC.class, null, true); FieldMapping map = pc.getFieldMapping("helpers"); - ClassMapping helper = conf.getMappingRepositoryInstance().getMapping(HelperPC.class, true); + ClassMapping helper = conf.getMappingRepositoryInstance().getMapping + (HelperPC.class, null, true); FieldMapping str = helper.getFieldMapping("stringField"); assertEquals("stringField", map.getKey().getValueMappedBy()); @@ -75,10 +77,12 @@ public class TestMappedByKeyMaps public void testJoinTableMapMapping() { JDBCConfiguration conf = (JDBCConfiguration) getConfiguration(); - ClassMapping pc = conf.getMappingRepositoryInstance().getMapping(JoinTableMapPC.class, true); + ClassMapping pc = conf.getMappingRepositoryInstance().getMapping + (JoinTableMapPC.class, null, true); FieldMapping map = pc.getFieldMapping("helpers"); - ClassMapping helper = conf.getMappingRepositoryInstance().getMapping(HelperPC.class, true); + ClassMapping helper = conf.getMappingRepositoryInstance().getMapping + (HelperPC.class, null, true); FieldMapping str = helper.getFieldMapping("stringField"); assertEquals("stringField", map.getKey().getValueMappedBy()); @@ -253,13 +257,13 @@ public class TestMappedByKeyMaps private void setLRS(Class cls, boolean lrs) { ClassMapping cm = ((JDBCConfiguration) getConfiguration()). - getMappingRepositoryInstance().getMapping(cls, true); + getMappingRepositoryInstance().getMapping(cls, null, true); cm.getFieldMapping("helpers").setLRS(lrs); } private void unsetLRS(Class cls) { ClassMapping cm = ((JDBCConfiguration) getConfiguration()). - getMappingRepositoryInstance().getMapping(cls, true); + getMappingRepositoryInstance().getMapping(cls, null, true); cm.getFieldMapping("helpers").setLRS(false); } diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/meta/TestMetaDataValueIndicator.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/meta/TestMetaDataValueIndicator.java index c15435ff6..1b64027fa 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/meta/TestMetaDataValueIndicator.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/meta/TestMetaDataValueIndicator.java @@ -62,6 +62,7 @@ public class TestMetaDataValueIndicator } public void setUp() { + // ### I hate that we have to do this Class c = MultiE.class; c = MultiF.class; @@ -69,13 +70,16 @@ public class TestMetaDataValueIndicator eMapping = (ClassMapping) ((OpenJPAEntityManagerSPI) pm).getConfiguration(). - getMetaDataRepositoryInstance().getMetaData(MultiE.class, true); + getMetaDataRepositoryInstance().getMetaData(MultiE.class, + pm.getClassLoader(), true); fMapping = (ClassMapping) ((OpenJPAEntityManagerSPI) pm).getConfiguration(). - getMetaDataRepositoryInstance().getMetaData(MultiF.class, true); + getMetaDataRepositoryInstance().getMetaData(MultiF.class, + pm.getClassLoader(), true); } - public void tearDown() throws Exception { + public void tearDown() + throws Exception { if (pm.getTransaction().isActive()) pm.getTransaction().rollback(); pm.close(); diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/order/TestOrderColumn.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/order/TestOrderColumn.java index 9f996f68c..5152aa4b6 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/order/TestOrderColumn.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/order/TestOrderColumn.java @@ -992,7 +992,7 @@ public class TestOrderColumn extends SingleEMFTestCase { Class clazz, String fieldName) { JDBCConfiguration conf = (JDBCConfiguration) emf1.getConfiguration(); ClassMapping cls = conf.getMappingRepositoryInstance(). - getMapping(clazz, true); + getMapping(clazz, null, true); FieldMapping fm = cls.getFieldMapping(fieldName); Column oc = fm.getOrderColumn(); assertNotNull(oc); diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/order/TestOrderColumnXML.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/order/TestOrderColumnXML.java index e49f8a476..b0e24264d 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/order/TestOrderColumnXML.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/order/TestOrderColumnXML.java @@ -65,7 +65,7 @@ public class TestOrderColumnXML extends AbstractCachedEMFTestCase { MetaDataRepository repos = conf.getMetaDataRepositoryInstance(); // Force entity resolution - repos.getMetaData(BaseTestEntity2.class, true); + repos.getMetaData(BaseTestEntity2.class, null, true); OpenJPAEntityManagerSPI em = emf1.createEntityManager(); @@ -240,7 +240,7 @@ public class TestOrderColumnXML extends AbstractCachedEMFTestCase { MetaDataRepository repos = conf.newMetaDataRepositoryInstance(); // Force entity resolution - repos.getMetaData(BaseTestEntity1.class, true); + repos.getMetaData(BaseTestEntity1.class, null, true); XMLPersistenceMappingSerializer ser = new XMLPersistenceMappingSerializer((JDBCConfiguration)conf); @@ -256,7 +256,7 @@ public class TestOrderColumnXML extends AbstractCachedEMFTestCase { MetaDataRepository mdr2 = parser.getRepository(); ClassMetaData _entityMeta2 = - mdr2.getMetaData(BaseTestEntity1.class, true); + mdr2.getMetaData(BaseTestEntity1.class, null, true); // Assert metadata is populated correctly FieldMapping fm = (FieldMapping)_entityMeta2.getField("one2Melems"); @@ -286,7 +286,7 @@ public class TestOrderColumnXML extends AbstractCachedEMFTestCase { Class clazz, String fieldName) { JDBCConfiguration conf = (JDBCConfiguration) emf1.getConfiguration(); ClassMapping cls = conf.getMappingRepositoryInstance(). - getMapping(clazz, true); + getMapping(clazz, null, true); FieldMapping fm = cls.getFieldMapping(fieldName); Column oc = fm.getOrderColumn(); assertNotNull(oc); diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/query/JDBCTestCase.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/query/JDBCTestCase.java index 2a227b4bc..dab4bab80 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/query/JDBCTestCase.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/query/JDBCTestCase.java @@ -62,7 +62,8 @@ public abstract class JDBCTestCase extends AbstractTestCase { public ClassMapping getClassMapping(Class c) { OpenJPAConfiguration jdoConf = getConfiguration(); - return ((JDBCConfiguration) jdoConf).getMappingRepositoryInstance().getMapping(c, true); + return ((JDBCConfiguration) jdoConf).getMappingRepositoryInstance(). + getMapping(c, getClass().getClassLoader(), true); } public FieldMapping getFieldMapping(Class c, String field) { diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/query/TestSQLQueries.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/query/TestSQLQueries.java index 74ecd4f4c..d5947359a 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/query/TestSQLQueries.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/query/TestSQLQueries.java @@ -90,7 +90,8 @@ public class TestSQLQueries .getConfiguration(); DBDictionary dict = conf.getDBDictionaryInstance(); MappingRepository repos = conf.getMappingRepositoryInstance(); - ClassMapping mapping = repos.getMapping(RuntimeTest1.class, true); + ClassMapping mapping = repos.getMapping(RuntimeTest1.class, + pm.getClassLoader(), true); _tableName = mapping.getTable().getName(); _fullTableName = dict.getFullName(mapping.getTable(), false); @@ -381,13 +382,15 @@ public class TestSQLQueries DBDictionary dict = conf.getDBDictionaryInstance(); MappingRepository repos = conf.getMappingRepositoryInstance(); - ClassMapping mappingA = repos.getMapping(AttachD.class, true); + ClassMapping mappingA = repos.getMapping(AttachD.class, + pm.getClassLoader(), true); String tableNameA = mappingA.getTable().getName(); String fullTableNameA = dict.getFullName(mappingA.getTable(), false); String relColNameA = mappingA.getFieldMapping("a"). getColumns()[0].getName(); - ClassMapping mappingD = repos.getMapping(AttachA.class, true); + ClassMapping mappingD = repos.getMapping(AttachA.class, + pm.getClassLoader(), true); String tableNameD = mappingD.getTable().getName(); String fullTableNameD = dict.getFullName(mappingD.getTable(), false); String pkColNameD = mappingD.getTable().getPrimaryKey(). diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/schema/TestClassDBSequenceFactory.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/schema/TestClassDBSequenceFactory.java index b9484acde..e96d6d7d4 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/schema/TestClassDBSequenceFactory.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/schema/TestClassDBSequenceFactory.java @@ -226,7 +226,7 @@ public class TestClassDBSequenceFactory ClassMapping mapping = ((JDBCConfiguration) _broker.getConfiguration()). getMappingRepositoryInstance(). - getMapping(SeqD.class, true); + getMapping(SeqD.class, null, true); ClassTableJDBCSeq seq = (ClassTableJDBCSeq) _broker.getIdentitySequence(mapping); for (int i = 0; i < 51; i++) diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/schema/TestClassSequenceFactory.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/schema/TestClassSequenceFactory.java index b791303c4..3b396a69b 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/schema/TestClassSequenceFactory.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/schema/TestClassSequenceFactory.java @@ -135,11 +135,11 @@ public class TestClassSequenceFactory extends BaseJDBCTest{ return; ClassMapping aMapping = conf.getMappingRepositoryInstance(). - getMapping(SeqA.class, true); + getMapping(SeqA.class, null, true); ClassMapping bMapping = conf.getMappingRepositoryInstance(). - getMapping(SeqB.class, true); + getMapping(SeqB.class, null, true); ClassMapping cMapping = conf.getMappingRepositoryInstance(). - getMapping(SeqC.class, true); + getMapping(SeqC.class, null, true); DataSource ds = conf.getDataSource2(null); // hold a and c and start b @@ -192,7 +192,7 @@ public class TestClassSequenceFactory extends BaseJDBCTest{ try { Seq seq = _conf.getSequenceInstance(); ClassMapping mapping = _conf.getMappingRepositoryInstance(). - getMapping(SeqA.class, true); + getMapping(SeqA.class, null, true); for (int i = 0; i < 51; i++) _set.add(seq.next(_broker, mapping)); } catch (Exception e) { diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/schema/TestDBSequenceFactory.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/schema/TestDBSequenceFactory.java index 94e880b4f..d16316673 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/schema/TestDBSequenceFactory.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/schema/TestDBSequenceFactory.java @@ -105,7 +105,7 @@ public class TestDBSequenceFactory for (int i = 0; i < 51; i++) _set.add(seq.next(_broker, conf.getMetaDataRepositoryInstance(). - getMetaData(RuntimeTest1.class, true))); + getMetaData(RuntimeTest1.class, null, true))); } catch (Exception e) { throw new RuntimeException(e.getMessage()); } diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/schema/TestDynamicSchemaFactory.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/schema/TestDynamicSchemaFactory.java index 275343bbb..cbb91acb8 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/schema/TestDynamicSchemaFactory.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/schema/TestDynamicSchemaFactory.java @@ -67,7 +67,7 @@ public class TestDynamicSchemaFactory JDBCConfiguration conf = new JDBCConfigurationImpl(); conf.setSchemaFactory(DynamicSchemaFactory.class.getName()); MappingRepository repos = conf.newMappingRepositoryInstance(); - _mapping = repos.getMapping(MappingTest1.class, true); + _mapping = repos.getMapping(MappingTest1.class, null, true); } public void testClassMapping() { diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/schema/TestPerClassSequenceFactory.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/schema/TestPerClassSequenceFactory.java index 7a4283a2b..2858318e6 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/schema/TestPerClassSequenceFactory.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/schema/TestPerClassSequenceFactory.java @@ -30,12 +30,10 @@ package org.apache.openjpa.persistence.jdbc.schema; import java.util.*; import org.apache.openjpa.jdbc.conf.JDBCConfiguration; import org.apache.openjpa.jdbc.meta.ClassMapping; -import org.apache.openjpa.jdbc.meta.MappingRepository; import org.apache.openjpa.jdbc.schema.Sequence; import org.apache.openjpa.kernel.Seq; import org.apache.openjpa.kernel.StoreContext; import org.apache.openjpa.meta.ClassMetaData; -import org.apache.openjpa.meta.MetaDataRepository; import org.apache.openjpa.persistence.jdbc.common.apps.*; @@ -61,18 +59,36 @@ public class TestPerClassSequenceFactory public void testPerClassSequenceFactory() throws Exception { - Map props = new HashMap(); + Map props=new HashMap(); props.put("openjpa.Sequence", "table"); - OpenJPAEntityManagerFactory factory =(OpenJPAEntityManagerFactory)getEmf(props); + OpenJPAEntityManagerFactory factory =(OpenJPAEntityManagerFactory) + getEmf(props); - JDBCConfiguration conf = (JDBCConfiguration) factory.getConfiguration(); - MappingRepository repos = conf.getMappingRepositoryInstance(); - ClassMapping mapping1 = repos.getMapping(RuntimeTest1.class, true); - ClassMapping mapping2 = repos.getMapping(PerClassTestObject.class, true); - ClassMapping mapping3 = repos.getMapping(PerClassTestObject2.class, true); + JDBCConfiguration conf = (JDBCConfiguration) + factory.getConfiguration(); + ClassMapping mapping1 = conf.getMappingRepositoryInstance(). + getMapping(RuntimeTest1.class, null, true); + ClassMapping mapping2 = conf.getMappingRepositoryInstance(). + getMapping(PerClassTestObject.class, null, true); + ClassMapping mapping3 = conf.getMappingRepositoryInstance(). + getMapping(PerClassTestObject2.class, null, true); OpenJPAEntityManager pm =(OpenJPAEntityManager)currentEntityManager(); + //FIXME jthomas + /* + Sequence s1 = pm.getIdentitySequence(mapping1.getDescribedType()); + Sequence s2 = pm.getIdentitySequence(mapping2.getDescribedType()); + Sequence s3 = pm.getFieldSequence(mapping3.getDescribedType(), "age"); + assertTrue(((SequenceImpl) s1).getDelegate() + instanceof TableJDBCSeq); + assertTrue(((SequenceImpl) s2).getDelegate().toString(), + ((SequenceImpl) s2).getDelegate() + instanceof DummySequenceFactory); + assertTrue(((SequenceImpl) s2).getDelegate().toString(), + ((SequenceImpl) s3).getDelegate() + instanceof DummySequenceFactory); + */ } public static class DummySequenceFactory diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/schema/TestSequenceGeneratorEnsureCapacityCall.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/schema/TestSequenceGeneratorEnsureCapacityCall.java index 73ffcf3d9..210699134 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/schema/TestSequenceGeneratorEnsureCapacityCall.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/schema/TestSequenceGeneratorEnsureCapacityCall.java @@ -84,9 +84,9 @@ public class TestSequenceGeneratorEnsureCapacityCall private Seq seqForClass(Class cls) { OpenJPAConfiguration conf = getConfiguration(); ClassMetaData meta = conf.getMetaDataRepositoryInstance().getMetaData - (cls, true); + (cls, null, true); SequenceMetaData smeta = meta.getIdentitySequenceMetaData(); return (smeta == null) ? conf.getSequenceInstance() - : smeta.getInstance(); + : smeta.getInstance(null); } } diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/sqlcache/TestPreparedQueryCache.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/sqlcache/TestPreparedQueryCache.java index b3bd89767..ca75f23af 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/sqlcache/TestPreparedQueryCache.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/sqlcache/TestPreparedQueryCache.java @@ -1324,7 +1324,7 @@ public class TestPreparedQueryCache extends AbstractPersistenceTestCase { return name; return emf.getConfiguration() .getMetaDataRepositoryInstance() - .getQueryMetaData(null, name, true) + .getQueryMetaData(null, name, null, true) .getQueryString(); } diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestPCClass.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestPCClass.java index 476a24d71..e078d8e3b 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestPCClass.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestPCClass.java @@ -60,7 +60,7 @@ public class TestPCClass extends BaseKernelTest { MetaDataRepository repos = getConfiguration() .getMetaDataRepositoryInstance(); - ClassMetaData meta = repos.getMetaData(PCClassPC.class, true); + ClassMetaData meta = repos.getMetaData(PCClassPC.class, null, true); FieldMetaData fmd = meta.getField("specificPC"); assertNotNull("fmd is nulll", fmd); diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestPersistenceManagerFactoryImpl.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestPersistenceManagerFactoryImpl.java index c5413a3a9..242d55019 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestPersistenceManagerFactoryImpl.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestPersistenceManagerFactoryImpl.java @@ -162,11 +162,11 @@ public class TestPersistenceManagerFactoryImpl extends BaseKernelTest { assertTrue("no listeners defined added to Runtimetest4", broker.getLifecycleEventManager().hasLoadListeners( new RuntimeTest4("foo"), - repos.getMetaData(RuntimeTest4.class, true))); + repos.getMetaData(RuntimeTest4.class, null, true))); assertFalse("there should be listeners def for runtimetest1", broker.getLifecycleEventManager().hasLoadListeners (new RuntimeTest1(), repos.getMetaData - (RuntimeTest1.class, true))); + (RuntimeTest1.class, null, true))); broker.close(); } finally { pmfSPI.removeLifecycleListener(listener); diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/managedinterface/TestSimpleManagedInterface.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/managedinterface/TestSimpleManagedInterface.java index c79b08149..8bc03f81a 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/managedinterface/TestSimpleManagedInterface.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/managedinterface/TestSimpleManagedInterface.java @@ -42,7 +42,7 @@ public class TestSimpleManagedInterface MetaDataRepository repos = bf.getConfiguration() .getMetaDataRepositoryInstance(); ClassMetaData meta = repos.getMetaData(SimpleManagedInterface.class, - false); + null, false); assertNotNull(meta); assertTrue(meta.isManagedInterface()); assertEquals(SimpleManagedInterface.class, meta.getDescribedType()); diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/meta/TestClassMetaData.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/meta/TestClassMetaData.java index d0ef906ad..620fd14ab 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/meta/TestClassMetaData.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/meta/TestClassMetaData.java @@ -60,11 +60,11 @@ public class TestClassMetaData public void setUp() throws Exception { _repos = getRepository(); - _metaTest5 = _repos.getMetaData(MetaTest5.class, true); - _metaTest3 = _repos.getMetaData(MetaTest3.class, true); - _metaTest2 = _repos.getMetaData(MetaTest2.class, true); - _metaTest1 = _repos.getMetaData(MetaTest1.class, true); - _metaTest6 = _repos.getMetaData(MetaTest6.class, true); + _metaTest5 = _repos.getMetaData(MetaTest5.class, null, true); + _metaTest3 = _repos.getMetaData(MetaTest3.class, null, true); + _metaTest2 = _repos.getMetaData(MetaTest2.class, null, true); + _metaTest1 = _repos.getMetaData(MetaTest1.class, null, true); + _metaTest6 = _repos.getMetaData(MetaTest6.class, null, true); } protected MetaDataRepository getRepository() @@ -274,7 +274,7 @@ public class TestClassMetaData * Test that metadata on inner classes is available. */ public void testStaticInnerClasses() { - assertNotNull(_repos.getMetaData(MetaTest1.Inner.class, true)); + assertNotNull(_repos.getMetaData(MetaTest1.Inner.class, null, true)); } /** diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/meta/TestFactoryMethod.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/meta/TestFactoryMethod.java index 9651b3221..3f96b83cf 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/meta/TestFactoryMethod.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/meta/TestFactoryMethod.java @@ -48,7 +48,7 @@ public class TestFactoryMethod extends AbstractTestCase { public void setUp() throws Exception { _repos = getRepository(); - _metaTest7 = _repos.getMetaData(MetaTest7.class, true); + _metaTest7 = _repos.getMetaData(MetaTest7.class, null, true); } protected MetaDataRepository getRepository() throws Exception { diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/meta/TestNonPersistentFields.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/meta/TestNonPersistentFields.java index 1aa74cc4c..8d8f134c4 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/meta/TestNonPersistentFields.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/meta/TestNonPersistentFields.java @@ -43,7 +43,7 @@ public class TestNonPersistentFields public void setUp() { MetaDataRepository repos = new OpenJPAConfigurationImpl(). newMetaDataRepositoryInstance(); - _meta = repos.getMetaData(NonPersistentFieldsPC.class, true); + _meta = repos.getMetaData(NonPersistentFieldsPC.class, null, true); } public void testNonPersistentFields() { diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/meta/TestPersistentClasses.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/meta/TestPersistentClasses.java index d86346edc..f0bf818f3 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/meta/TestPersistentClasses.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/meta/TestPersistentClasses.java @@ -45,7 +45,8 @@ public class TestPersistentClasses private void assertClass(String clsName, OpenJPAConfiguration conf, boolean shouldExist) { - Collection names = conf.getMetaDataRepositoryInstance().getPersistentTypeNames(false); + Collection names = conf.getMetaDataRepositoryInstance(). + getPersistentTypeNames(false, null); if (shouldExist) assertTrue("expected element " + clsName + " was not found in " @@ -64,7 +65,7 @@ public class TestPersistentClasses assertNull(((OpenJPAEntityManagerFactorySPI) pmf).getConfiguration() .getMetaDataRepositoryInstance(). - getPersistentTypeNames(false)); + getPersistentTypeNames(false, null)); pmf.close(); } diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/meta/TestQueryTypeAliasRegistration.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/meta/TestQueryTypeAliasRegistration.java index b40937b87..9899d8c80 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/meta/TestQueryTypeAliasRegistration.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/meta/TestQueryTypeAliasRegistration.java @@ -94,7 +94,7 @@ public class TestQueryTypeAliasRegistration extends SingleEMFTestCase { @Override public void run() { try { - repo.getMetaData("MdrTestEntity", true); + repo.getMetaData("MdrTestEntity", Thread.currentThread().getContextClassLoader(), true); } catch (Exception e) { ex = e; e.printStackTrace(); diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/meta/TestValueStrategies.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/meta/TestValueStrategies.java index af187a7e7..b07d88b61 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/meta/TestValueStrategies.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/meta/TestValueStrategies.java @@ -231,7 +231,7 @@ public class TestValueStrategies pm.persist(pc); ClassMetaData meta = getConfiguration() .getMetaDataRepositoryInstance(). - getMetaData(pc.getClass(), false); + getMetaData(pc.getClass(), null, false); assertNotNull(meta.getVersionField()); assertEquals("version", meta.getVersionField().getName()); assertEquals(0, pc.getVersion()); diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/meta/TestXMLPersistenceMetaDataSerializer.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/meta/TestXMLPersistenceMetaDataSerializer.java index b14c7eef4..c0669d5de 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/meta/TestXMLPersistenceMetaDataSerializer.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/meta/TestXMLPersistenceMetaDataSerializer.java @@ -53,11 +53,11 @@ public class TestXMLPersistenceMetaDataSerializer throws Exception { OpenJPAConfiguration conf = new OpenJPAConfigurationImpl(); MetaDataRepository repos = conf.newMetaDataRepositoryInstance(); - repos.getMetaData(MetaTest5.class, true); - repos.getMetaData(MetaTest3.class, true); - repos.getMetaData(MetaTest2.class, true); - repos.getMetaData(MetaTest1.class, true); - repos.getMetaData(MetaTest6.class, true); + repos.getMetaData(MetaTest5.class, null, true); + repos.getMetaData(MetaTest3.class, null, true); + repos.getMetaData(MetaTest2.class, null, true); + repos.getMetaData(MetaTest1.class, null, true); + repos.getMetaData(MetaTest6.class, null, true); XMLPersistenceMetaDataSerializer ser = new XMLPersistenceMetaDataSerializer(conf); diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/query/TestAccessPathsOfSubqueries.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/query/TestAccessPathsOfSubqueries.java index 2fd2b4381..81e409a8c 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/query/TestAccessPathsOfSubqueries.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/query/TestAccessPathsOfSubqueries.java @@ -38,7 +38,6 @@ import org.apache.openjpa.kernel.Broker; import org.apache.openjpa.kernel.Query; import org.apache.openjpa.kernel.jpql.JPQLParser; import org.apache.openjpa.meta.ClassMetaData; -import org.apache.openjpa.meta.MetaDataRepository; public class TestAccessPathsOfSubqueries extends BaseQueryTest { @@ -58,9 +57,12 @@ public class TestAccessPathsOfSubqueries extends BaseQueryTest { + "WHERE rt5.name IS NOT NULL)"); ClassMetaData[] metas = q.getAccessPathMetaDatas(); Collection c = Arrays.asList(metas); - MetaDataRepository repos = broker.getConfiguration().getMetaDataRepositoryInstance(); - ClassMetaData rt1 = repos.getMetaData(RuntimeTest1.class,true); - ClassMetaData rt5 = repos.getMetaData(RuntimeTest5.class,true); + ClassMetaData rt1 = broker.getConfiguration(). + getMetaDataRepositoryInstance().getMetaData(RuntimeTest1.class, + broker.getClassLoader(), true); + ClassMetaData rt5 = broker.getConfiguration(). + getMetaDataRepositoryInstance().getMetaData(RuntimeTest5.class, + broker.getClassLoader(), true); assertTrue(c.contains(rt1)); assertTrue(c.contains(rt5)); assertEquals(2, c.size()); @@ -75,10 +77,15 @@ public class TestAccessPathsOfSubqueries extends BaseQueryTest { ClassMetaData[] metas = q.getAccessPathMetaDatas(); Collection c = Arrays.asList(metas); - MetaDataRepository repos = broker.getConfiguration().getMetaDataRepositoryInstance(); - ClassMetaData rt1 = repos.getMetaData(RuntimeTest1.class, true); - ClassMetaData rt4 = repos.getMetaData(RuntimeTest4.class, true); - ClassMetaData rt5 = repos.getMetaData(RuntimeTest5.class, true); + ClassMetaData rt1 = broker.getConfiguration(). + getMetaDataRepositoryInstance().getMetaData(RuntimeTest1.class, + broker.getClassLoader(), true); + ClassMetaData rt4 = broker.getConfiguration(). + getMetaDataRepositoryInstance().getMetaData(RuntimeTest4.class, + broker.getClassLoader(), true); + ClassMetaData rt5 = broker.getConfiguration(). + getMetaDataRepositoryInstance().getMetaData(RuntimeTest5.class, + broker.getClassLoader(), true); assertTrue(c.contains(rt1)); assertTrue(c.contains(rt4)); assertTrue(c.contains(rt5)); diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/query/TestNamedQueries.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/query/TestNamedQueries.java index 53294072c..80131c527 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/query/TestNamedQueries.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/query/TestNamedQueries.java @@ -86,7 +86,8 @@ public class TestNamedQueries extends BaseQueryTest { assertEquals("num", query.getGrouping()); */ QueryMetaData meta = ((OpenJPAEntityManagerSPI) pm).getConfiguration(). - getMetaDataRepositoryInstance().getQueryMetaData(null, "named", true); + getMetaDataRepositoryInstance().getQueryMetaData(null, + "named", pm.getClassLoader(), true); assertNotNull(meta); assertEquals("SELECT o FROM QueryTest1 o", meta.getQueryString()); assertEquals(null, meta.getResultType()); diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/test/ContainerEMFTest.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/test/ContainerEMFTest.java index b3103aa15..c9bcb4b6a 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/test/ContainerEMFTest.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/test/ContainerEMFTest.java @@ -85,7 +85,7 @@ public abstract class ContainerEMFTest extends SingleEMFTestCase { clist = (List>)map.remove(PERSISTENT_CLASS_LIST); } PersistenceProductDerivation.ConfigurationParser cfgParser = - new PersistenceProductDerivation.ConfigurationParser(this.getClass().getClassLoader(), config); + new PersistenceProductDerivation.ConfigurationParser(config); try { URL url = getResourceURL(persistenceFile); cfgParser.parse(url); diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/test/SingleEMFTestCase.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/test/SingleEMFTestCase.java index 8ed88f754..c0b6d7265 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/test/SingleEMFTestCase.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/test/SingleEMFTestCase.java @@ -25,7 +25,6 @@ import javax.persistence.EntityManager; import org.apache.openjpa.jdbc.conf.JDBCConfiguration; import org.apache.openjpa.jdbc.meta.ClassMapping; import org.apache.openjpa.jdbc.sql.DBDictionary; -import org.apache.openjpa.lib.conf.ProductDerivations; import org.apache.openjpa.lib.log.Log; import org.apache.openjpa.persistence.OpenJPAEntityManagerFactorySPI; import org.apache.openjpa.persistence.OpenJPAEntityManagerSPI; @@ -104,7 +103,8 @@ public abstract class SingleEMFTestCase */ protected ClassMapping getMapping(String name) { return (ClassMapping) emf.getConfiguration() - .getMetaDataRepositoryInstance().getMetaData(name, true); + .getMetaDataRepositoryInstance().getMetaData(name, + getClass().getClassLoader(), true); } /** @@ -117,7 +117,8 @@ public abstract class SingleEMFTestCase */ protected ClassMapping getMapping(Class entityClass) { return (ClassMapping) emf.getConfiguration() - .getMetaDataRepositoryInstance().getMetaData(entityClass, true); + .getMetaDataRepositoryInstance().getMetaData(entityClass, + getClass().getClassLoader(), true); } /** @@ -159,7 +160,7 @@ public abstract class SingleEMFTestCase public String getAlias(Class t) { return emf.getConfiguration().getMetaDataRepositoryInstance() - .getMetaData(t, true).getTypeAlias(); + .getMetaData(t, null, true).getTypeAlias(); } protected ClassMapping [] getMappings() { diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/util/TestJPAFacadeHelper.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/util/TestJPAFacadeHelper.java index fd8156440..f03ac207f 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/util/TestJPAFacadeHelper.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/util/TestJPAFacadeHelper.java @@ -57,7 +57,7 @@ public class TestJPAFacadeHelper extends SingleEMFTestCase { } public void testEmbeddedId() throws Exception { - ClassMetaData cmd = repo.getMetaData(EmbeddedIdEntity.class, true); + ClassMetaData cmd = repo.getMetaData(EmbeddedIdEntity.class, null, true); try { JPAFacadeHelper.toOpenJPAObjectId(cmd, new EmbeddedIdEntity()); fail("Didn't fail!"); @@ -70,7 +70,7 @@ public class TestJPAFacadeHelper extends SingleEMFTestCase { } public void testCompositeId() throws Exception { - ClassMetaData cmd = repo.getMetaData(EntityWithCompositeId.class, true); + ClassMetaData cmd = repo.getMetaData(EntityWithCompositeId.class, null, true); try { JPAFacadeHelper.toOpenJPAObjectId(cmd, new EntityWithCompositeId()); fail("Didn't fail!"); @@ -83,7 +83,7 @@ public class TestJPAFacadeHelper extends SingleEMFTestCase { } public void testBasic() throws Exception { - ClassMetaData cmd = repo.getMetaData(BasicEntity.class, true); + ClassMetaData cmd = repo.getMetaData(BasicEntity.class, null, true); try { JPAFacadeHelper.toOpenJPAObjectId(cmd, new BasicEntity()); fail("Didn't fail!"); @@ -103,7 +103,7 @@ public class TestJPAFacadeHelper extends SingleEMFTestCase { } public void testDerivedId() throws Exception { - ClassMetaData cmd = repo.getMetaData(EDSQLDateID.class, true); + ClassMetaData cmd = repo.getMetaData(EDSQLDateID.class, null, true); try { JPAFacadeHelper.toOpenJPAObjectId(cmd, new EDSQLDateID()); fail("Didn't fail!"); @@ -116,7 +116,7 @@ public class TestJPAFacadeHelper extends SingleEMFTestCase { } public void testNoId() throws Exception { - ClassMetaData cmd = repo.getMetaData(AllFieldTypes.class, true); + ClassMetaData cmd = repo.getMetaData(AllFieldTypes.class, null, true); try { // Don't parameterize this collection to force the JVM to use the // ...(ClassMetaData meta, Collection oids) method sig. diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/xml/TestXmlOverrideEntity.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/xml/TestXmlOverrideEntity.java index 136589ac7..07c7c63c2 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/xml/TestXmlOverrideEntity.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/xml/TestXmlOverrideEntity.java @@ -60,11 +60,13 @@ public class TestXmlOverrideEntity extends SingleEMFTestCase { public void testOverriddenEntityName() { emf.createEntityManager().close(); - ClassMetaData meta = JPAFacadeHelper.getMetaData(emf, XmlOverrideEntity.class); + ClassMetaData meta = JPAFacadeHelper.getMetaData(emf, + XmlOverrideEntity.class); assertEquals("XmlOverride", meta.getTypeAlias()); MetaDataRepository repo = emf.getConfiguration() .getMetaDataRepositoryInstance(); - assertEquals(meta, repo.getMetaData("XmlOverride", true)); + assertEquals(meta, repo.getMetaData("XmlOverride", + XmlOverrideEntity.class.getClassLoader(), true)); } /** diff --git a/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/AnnotationPersistenceMetaDataParser.java b/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/AnnotationPersistenceMetaDataParser.java index fb1bd595a..ef0f81bfe 100644 --- a/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/AnnotationPersistenceMetaDataParser.java +++ b/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/AnnotationPersistenceMetaDataParser.java @@ -181,9 +181,11 @@ import serp.util.Strings; public class AnnotationPersistenceMetaDataParser implements MetaDataModes { - private static final Localizer _loc = Localizer.forPackage(AnnotationPersistenceMetaDataParser.class); + private static final Localizer _loc = Localizer.forPackage + (AnnotationPersistenceMetaDataParser.class); - private static final Map, MetaDataTag> _tags = new HashMap, MetaDataTag>(); + private static final Map, MetaDataTag> _tags = + new HashMap, MetaDataTag>(); static { _tags.put(Access.class, ACCESS); @@ -191,7 +193,8 @@ public class AnnotationPersistenceMetaDataParser _tags.put(EmbeddedId.class, EMBEDDED_ID); _tags.put(EntityListeners.class, ENTITY_LISTENERS); _tags.put(ExcludeDefaultListeners.class, EXCLUDE_DEFAULT_LISTENERS); - _tags.put(ExcludeSuperclassListeners.class, EXCLUDE_SUPERCLASS_LISTENERS); + _tags.put(ExcludeSuperclassListeners.class, + EXCLUDE_SUPERCLASS_LISTENERS); _tags.put(FlushModeType.class, FLUSH_MODE); _tags.put(GeneratedValue.class, GENERATED_VALUE); _tags.put(Id.class, ID); @@ -237,6 +240,7 @@ public class AnnotationPersistenceMetaDataParser private final OpenJPAConfiguration _conf; private final Log _log; private MetaDataRepository _repos = null; + private ClassLoader _envLoader = null; private boolean _override = false; private int _mode = MODE_NONE; @@ -294,6 +298,21 @@ public class AnnotationPersistenceMetaDataParser _repos = repos; } + /** + * Return the environmental class loader to pass on to parsed + * metadata instances. + */ + public ClassLoader getEnvClassLoader() { + return _envLoader; + } + + /** + * Set the environmental class loader to pass on to parsed + * metadata instances. + */ + public void setEnvClassLoader(ClassLoader loader) { + _envLoader = loader; + } /** * Whether to allow later parses of mapping information to override @@ -731,6 +750,7 @@ public class AnnotationPersistenceMetaDataParser if (meta == null) { meta = getRepository().addMetaData(_cls, getAccessCode(_cls)); + meta.setEnvClassLoader(_envLoader); meta.setSourceMode(MODE_NONE); meta.setSource(getSourceFile(), SourceTracker.SRC_ANNOTATIONS, getSourceFile() == null ? "" : getSourceFile().getPath()); diff --git a/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/EntityManagerFactoryValue.java b/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/EntityManagerFactoryValue.java index ede007fff..5ffc6015b 100644 --- a/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/EntityManagerFactoryValue.java +++ b/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/EntityManagerFactoryValue.java @@ -18,8 +18,6 @@ */ package org.apache.openjpa.persistence; -import javax.persistence.EntityManagerFactory; - import org.apache.openjpa.conf.OpenJPAConfiguration; import org.apache.openjpa.kernel.BrokerFactory; import org.apache.openjpa.lib.conf.PluginValue; @@ -31,7 +29,7 @@ import org.apache.openjpa.lib.conf.PluginValue; * @nojavadoc */ public class EntityManagerFactoryValue - extends PluginValue { + extends PluginValue { /** * Configuration property key. @@ -47,16 +45,17 @@ public class EntityManagerFactoryValue */ public static OpenJPAEntityManagerFactory newFactory(BrokerFactory bf) { OpenJPAConfiguration conf = bf.getConfiguration(); - PluginValue val = (PluginValue) conf.getValue(KEY); + PluginValue val = (PluginValue) conf.getValue(KEY); if (val == null) return null; - EntityManagerFactoryImpl emf = (EntityManagerFactoryImpl)val.instantiate(conf, true); + EntityManagerFactoryImpl emf = (EntityManagerFactoryImpl) val. + instantiate(EntityManagerFactoryImpl.class, conf, true); emf.setBrokerFactory(bf); return emf; } public EntityManagerFactoryValue() { - super(OpenJPAEntityManagerFactory.class, KEY, false); + super(KEY, false); setAliases(ALIASES); setDefault(ALIASES[0]); setClassName(ALIASES[1]); diff --git a/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/EntityManagerImpl.java b/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/EntityManagerImpl.java index 03ee6a78b..2d2a3a34a 100644 --- a/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/EntityManagerImpl.java +++ b/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/EntityManagerImpl.java @@ -219,6 +219,10 @@ public class EntityManagerImpl _broker.setSyncWithManagedTransactions(sync); } + public ClassLoader getClassLoader() { + return _broker.getClassLoader(); + } + public String getConnectionUserName() { return _broker.getConnectionUserName(); } @@ -919,8 +923,9 @@ public class EntityManagerImpl assertNotCloseInvoked(); try { SequenceMetaData meta = _broker.getConfiguration(). - getMetaDataRepositoryInstance().getSequenceMetaData(name, true); - Seq seq = meta.getInstance(); + getMetaDataRepositoryInstance().getSequenceMetaData(name, + _broker.getClassLoader(), true); + Seq seq = meta.getInstance(_broker.getClassLoader()); return new GeneratorImpl(seq, name, _broker, null); } catch (RuntimeException re) { throw PersistenceExceptions.toPersistenceException(re); @@ -931,7 +936,8 @@ public class EntityManagerImpl assertNotCloseInvoked(); try { ClassMetaData meta = _broker.getConfiguration(). - getMetaDataRepositoryInstance().getMetaData(forClass, true); + getMetaDataRepositoryInstance().getMetaData(forClass, + _broker.getClassLoader(), true); Seq seq = _broker.getIdentitySequence(meta); return (seq == null) ? null : new GeneratorImpl(seq, null, _broker, meta); @@ -944,7 +950,8 @@ public class EntityManagerImpl assertNotCloseInvoked(); try { ClassMetaData meta = _broker.getConfiguration(). - getMetaDataRepositoryInstance().getMetaData(forClass, true); + getMetaDataRepositoryInstance().getMetaData(forClass, + _broker.getClassLoader(), true); FieldMetaData fmd = meta.getField(fieldName); if (fmd == null) throw new ArgumentException(_loc.get("no-named-field", @@ -1015,7 +1022,8 @@ public class EntityManagerImpl _broker.assertOpen(); try { QueryMetaData meta = _broker.getConfiguration(). - getMetaDataRepositoryInstance().getQueryMetaData(null, name, true); + getMetaDataRepositoryInstance().getQueryMetaData(null, name, + _broker.getClassLoader(), true); String qid = meta.getQueryString(); PreparedQuery pq = JPQLParser.LANG_JPQL.equals(meta.getLanguage()) ? getPreparedQuery(qid) : null; diff --git a/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/HintHandler.java b/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/HintHandler.java index d99d5f6a7..9f59f8f00 100644 --- a/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/HintHandler.java +++ b/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/HintHandler.java @@ -145,7 +145,7 @@ public class HintHandler { return; } - ClassLoader loader = owner.getDelegate().getBroker().getConfiguration().getClassLoader(); + ClassLoader loader = owner.getDelegate().getBroker().getClassLoader(); if (QueryHints.HINT_SUBCLASSES.equals(key)) { if (value instanceof String) value = Boolean.valueOf((String) value); diff --git a/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/JPAFacadeHelper.java b/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/JPAFacadeHelper.java index 14b8c4623..5e44b41e3 100644 --- a/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/JPAFacadeHelper.java +++ b/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/JPAFacadeHelper.java @@ -177,7 +177,7 @@ public class JPAFacadeHelper { OpenJPAPersistence.cast(em); try { return kem.getConfiguration().getMetaDataRepositoryInstance(). - getMetaData(cls, false); + getMetaData(cls, kem.getClassLoader(), false); } catch (Exception e) { throw PersistenceExceptions.toPersistenceException(e); } @@ -196,7 +196,7 @@ public class JPAFacadeHelper { (OpenJPAEntityManagerFactorySPI) OpenJPAPersistence.cast(emf); try { return emfSPI.getConfiguration().getMetaDataRepositoryInstance(). - getMetaData(cls, false); + getMetaData(cls, null, false); } catch (Exception e) { throw PersistenceExceptions.toPersistenceException(e); } diff --git a/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/OpenJPAEntityManager.java b/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/OpenJPAEntityManager.java index 2e927be6c..b0e7b64e8 100644 --- a/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/OpenJPAEntityManager.java +++ b/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/OpenJPAEntityManager.java @@ -109,6 +109,12 @@ public interface OpenJPAEntityManager */ public void setSyncWithManagedTransactions(boolean resync); + /** + * Return the current thread's class loader at the time this entity + * manager was obtained from the factory. + */ + public ClassLoader getClassLoader(); + /** * Return the connection user name. */ diff --git a/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/OpenJPAPersistence.java b/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/OpenJPAPersistence.java index 6196561c6..6fcfdeb85 100644 --- a/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/OpenJPAPersistence.java +++ b/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/OpenJPAPersistence.java @@ -86,9 +86,11 @@ public class OpenJPAPersistence { * overrides. */ public static OpenJPAEntityManagerFactory getEntityManagerFactory(Map map) { - ConfigurationProvider cp = new PersistenceProductDerivation.ConfigurationProviderImpl(map); + ConfigurationProvider cp = new PersistenceProductDerivation. + ConfigurationProviderImpl(map); try { - return JPAFacadeHelper.toEntityManagerFactory(Bootstrap.getBrokerFactory(cp)); + return JPAFacadeHelper.toEntityManagerFactory( + Bootstrap.getBrokerFactory(cp, null)); } catch (Exception e) { throw PersistenceExceptions.toPersistenceException(e); } diff --git a/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/PersistenceMetaDataDefaults.java b/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/PersistenceMetaDataDefaults.java index da631f1c8..e62e3981e 100644 --- a/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/PersistenceMetaDataDefaults.java +++ b/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/PersistenceMetaDataDefaults.java @@ -309,7 +309,7 @@ public class PersistenceMetaDataDefaults MetaDataRepository repos = meta.getRepository(); ClassMetaData supMeta = repos.getCachedMetaData(sup); if (supMeta == null) - supMeta = repos.getMetaData(sup, false); + supMeta = repos.getMetaData(sup, null, false); return supMeta; } diff --git a/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/PersistenceMetaDataFactory.java b/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/PersistenceMetaDataFactory.java index 43bb78865..8e2f4ad5f 100644 --- a/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/PersistenceMetaDataFactory.java +++ b/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/PersistenceMetaDataFactory.java @@ -75,9 +75,11 @@ public class PersistenceMetaDataFactory extends AbstractCFMetaDataFactory implements Configurable, GenericConfigurable { - private static final Localizer _loc = Localizer.forPackage(PersistenceMetaDataFactory.class); + private static final Localizer _loc = Localizer.forPackage + (PersistenceMetaDataFactory.class); - private final PersistenceMetaDataDefaults _def = new PersistenceMetaDataDefaults(); + private final PersistenceMetaDataDefaults _def = + new PersistenceMetaDataDefaults(); private AnnotationPersistenceMetaDataParser _annoParser = null; private AnnotationPersistenceXMLMetaDataParser _annoXMLParser = null; private XMLPersistenceMetaDataParser _xmlParser = null; @@ -85,7 +87,8 @@ public class PersistenceMetaDataFactory private Set _unparsed = null; // xml rsrc private boolean _fieldOverride = true; - protected Stack _stack = new Stack(); + protected Stack _stack = + new Stack(); /** * Whether to use field-level override or class-level override. @@ -117,7 +120,8 @@ public class PersistenceMetaDataFactory /** * Set the metadata parser. */ - public void setAnnotationParser(AnnotationPersistenceMetaDataParser parser) { + public void setAnnotationParser( + AnnotationPersistenceMetaDataParser parser) { if (_annoParser != null) _annoParser.setRepository(null); if (parser != null) @@ -129,7 +133,8 @@ public class PersistenceMetaDataFactory * Create a new metadata parser. */ protected AnnotationPersistenceMetaDataParser newAnnotationParser() { - return new AnnotationPersistenceMetaDataParser(repos.getConfiguration()); + return new AnnotationPersistenceMetaDataParser + (repos.getConfiguration()); } /** @@ -200,7 +205,7 @@ public class PersistenceMetaDataFactory return new XMLPersistenceMetaDataSerializer(repos.getConfiguration()); } - public void load(Class cls, int mode) { + public void load(Class cls, int mode, ClassLoader envLoader) { if (mode == MODE_NONE) return; if (!strict && (mode & MODE_META) != 0) @@ -209,7 +214,7 @@ public class PersistenceMetaDataFactory // getting the list of persistent types runs callbacks to // mapPersistentTypeNames if it hasn't been called already, which // caches XML resources - getPersistentTypeNames(false); + getPersistentTypeNames(false, envLoader); URL xml = findXML(cls); // we have to parse metadata up-front to register persistence unit @@ -220,7 +225,7 @@ public class PersistenceMetaDataFactory && (mode & MODE_META) != 0) { Set unparsed = new HashSet(_unparsed); for (URL url : unparsed) { - parseXML(url, cls, mode); + parseXML(url, cls, mode, envLoader); } parsedXML = unparsed.contains(xml); _unparsed.clear(); @@ -240,7 +245,7 @@ public class PersistenceMetaDataFactory // we may still need to parse XML if this is a redeploy of a class, or // if we're in strict query-only mode if (!parsedXML && xml != null) { - parseXML(xml, cls, mode); + parseXML(xml, cls, mode, envLoader); // XML process check meta = repos.getCachedMetaData(cls); if (meta != null && (meta.getSourceMode() & mode) == mode) { @@ -250,6 +255,7 @@ public class PersistenceMetaDataFactory } AnnotationPersistenceMetaDataParser parser = getAnnotationParser(); + parser.setEnvClassLoader(envLoader); parser.setMode(mode); parser.parse(cls); @@ -261,11 +267,27 @@ public class PersistenceMetaDataFactory /** * Parse the given XML resource. */ - private void parseXML(URL xml, Class cls, int mode) { + private void parseXML(URL xml, Class cls, int mode, + ClassLoader envLoader) { // spring needs to use the envLoader first for all class resolution, // but we must still fall back on application loader + ClassLoader loader = repos.getConfiguration(). + getClassResolverInstance().getClassLoader(cls, null); + if (envLoader != null && envLoader != loader) { + MultiClassLoader mult = new MultiClassLoader(); + mult.addClassLoader(envLoader); + + // loader from resolver is usually a multi loader itself + if (loader instanceof MultiClassLoader) + mult.addClassLoaders((MultiClassLoader)loader); + else + mult.addClassLoader(loader); + loader = mult; + } XMLPersistenceMetaDataParser xmlParser = getXMLParser(); + xmlParser.setClassLoader(loader); + xmlParser.setEnvClassLoader(envLoader); xmlParser.setMode(mode); try { xmlParser.parse(xml); @@ -322,10 +344,10 @@ public class PersistenceMetaDataFactory } @Override - public Class getQueryScope(String queryName) { + public Class getQueryScope(String queryName, ClassLoader loader) { if (queryName == null) return null; - Collection> classes = repos.loadPersistentTypes(false); + Collection> classes = repos.loadPersistentTypes(false, loader); for (Class cls : classes) { if ((AccessController.doPrivileged(J2DoPrivHelper .isAnnotationPresentAction(cls, NamedQuery.class))) @@ -355,11 +377,12 @@ public class PersistenceMetaDataFactory } @Override - public Class getResultSetMappingScope(String rsMappingName) { + public Class getResultSetMappingScope(String rsMappingName, + ClassLoader loader) { if (rsMappingName == null) return null; - Collection> classes = repos.loadPersistentTypes(false); + Collection> classes = repos.loadPersistentTypes(false, loader); for (Class cls : classes) { if ((AccessController.doPrivileged(J2DoPrivHelper @@ -488,7 +511,8 @@ public class PersistenceMetaDataFactory * Look for META-INF/orm.xml, and if it doesn't exist, choose a default. */ private File defaultXMLFile() { - ClassLoader loader = repos.getConfiguration().getClassLoader(); + ClassLoader loader = repos.getConfiguration(). + getClassResolverInstance().getClassLoader(getClass(), null); URL rsrc = AccessController.doPrivileged( J2DoPrivHelper.getResourceAction(loader, "META-INF/orm.xml")); if (rsrc != null) { diff --git a/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/PersistenceProductDerivation.java b/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/PersistenceProductDerivation.java index cf6b33d81..4341dd435 100644 --- a/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/PersistenceProductDerivation.java +++ b/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/PersistenceProductDerivation.java @@ -48,6 +48,7 @@ import org.apache.openjpa.conf.OpenJPAConfigurationImpl; import org.apache.openjpa.conf.OpenJPAProductDerivation; import org.apache.openjpa.conf.Specification; import org.apache.openjpa.datacache.DataCacheMode; +import org.apache.openjpa.kernel.MixedLockLevels; import org.apache.openjpa.kernel.QueryHints; import org.apache.openjpa.lib.conf.AbstractProductDerivation; import org.apache.openjpa.lib.conf.Configuration; @@ -60,12 +61,9 @@ import org.apache.openjpa.lib.meta.XMLMetaDataParser; import org.apache.openjpa.lib.meta.XMLVersionParser; 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.persistence.osgi.BundleUtils; -import org.apache.openjpa.validation.Validator; import org.xml.sax.Attributes; import org.xml.sax.SAXException; -import static org.apache.openjpa.kernel.MixedLockLevels.*; + /** * Sets JPA specification defaults and parses JPA specification XML files. @@ -80,7 +78,6 @@ import static org.apache.openjpa.kernel.MixedLockLevels.*; * a named one). * * @author Abe White - * @author Pinaki Poddar * @nojavadoc */ public class PersistenceProductDerivation @@ -93,8 +90,11 @@ public class PersistenceProductDerivation public static final String RSRC_DEFAULT = "META-INF/persistence.xml"; public static final BigDecimal VERSION_1_0 = BigDecimal.valueOf(1.0); - private static final Localizer _loc = Localizer.forPackage(PersistenceProductDerivation.class); + private static final Localizer _loc = Localizer.forPackage + (PersistenceProductDerivation.class); + private HashMap _puNameCollisions + = new HashMap(); public static final String PREFIX = "javax.persistence"; @@ -104,11 +104,8 @@ public class PersistenceProductDerivation private static Set _hints = new HashSet(); - /** - * The loader used to load resources and classes by name and eventually set into - * the configuration. - */ - private final MultiClassLoader _loader; + // Provider name to filter out PUs that don't belong to this derivation. + protected String _providerImplName; static { _hints.add("javax.persistence.lock.timeout"); @@ -152,21 +149,8 @@ public class PersistenceProductDerivation _hints = Collections.unmodifiableSet(_hints); } - public PersistenceProductDerivation() { - this(false); - } - - /** - * Constructs and configures a class loader to be used for loading - * resources and classes by their names. - */ - public PersistenceProductDerivation(boolean osgi) { - _loader = AccessController.doPrivileged(J2DoPrivHelper.newMultiClassLoaderAction()); - if (osgi) - _loader.addClassLoader(BundleUtils.getBundleClassLoader()); - _loader.addClassLoader(MultiClassLoader.THREAD_LOADER); - _loader.addClassLoader(this.getClass().getClassLoader()); - _loader.addClassLoader(MultiClassLoader.SYSTEM_LOADER); + public PersistenceProductDerivation() { + _providerImplName = PersistenceProviderImpl.class.getName(); } public void putBrokerFactoryAliases(Map m) { @@ -187,7 +171,8 @@ public class PersistenceProductDerivation } @Override - public void validate() throws Exception { + public void validate() + throws Exception { // make sure JPA is available AccessController.doPrivileged(J2DoPrivHelper.getClassLoaderAction( javax.persistence.EntityManagerFactory.class)); @@ -204,17 +189,26 @@ public class PersistenceProductDerivation conf.addValue(new EntityManagerFactoryValue()); - conf.readLockLevel.setAlias("optimistic", String.valueOf(LOCK_OPTIMISTIC)); - conf.readLockLevel.setAlias("optimistic-force-increment", String.valueOf(LOCK_OPTIMISTIC_FORCE_INCREMENT)); - conf.readLockLevel.setAlias("pessimistic-read", String.valueOf(LOCK_PESSIMISTIC_READ)); - conf.readLockLevel.setAlias("pessimistic-write", String.valueOf(LOCK_PESSIMISTIC_WRITE)); - conf.readLockLevel.setAlias("pessimistic-force-increment", String.valueOf(LOCK_PESSIMISTIC_FORCE_INCREMENT)); + conf.readLockLevel.setAlias("optimistic", String.valueOf(MixedLockLevels.LOCK_OPTIMISTIC)); + conf.readLockLevel.setAlias("optimistic-force-increment", String + .valueOf(MixedLockLevels.LOCK_OPTIMISTIC_FORCE_INCREMENT)); + conf.readLockLevel.setAlias("pessimistic-read", String + .valueOf(MixedLockLevels.LOCK_PESSIMISTIC_READ)); + conf.readLockLevel.setAlias("pessimistic-write", String + .valueOf(MixedLockLevels.LOCK_PESSIMISTIC_WRITE)); + conf.readLockLevel.setAlias("pessimistic-force-increment", String + .valueOf(MixedLockLevels.LOCK_PESSIMISTIC_FORCE_INCREMENT)); - conf.writeLockLevel.setAlias("optimistic", String.valueOf(LOCK_OPTIMISTIC)); - conf.writeLockLevel.setAlias("optimistic-force-increment", String.valueOf(LOCK_OPTIMISTIC_FORCE_INCREMENT)); - conf.writeLockLevel.setAlias("pessimistic-read", String.valueOf(LOCK_PESSIMISTIC_READ)); - conf.writeLockLevel.setAlias("pessimistic-write", String.valueOf(LOCK_PESSIMISTIC_WRITE)); - conf.writeLockLevel.setAlias("pessimistic-force-increment", String.valueOf(LOCK_PESSIMISTIC_FORCE_INCREMENT)); + conf.writeLockLevel.setAlias("optimistic", String + .valueOf(MixedLockLevels.LOCK_OPTIMISTIC)); + conf.writeLockLevel.setAlias("optimistic-force-increment", String + .valueOf(MixedLockLevels.LOCK_OPTIMISTIC_FORCE_INCREMENT)); + conf.writeLockLevel.setAlias("pessimistic-read", String + .valueOf(MixedLockLevels.LOCK_PESSIMISTIC_READ)); + conf.writeLockLevel.setAlias("pessimistic-write", String + .valueOf(MixedLockLevels.LOCK_PESSIMISTIC_WRITE)); + conf.writeLockLevel.setAlias("pessimistic-force-increment", String + .valueOf(MixedLockLevels.LOCK_PESSIMISTIC_FORCE_INCREMENT)); configureBeanValidation(conf); @@ -236,8 +230,8 @@ public class PersistenceProductDerivation */ private void configureBeanValidation(OpenJPAConfigurationImpl conf) { // Validation defines/adds the following plugins to OpenJPA Configuration - conf.validationFactory = conf.addObject(Object.class, JPAProperties.VALIDATE_FACTORY); - conf.validator = conf.addObject(Validator.class, "Validator"); + conf.validationFactory = conf.addObject(JPAProperties.VALIDATE_FACTORY); + conf.validator = conf.addObject("Validator"); conf.validationMode = conf.addString(JPAProperties.VALIDATE_MODE); conf.validationGroupPrePersist = conf.addString(JPAProperties.VALIDATE_PRE_PERSIST); conf.validationGroupPreUpdate = conf.addString(JPAProperties.VALIDATE_PRE_UPDATE); @@ -308,10 +302,12 @@ public class PersistenceProductDerivation * Load configuration from the given persistence unit with the specified * user properties. */ - public ConfigurationProvider load(PersistenceUnitInfo pinfo, Map m) throws IOException { + public ConfigurationProvider load(PersistenceUnitInfo pinfo, Map m) + throws IOException { if (pinfo == null) return null; - if (!isOpenJPAPersistenceProvider(pinfo)) { + if (!isOpenJPAPersistenceProvider(pinfo, null)) { + warnUnknownProvider(pinfo); return null; } @@ -337,7 +333,7 @@ public class PersistenceProductDerivation rsrc = RSRC_DEFAULT; ConfigurationProviderImpl cp = new ConfigurationProviderImpl(); - Boolean ret = load(cp, rsrc, name, m, explicit); + Boolean ret = load(cp, rsrc, name, m, null, explicit); if (ret != null) return (ret.booleanValue()) ? cp : null; if (explicit) @@ -346,7 +342,8 @@ public class PersistenceProductDerivation // persistence.xml does not exist; just load map PersistenceUnitInfoImpl pinfo = new PersistenceUnitInfoImpl(); pinfo.fromUserProperties(m); - if (!isOpenJPAPersistenceProvider(pinfo)) { + if (!isOpenJPAPersistenceProvider(pinfo, null)) { + warnUnknownProvider(pinfo); return null; } cp.addProperties(pinfo.toOpenJPAProperties()); @@ -354,25 +351,27 @@ public class PersistenceProductDerivation } @Override - public ConfigurationProvider load(String rsrc, String anchor) throws IOException { + public ConfigurationProvider load(String rsrc, String anchor, + ClassLoader loader) + throws IOException { if (rsrc != null && !rsrc.endsWith(".xml")) return null; ConfigurationProviderImpl cp = new ConfigurationProviderImpl(); - if (load(cp, rsrc, anchor, null, true) == Boolean.TRUE) + if (load(cp, rsrc, anchor, null, loader, true) == Boolean.TRUE) return cp; return null; } @Override - public ConfigurationProvider load(File file, String anchor) throws IOException { + public ConfigurationProvider load(File file, String anchor) + throws IOException { if (!file.getName().endsWith(".xml")) return null; - ConfigurationParser parser = new ConfigurationParser(_loader, null); + ConfigurationParser parser = new ConfigurationParser(null); parser.parse(file); - List units = (List) parser.getResults(); - PersistenceUnitInfoImpl unit = findUnit(units, anchor); - return load(unit, null); + return load(findUnit((List) + parser.getResults(), anchor, null), null); } @Override @@ -381,8 +380,8 @@ public class PersistenceProductDerivation } @Override - public List getAnchorsInFile(File file) throws IOException { - ConfigurationParser parser = new ConfigurationParser(_loader, null); + public List getAnchorsInFile(File file) throws IOException { + ConfigurationParser parser = new ConfigurationParser(null); try { parser.parse(file); return getUnitNames(parser); @@ -398,7 +397,7 @@ public class PersistenceProductDerivation for (PersistenceUnitInfoImpl unit : units){ String provider = unit.getPersistenceProviderClassName(); // Only add the PU name if the provider it is ours or not specified. - if (provider == null || provider.indexOf("openjpa") != -1) { + if (provider == null || provider.equals(_providerImplName)) { names.add(unit.getPersistenceUnitName()); } else { // Should trace something, but logging isn't configured yet. @@ -409,11 +408,13 @@ public class PersistenceProductDerivation } @Override - public List getAnchorsInResource(String resource) throws Exception { - ConfigurationParser parser = new ConfigurationParser(_loader, null); + public List getAnchorsInResource(String resource) throws Exception { + ConfigurationParser parser = new ConfigurationParser(null); try { - List results = new ArrayList(); - List urls = getResourceURLs(resource); + List results = new ArrayList(); + ClassLoader loader = AccessController.doPrivileged( + J2DoPrivHelper.getContextClassLoaderAction()); + List urls = getResourceURLs(resource, loader); if (urls != null) { for (URL url : urls) { parser.parse(url); @@ -428,7 +429,7 @@ public class PersistenceProductDerivation } @Override - public ConfigurationProvider loadGlobals() + public ConfigurationProvider loadGlobals(ClassLoader loader) throws IOException { String[] prefixes = ProductDerivations.getConfigurationPrefixes(); String rsrc = null; @@ -450,52 +451,54 @@ public class PersistenceProductDerivation return null; ConfigurationProviderImpl cp = new ConfigurationProviderImpl(); - if (load(cp, rsrc, anchor, null, explicit) == Boolean.TRUE) + if (load(cp, rsrc, anchor, null, loader, explicit) == Boolean.TRUE) return cp; return null; } @Override - public ConfigurationProvider loadDefaults() + public ConfigurationProvider loadDefaults(ClassLoader loader) throws IOException { ConfigurationProviderImpl cp = new ConfigurationProviderImpl(); - if (load(cp, RSRC_DEFAULT, null, null, false) == Boolean.TRUE) + if (load(cp, RSRC_DEFAULT, null, null, loader, false) == Boolean.TRUE) return cp; return null; } - private void checkPuNameCollisions(){ + /** + * This method checks to see if the provided puName was + * detected in multiple resources. If a collision is detected, a warning + * will be logged and this method will return true. + *

    + */ + public boolean checkPuNameCollisions(Log logger,String puName){ + PUNameCollision p = _puNameCollisions.get(puName); + if (p != null){ + p.logCollision(logger); + return true; + } + return false; } - private List getResourceURLs(String rsrc) + private static List getResourceURLs(String rsrc, ClassLoader loader) throws IOException { Enumeration urls = null; try { - urls = AccessController.doPrivileged(J2DoPrivHelper.getResourcesAction(_loader, rsrc)); + urls = AccessController.doPrivileged(J2DoPrivHelper.getResourcesAction(loader, rsrc)); if (!urls.hasMoreElements()) { if (!rsrc.startsWith("META-INF")) - urls = AccessController.doPrivileged(J2DoPrivHelper.getResourcesAction(_loader, "META-INF/" + rsrc)); + urls = AccessController.doPrivileged(J2DoPrivHelper.getResourcesAction(loader, "META-INF/" + rsrc)); if (!urls.hasMoreElements()) return null; } } catch (PrivilegedActionException pae) { throw (IOException) pae.getException(); } - List result = new ArrayList(); - for (;urls.hasMoreElements();) { - URL url = urls.nextElement(); - if (!result.contains(url)) { - result.add(url); - } - } - return result; + + return Collections.list(urls); } /** - * The core load method to load the configuration resource. - * The class loader that loads the configuration resource is remembered by the provider - * and later {@link ConfigurationProvider#setInto(Configuration) set into} {@link Configuration}. - *
    * Looks through the resources at rsrc for a configuration * file that matches name (or an unnamed one if * name is null), and loads the XML in the @@ -505,21 +508,26 @@ public class PersistenceProductDerivation * @return {@link Boolean#TRUE} if the resource was loaded, null if it * does not exist, or {@link Boolean#FALSE} if it is not for OpenJPA */ - private Boolean load(ConfigurationProviderImpl cp, String rsrc, String name, Map m, boolean explicit) + private Boolean load(ConfigurationProviderImpl cp, String rsrc, + String name, Map m, ClassLoader loader, boolean explicit) throws IOException { - List urls = getResourceURLs(rsrc); + if (loader == null) + loader = AccessController.doPrivileged(J2DoPrivHelper.getContextClassLoaderAction()); + + List urls = getResourceURLs(rsrc, loader); if (urls == null || urls.size() == 0) return null; - ConfigurationParser parser = new ConfigurationParser(_loader, m); - PersistenceUnitInfoImpl pinfo = parseResources(parser, urls, name); + ConfigurationParser parser = new ConfigurationParser(m); + PersistenceUnitInfoImpl pinfo = parseResources(parser, urls, name, loader); if (pinfo == null) { if (!explicit) return Boolean.FALSE; throw new MissingResourceException(_loc.get("missing-xml-config", rsrc, String.valueOf(name)).getMessage(), getClass().getName(), rsrc); - } else if (!isOpenJPAPersistenceProvider(pinfo)) { + } else if (!isOpenJPAPersistenceProvider(pinfo, loader)) { if (!explicit) { + warnUnknownProvider(pinfo); return Boolean.FALSE; } throw new MissingResourceException(_loc.get("unknown-provider", @@ -532,7 +540,6 @@ public class PersistenceProductDerivation cp.addProperties(pinfo.toOpenJPAProperties()); cp.setSource(pinfo.getPersistenceXmlFileUrl().toString()); - return Boolean.TRUE; } @@ -542,70 +549,100 @@ public class PersistenceProductDerivation * no name given (preferring an unnamed OpenJPA unit to a named one). */ private PersistenceUnitInfoImpl parseResources(ConfigurationParser parser, - List urls, String name) + List urls, String name, ClassLoader loader) throws IOException { List pinfos = new ArrayList(); for (URL url : urls) { parser.parse(url); pinfos.addAll((List) parser.getResults()); - PersistenceUnitInfoImpl pu = null; - } - return findUnit(pinfos, name); + } + return findUnit(pinfos, name, loader); } /** - * Finds the unit with the given name in the given list of persistence unit infos. - * Ignores any persistence unit info that does not use OpenJPA as persistence provider. - * If the same unit name is found in multiple units, returns the first unit but - * records the rest as duplicates. + * Find the unit with the given name, or an OpenJPA unit if no name is + * given (preferring an unnamed OpenJPA unit to a named one). */ - private PersistenceUnitInfoImpl findUnit(List pinfos, String name) { - PUNameCollision _puNameCollisions = null; + private PersistenceUnitInfoImpl findUnit(List + pinfos, String name, ClassLoader loader) { + PersistenceUnitInfoImpl ojpa = null; PersistenceUnitInfoImpl result = null; for (PersistenceUnitInfoImpl pinfo : pinfos) { - if (!isOpenJPAPersistenceProvider(pinfo)) { - continue; - } - if (name == null || name.equals(pinfo.getPersistenceUnitName())) { - if (result == null) { - result = pinfo; - } else { - if (_puNameCollisions == null) { - _puNameCollisions = new PUNameCollision(name, result, pinfo); - } else { - _puNameCollisions.addDuplicate(pinfo); - } - } - } + // found named unit? + if (name != null) { + if (name.equals(pinfo.getPersistenceUnitName())){ + if (result != null){ + this.addPuNameCollision(name, result.getPersistenceXmlFileUrl().toString(), + pinfo.getPersistenceXmlFileUrl().toString()); + + } else { + // Grab a ref to the pinfo that matches the name we're + // looking for. Keep going to look for duplicate pu names. + result = pinfo; + } + } + continue; + } + + if (isOpenJPAPersistenceProvider(pinfo, loader)) { + // if no name given and found unnamed unit, return it. + // otherwise record as default unit unless we find a better match later + if (StringUtils.isEmpty(pinfo.getPersistenceUnitName())) + return pinfo; + if (ojpa == null) + ojpa = pinfo; + } } - if (_puNameCollisions != null) { - _puNameCollisions.logCollision(); + if(result!=null){ + return result; } - return result; + return ojpa; } /** - * Affirms if the given provider is recognized as an OpenJPA provider. - * An empty string or a name containing "openjpa" returns true. + * Return whether the given persistence unit uses an OpenJPA provider. */ - private boolean isOpenJPAPersistenceProvider(PersistenceUnitInfo pinfo) { - String provider = pinfo.getPersistenceProviderClassName(); - if (StringUtils.isEmpty(provider) || "void".equals(provider) || provider.indexOf("openjpa") != -1) + private static boolean isOpenJPAPersistenceProvider(PersistenceUnitInfo pinfo, ClassLoader loader) { + String provider = pinfo.getPersistenceProviderClassName(); + if (StringUtils.isEmpty(provider) || PersistenceProviderImpl.class.getName().equals(provider)) return true; - log(_loc.get("unrecognized-provider", provider).getMessage()); + if (loader == null) + loader = AccessController.doPrivileged(J2DoPrivHelper.getContextClassLoaderAction()); + try { + if (PersistenceProviderImpl.class.isAssignableFrom(Class.forName(provider, false, loader))) + return true; + } catch (Throwable t) { + log(_loc.get("unloadable-provider", provider, t).getMessage()); + return false; + } return false; } + /** + * Warn the user that we could only find an unrecognized persistence + * provider. + */ + private static void warnUnknownProvider(PersistenceUnitInfo pinfo) { + log(_loc.get("unrecognized-provider", pinfo.getPersistenceProviderClassName()).getMessage()); + } /** - * Log a message on the console because no logging mechanism has been configured yet. + * Log a message. */ private static void log(String msg) { // at this point logging isn't configured yet - System.err.println("WARN: " + msg); + System.err.println(msg); } + private void addPuNameCollision(String puName, String file1, String file2){ + PUNameCollision pun = _puNameCollisions.get(puName); + if (pun != null){ + pun.addCollision(file1, file2); + } else { + _puNameCollisions.put(puName, new PUNameCollision(puName, file1, file2)); + } + } /** * Custom configuration provider. @@ -616,7 +653,6 @@ public class PersistenceProductDerivation private String _source; public ConfigurationProviderImpl() { - super(); } public ConfigurationProviderImpl(Map props) { @@ -630,9 +666,6 @@ public class PersistenceProductDerivation _source = source; } - /** - * Sets the configuration. - */ @Override public void setInto(Configuration conf) { if (conf instanceof OpenJPAConfiguration) { @@ -661,17 +694,17 @@ public class PersistenceProductDerivation } super.setInto(conf, null); - // At this point user properties have been loaded into the configuration. - // Apply any modifications based off those. + // At this point user properties have been loaded into the configuration. Apply any modifications based off + // those. if (conf instanceof OpenJPAConfiguration) { OpenJPAConfiguration oconf = (OpenJPAConfiguration) conf; - // If the data cache is enabled, make sure we have a RemoteCommitProvider + // If the datacache is enabled, make sure we have a RemoteCommitProvider String dc = oconf.getDataCache(); String rcp = oconf.getRemoteCommitProvider(); - // If the data cache is set and is something other than false - if (!"false".equals(dc)) { + // If the datacache is set and is something other than false + if (dc != null && dc.equals("false") == false) { // If RCP is null or empty, set it to sjvm. - if (StringUtils.isEmpty(rcp)) { + if (rcp == null || (rcp != null && rcp.equals("") == false)) { oconf.setRemoteCommitProvider("sjvm"); } } @@ -704,6 +737,8 @@ public class PersistenceProductDerivation private static final String PERSISTENCE_XSD_1_0 = "persistence_1_0.xsd"; private static final String PERSISTENCE_XSD_2_0 = "persistence_2_0.xsd"; + private static final Localizer _loc = Localizer.forPackage + (ConfigurationParser.class); private final Map _map; private PersistenceUnitInfoImpl _info = null; @@ -712,15 +747,7 @@ public class PersistenceProductDerivation private String _schemaLocation; private boolean _excludeUnlistedSet = false; - /** - * Parse configuration information. - * - * @param loader Class Loader to load resources. Must not be null. - * @param - * @param map - */ - public ConfigurationParser(ClassLoader loader, Map map) { - super(loader); + public ConfigurationParser(Map map) { _map = map; setCaching(false); setValidating(true); @@ -739,7 +766,8 @@ public class PersistenceProductDerivation _persistenceVersion = vp.getVersion(); _schemaLocation = vp.getSchemaLocation(); } catch (Throwable t) { - log(_loc.get("version-check-error", _source.toString()).toString()); + log(_loc.get("version-check-error", + _source.toString()).toString()); } super.parse(url); } @@ -748,7 +776,8 @@ public class PersistenceProductDerivation public void parse(File file) throws IOException { try { - _source = AccessController.doPrivileged(J2DoPrivHelper.toURLAction(file)); + _source = AccessController.doPrivileged(J2DoPrivHelper + .toURLAction(file)); } catch (PrivilegedActionException pae) { throw (MalformedURLException) pae.getException(); } @@ -759,22 +788,11 @@ public class PersistenceProductDerivation _persistenceVersion = vp.getVersion(); _schemaLocation = vp.getSchemaLocation(); } catch (Throwable t) { - log(_loc.get("version-check-error", _source.toString()).toString()); + log(_loc.get("version-check-error", + _source.toString()).toString()); } super.parse(file); } - - boolean peek(String name, URL fileOrURL) { - XMLVersionParser vp = new XMLVersionParser("persistence"); - try { - vp.parse(fileOrURL); - _persistenceVersion = vp.getVersion(); - _schemaLocation = vp.getSchemaLocation(); - } catch (Throwable t) { - log(_loc.get("version-check-error", _source.toString()).toString()); - } - return vp.unitNames().contains(name); - } @Override protected Object getSchemaSource() { @@ -912,8 +930,9 @@ public class PersistenceProductDerivation return new BigDecimal(_info.getPersistenceXMLSchemaVersion()); } catch (Throwable t) { - log(_loc.get("invalid-version-attribute", _info.getPersistenceXMLSchemaVersion(), - VERSION_1_0).toString()); + log(_loc.get("invalid-version-attribute", + _info.getPersistenceXMLSchemaVersion(), + VERSION_1_0.toString()).toString()); } } // OpenJPA supports persistence files without a version attribute. @@ -926,40 +945,32 @@ public class PersistenceProductDerivation /** - * Holds the URLs of persistence configuration that contain the same unit name. + * This private class is used to hold onto information regarding + * PersistentUnit name collisions. */ - private static class PUNameCollision { - private final String _puName; - private final PersistenceUnitInfoImpl _original; - private final Set _duplicates; + private static class PUNameCollision{ + private String _puName; + private Set _resources; - PUNameCollision(String pu, PersistenceUnitInfoImpl original, PersistenceUnitInfoImpl duplicate) { - _puName = pu; - _original = original; - _duplicates = new LinkedHashSet(); - _duplicates.add(duplicate); + PUNameCollision(String puName, String file1, String file2) { + _resources = new LinkedHashSet(); + _resources.add(file1); + _resources.add(file2); + _puName=puName; } - void logCollision(){ - String duplicates = listDuplicates(); - if (_puName == null) { - log(_loc.get("dup-pu-unnamed", _original, duplicates).toString()); - } else { - log(_loc.get("dup-pu", _puName, _original, duplicates).toString()); - } + void logCollision(Log logger){ + if(logger.isWarnEnabled()){ + logger.warn(_loc.getFatal("dup-pu", new Object[]{_puName,_resources.toString(), + _resources.iterator().next()})); + } } - void addDuplicate(PersistenceUnitInfoImpl dup){ - _duplicates.add(dup); - } - - String listDuplicates() { - StringBuilder buf = new StringBuilder("\r\n"); - for (PersistenceUnitInfoImpl pu : _duplicates) { - buf.append(pu).append("\r\n"); - } - return buf.toString(); + void addCollision(String file1, String file2){ + _resources.add(file1); + _resources.add(file2); } + } } diff --git a/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/PersistenceProviderImpl.java b/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/PersistenceProviderImpl.java index d2a29b144..a73bb20ab 100644 --- a/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/PersistenceProviderImpl.java +++ b/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/PersistenceProviderImpl.java @@ -36,14 +36,12 @@ import org.apache.openjpa.conf.OpenJPAConfiguration; import org.apache.openjpa.conf.OpenJPAConfigurationImpl; import org.apache.openjpa.enhance.PCClassFileTransformer; import org.apache.openjpa.enhance.PCEnhancerAgent; -import org.apache.openjpa.enhance.RuntimeUnenhancedClassesModes; import org.apache.openjpa.kernel.Bootstrap; import org.apache.openjpa.kernel.BrokerFactory; import org.apache.openjpa.kernel.ConnectionRetainModes; 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.log.Log; import org.apache.openjpa.lib.util.Localizer; import org.apache.openjpa.meta.AbstractCFMetaDataFactory; @@ -51,10 +49,12 @@ import org.apache.openjpa.meta.MetaDataModes; import org.apache.openjpa.meta.MetaDataRepository; import org.apache.openjpa.persistence.osgi.BundleUtils; import org.apache.openjpa.persistence.validation.ValidationUtils; +import org.apache.openjpa.util.ClassResolver; /** - * Bootstrapping class that allows the creation of a stand-alone {@link EntityManager}. + * Bootstrapping class that allows the creation of a stand-alone + * {@link EntityManager}. * * @see javax.persistence.Persistence#createEntityManagerFactory(String,Map) * @published @@ -68,27 +68,19 @@ public class PersistenceProviderImpl private static final Localizer _loc = Localizer.forPackage(PersistenceProviderImpl.class); private Log _log; - /** * Loads the entity manager specified by name, applying - * the properties in given map m as overrides to the properties defined + * the properties in m as overrides to the properties defined * in the XML configuration file for name. If name * is null, this method loads the XML in the resource * identified by resource, and uses the first resource found * when doing this lookup, regardless of the name specified in the XML * resource or the name of the jar that the resource is contained in. - *
    - * This does not pool EntityManagersFactories. - * - * @param name name of the persistence unit - * @param resource name of the resource. Normally, META-INF/persistence.xml, but not necessarily. - * @param m a map of properties that overrides properties found in the resource. - * - * @return EntityManagerFactory or null if anything goes wrong during loading resources. + * This does no pooling of EntityManagersFactories. + * @return EntityManagerFactory or null */ public OpenJPAEntityManagerFactory createEntityManagerFactory(String name, String resource, Map m) { - PersistenceProductDerivation pd = new PersistenceProductDerivation(BundleUtils.runningUnderOSGi()); - ProductDerivations.load(resource, name); + PersistenceProductDerivation pd = new PersistenceProductDerivation(); try { Object poolValue = Configurations.removeProperty(EMF_POOL, m); ConfigurationProvider cp = pd.load(resource, name, m); @@ -96,9 +88,10 @@ public class PersistenceProviderImpl return null; } - BrokerFactory factory = getBrokerFactory(cp, poolValue); + BrokerFactory factory = getBrokerFactory(cp, poolValue, BundleUtils.getBundleClassLoader()); OpenJPAConfiguration conf = factory.getConfiguration(); - _log = conf.getLog(OpenJPAConfiguration.LOG_RUNTIME); + _log = conf.getLog(OpenJPAConfiguration.LOG_RUNTIME); + pd.checkPuNameCollisions(_log,name); // add enhancer loadAgent(factory); @@ -137,11 +130,12 @@ public class PersistenceProviderImpl } } - private BrokerFactory getBrokerFactory(ConfigurationProvider cp, Object poolValue) { + private BrokerFactory getBrokerFactory(ConfigurationProvider cp, + Object poolValue, ClassLoader loader) { // handle "true" and "false" if (poolValue instanceof String && ("true".equalsIgnoreCase((String) poolValue) - || "false".equalsIgnoreCase((String) poolValue))) + || "false".equalsIgnoreCase((String) poolValue))) poolValue = Boolean.valueOf((String) poolValue); if (poolValue != null && !(poolValue instanceof Boolean)) { @@ -149,11 +143,10 @@ public class PersistenceProviderImpl throw new IllegalArgumentException(poolValue.toString()); } - if (poolValue == null || !((Boolean) poolValue).booleanValue()) { - return Bootstrap.newBrokerFactory(cp); - } else { - return Bootstrap.getBrokerFactory(cp); - } + if (poolValue == null || !((Boolean) poolValue).booleanValue()) + return Bootstrap.newBrokerFactory(cp, loader); + else + return Bootstrap.getBrokerFactory(cp, loader); } public OpenJPAEntityManagerFactory createEntityManagerFactory(String name, Map m) { @@ -161,7 +154,7 @@ public class PersistenceProviderImpl } public OpenJPAEntityManagerFactory createContainerEntityManagerFactory(PersistenceUnitInfo pui, Map m) { - PersistenceProductDerivation pd = new PersistenceProductDerivation(BundleUtils.runningUnderOSGi()); + PersistenceProductDerivation pd = new PersistenceProductDerivation(); try { Object poolValue = Configurations.removeProperty(EMF_POOL, m); ConfigurationProvider cp = pd.load(pui, m); @@ -179,14 +172,20 @@ public class PersistenceProviderImpl transformerException = e; } - // if the BrokerImpl hasn't been specified, switch to the non-finalizing one, - // since anything claiming to be a container should be doing proper resource management. + // if the BrokerImpl hasn't been specified, switch to the + // non-finalizing one, since anything claiming to be a container + // should be doing proper resource management. if (!Configurations.containsProperty(BrokerValue.KEY, cp.getProperties())) { cp.addProperty("openjpa." + BrokerValue.KEY, getDefaultBrokerAlias()); } - BrokerFactory factory = getBrokerFactory(cp, poolValue); - + // OPENJPA-1491 If running under OSGi, use the Bundle's ClassLoader instead of the application one + BrokerFactory factory; + if (BundleUtils.runningUnderOSGi()) { + factory = getBrokerFactory(cp, poolValue, BundleUtils.getBundleClassLoader()); + } else { + factory = getBrokerFactory(cp, poolValue, pui.getClassLoader()); + } OpenJPAConfiguration conf = factory.getConfiguration(); setPersistenceEnvironmentInfo(conf, pui); @@ -272,34 +271,44 @@ public class PersistenceProviderImpl final ClassLoader tmpLoader, OpenJPAConfiguration conf) { cp.setInto(conf); // use the temporary loader for everything - conf.addClassLoader(tmpLoader); + conf.setClassResolver(new ClassResolver() { + public ClassLoader getClassLoader(Class context, ClassLoader env) { + return tmpLoader; + } + }); conf.setReadOnly(Configuration.INIT_STATE_FREEZING); MetaDataRepository repos = conf.getMetaDataRepositoryInstance(); repos.setResolve(MetaDataModes.MODE_MAPPING, false); - _trans = new PCClassFileTransformer(repos, Configurations.parseProperties(props), tmpLoader); + _trans = new PCClassFileTransformer(repos, + Configurations.parseProperties(props), tmpLoader); } public byte[] transform(ClassLoader cl, String name, - Class previousVersion, ProtectionDomain pd, byte[] bytes) + Class previousVersion, ProtectionDomain pd, byte[] bytes) throws IllegalClassFormatException { return _trans.transform(cl, name, previousVersion, pd, bytes); } } /** - * Loads the PCEnhancerAgent. + * This private worker method will attempt load the PCEnhancerAgent. */ private void loadAgent(BrokerFactory factory) { OpenJPAConfiguration conf = factory.getConfiguration(); - if (conf.getRuntimeUnenhancedClassesConstant() == RuntimeUnenhancedClassesModes.SUPPORTED - && conf.getDynamicEnhancementAgent()) { - boolean res = PCEnhancerAgent.loadDynamicAgent(conf); - } + Log log = conf.getLog(OpenJPAConfiguration.LOG_RUNTIME); + + if (conf.getDynamicEnhancementAgent() == true) { + boolean res = PCEnhancerAgent.loadDynamicAgent(log); + if (log.isInfoEnabled() && res == true ){ + log.info(_loc.get("dynamic-agent")); + } + } } /** - * Sets up the proper LifecycleEventManager type based on if the javax.validation APIs are + * This private worker method will attempt to setup the proper + * LifecycleEventManager type based on if the javax.validation APIs are * available and a ValidatorImpl is required by the configuration. * @param log * @param conf @@ -309,7 +318,8 @@ public class PersistenceProviderImpl OpenJPAConfiguration conf = factory.getConfiguration(); Log log = conf.getLog(OpenJPAConfiguration.LOG_RUNTIME); - if ((ValidationUtils.setupValidation(conf) == true) && log.isInfoEnabled()) { + if ((ValidationUtils.setupValidation(conf) == true) && + log.isInfoEnabled()) { log.info(_loc.get("vlem-creation-info")); } } diff --git a/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/PersistenceUnitInfoImpl.java b/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/PersistenceUnitInfoImpl.java index b7b8efc5d..91f7ce05e 100644 --- a/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/PersistenceUnitInfoImpl.java +++ b/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/PersistenceUnitInfoImpl.java @@ -62,12 +62,14 @@ public class PersistenceUnitInfoImpl public static final String PERSISTENCE_VERSION = "PersistenceVersion"; - private static final Localizer s_loc = Localizer.forPackage(PersistenceUnitInfoImpl.class); + private static final Localizer s_loc = Localizer.forPackage + (PersistenceUnitInfoImpl.class); private String _name; private final HashMap _props = new HashMap(); - private PersistenceUnitTransactionType _transType = PersistenceUnitTransactionType.RESOURCE_LOCAL; - private ClassLoader _loader; + private PersistenceUnitTransactionType _transType = + PersistenceUnitTransactionType.RESOURCE_LOCAL; + private String _providerClassName; private List _mappingFileNames; private List _entityClassNames; @@ -96,11 +98,8 @@ public class PersistenceUnitInfoImpl // - an application client jar file private URL _root; - public PersistenceUnitInfoImpl() { - } - public ClassLoader getClassLoader() { - return _loader; + return null; } public ClassLoader getNewTempClassLoader() { @@ -571,8 +570,4 @@ public class PersistenceUnitInfoImpl public void setSharedCacheMode(SharedCacheMode mode) { _sharedCacheMode = mode; } - - public String toString() { - return getPersistenceXmlFileUrl().toString() + '#' + getPersistenceUnitName(); - } } diff --git a/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/StoreCacheImpl.java b/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/StoreCacheImpl.java index 72ece43f7..44a3a2fd8 100644 --- a/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/StoreCacheImpl.java +++ b/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/StoreCacheImpl.java @@ -141,7 +141,7 @@ public class StoreCacheImpl */ private ClassMetaData getMetaData(Class cls) { try { - return _repos.getMetaData(cls, true); + return _repos.getMetaData(cls, null, true); } catch (RuntimeException re) { throw PersistenceExceptions.toPersistenceException(re); } diff --git a/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/XMLPersistenceMetaDataParser.java b/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/XMLPersistenceMetaDataParser.java index 37c6df85a..fac0f0325 100644 --- a/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/XMLPersistenceMetaDataParser.java +++ b/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/XMLPersistenceMetaDataParser.java @@ -116,7 +116,8 @@ public class XMLPersistenceMetaDataParser SEQUENCE_GEN_SCHEMA } - private static final Map _elems = new HashMap(); + private static final Map _elems = + new HashMap(); // Map for storing deferred metadata which needs to be populated // after embeddables are loaded. @@ -184,12 +185,13 @@ public class XMLPersistenceMetaDataParser _elems.put("map-key-class", MAP_KEY_CLASS); } - private static final Localizer _loc = Localizer.forPackage(XMLPersistenceMetaDataParser.class); + private static final Localizer _loc = Localizer.forPackage + (XMLPersistenceMetaDataParser.class); private final OpenJPAConfiguration _conf; private MetaDataRepository _repos = null; private AnnotationPersistenceMetaDataParser _parser = null; -// private ClassLoader _envLoader = null; + private ClassLoader _envLoader = null; private int _mode = MODE_NONE; private boolean _override = false; @@ -222,7 +224,6 @@ public class XMLPersistenceMetaDataParser * Constructor; supply configuration. */ public XMLPersistenceMetaDataParser(OpenJPAConfiguration conf) { - super(conf.getClassLoader()); _conf = conf; setValidating(true); setLog(conf.getLog(OpenJPAConfiguration.LOG_METADATA)); @@ -279,23 +280,31 @@ public class XMLPersistenceMetaDataParser if (repos != null && (repos.getValidate() & MetaDataRepository.VALIDATE_RUNTIME) != 0) setParseComments(false); + + if (repos != null) { + // Determine if the Thread Context Classloader needs to be temporally overridden to the Classloader + // that loaded the OpenJPA classes, to avoid a potential deadlock issue with the way Xerces + // handles parsers and classloaders. + this.setOverrideContextClassloader(repos.getConfiguration().getCompatibilityInstance(). + getOverrideContextClassloader()); + } } /** * Return the environmental class loader to pass on to parsed * metadata instances. */ -// public ClassLoader getEnvClassLoader() { -// return _envLoader; -// } + public ClassLoader getEnvClassLoader() { + return _envLoader; + } /** * Set the environmental class loader to pass on to parsed * metadata instances. */ -// public void setEnvClassLoader(ClassLoader loader) { -// _envLoader = loader; -// } + public void setEnvClassLoader(ClassLoader loader) { + _envLoader = loader; + } /** * Whether to allow later parses of mapping information to override @@ -374,7 +383,8 @@ public class XMLPersistenceMetaDataParser } catch (Throwable t) { Log log = getLog(); if (log.isInfoEnabled()) - log.trace(_loc.get("version-check-error", file.toString())); + log.trace(_loc.get("version-check-error", + file.toString())); } super.parse(file); } @@ -872,7 +882,7 @@ public class XMLPersistenceMetaDataParser && ((isMetaDataMode() && (meta.getSourceMode() & MODE_META) != 0) || (isMappingMode() && (meta.getSourceMode() & MODE_MAPPING) != 0))) { - if (isDuplicateClass(meta)) { + if(isDuplicateClass(meta)) { if (log.isWarnEnabled()) { log.warn(_loc.get("dup-metadata", _cls, getSourceName())); } @@ -901,6 +911,7 @@ public class XMLPersistenceMetaDataParser fmds[i].setExplicit(true); } } + meta.setEnvClassLoader(_envLoader); meta.setSourceMode(MODE_NONE); // parse annotations first so XML overrides them diff --git a/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/XMLPersistenceMetaDataSerializer.java b/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/XMLPersistenceMetaDataSerializer.java index 1f76ce786..369dd0e7c 100644 --- a/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/XMLPersistenceMetaDataSerializer.java +++ b/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/XMLPersistenceMetaDataSerializer.java @@ -960,7 +960,7 @@ public class XMLPersistenceMetaDataSerializer ClassMetaData meta = fmd.getEmbeddedMetaData(); ClassMetaData owner = getConfiguration(). getMetaDataRepositoryInstance().getMetaData - (meta.getDescribedType(), true); + (meta.getDescribedType(), meta.getEnvClassLoader(), true); FieldMetaData eorig; for (FieldMetaData efmd : meta.getFields()) { eorig = owner.getField(efmd.getName()); diff --git a/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/criteria/CriteriaExpressionBuilder.java b/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/criteria/CriteriaExpressionBuilder.java index 6a75df09e..b4e250460 100644 --- a/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/criteria/CriteriaExpressionBuilder.java +++ b/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/criteria/CriteriaExpressionBuilder.java @@ -92,7 +92,7 @@ class CriteriaExpressionBuilder { for (Join join : root.getJoins()) { Class cls = join.getAttribute().getJavaType(); if (join.getAttribute().isAssociation()) { - ClassMetaData meta = metamodel.getRepository().getMetaData(cls, true); + ClassMetaData meta = metamodel.getRepository().getMetaData(cls, null, true); PersistenceType type = MetamodelImpl.getPersistenceType(meta); if (type == PersistenceType.ENTITY || type == PersistenceType.EMBEDDABLE) metas.add(meta); diff --git a/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/criteria/Expressions.java b/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/criteria/Expressions.java index 3fef613ed..6fd6d6833 100644 --- a/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/criteria/Expressions.java +++ b/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/criteria/Expressions.java @@ -1056,7 +1056,7 @@ class Expressions { ClassMetaData can = ((Types.Entity)q.getRoot().getModel()).meta; Class candidate = can.getDescribedType(); if (candidate.isAssignableFrom((Class)value)) { - lit.setMetaData(q.getMetamodel().getRepository().getMetaData((Class)value, true)); + lit.setMetaData(q.getMetamodel().getRepository().getMetaData((Class)value, null, true)); } else { lit.setMetaData(can); } diff --git a/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/meta/MetamodelImpl.java b/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/meta/MetamodelImpl.java index 4845b9c7c..d3cf673c8 100644 --- a/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/meta/MetamodelImpl.java +++ b/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/meta/MetamodelImpl.java @@ -82,9 +82,9 @@ public class MetamodelImpl implements Metamodel, Resolver { */ public MetamodelImpl(MetaDataRepository repos) { this.repos = repos; - Collection> classes = repos.loadPersistentTypes(true); + Collection> classes = repos.loadPersistentTypes(true, null); for (Class cls : classes) { - ClassMetaData meta = repos.getMetaData(cls, true); + ClassMetaData meta = repos.getMetaData(cls, null, true); PersistenceType type = getPersistenceType(meta); switch (type) { case ENTITY: @@ -221,7 +221,7 @@ public class MetamodelImpl implements Metamodel, Resolver { PersistenceType expected) { if (container.containsKey(cls)) return container.get(cls); - ClassMetaData meta = repos.getMetaData(cls, false); + ClassMetaData meta = repos.getMetaData(cls, null, false); if (meta != null) { instantiate(cls, meta, container, expected); } diff --git a/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/osgi/BundleDelegatingClassLoader.java b/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/osgi/BundleDelegatingClassLoader.java index 8e9885359..f3ffe970b 100644 --- a/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/osgi/BundleDelegatingClassLoader.java +++ b/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/osgi/BundleDelegatingClassLoader.java @@ -28,6 +28,7 @@ import org.osgi.framework.Bundle; * This is a simple ClassLoader that delegates to the Bundle * and is used by the PersistenceUnitInfo * + * @version $Rev$ $Date$ */ public class BundleDelegatingClassLoader extends ClassLoader { diff --git a/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/osgi/BundleUtils.java b/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/osgi/BundleUtils.java index e273bcd1a..1b8f37127 100644 --- a/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/osgi/BundleUtils.java +++ b/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/osgi/BundleUtils.java @@ -25,6 +25,7 @@ package org.apache.openjpa.persistence.osgi; * All routines MUST use reflection, so we don't have any hard-coded * runtime depends on OSGi classes for Java SE and EE users. * + * @version $Rev$ $Date$ */ public class BundleUtils { diff --git a/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/validation/ValidationUtils.java b/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/validation/ValidationUtils.java index e80d6b4e3..82cf5ce57 100644 --- a/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/validation/ValidationUtils.java +++ b/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/validation/ValidationUtils.java @@ -29,15 +29,17 @@ import org.apache.openjpa.validation.ValidationUnavailableException; /** * Validation helper routines and wrappers to remove runtime dependencies - * on the Bean Validation APIs or a implementation. + * on the Bean Valdiation APIs or a implementation. * * Note: This class should have no direct dependency on the javax.validation * packages, which should only occur in the ValidatorImpl class. * + * @version $Rev$ $Date$ */ public class ValidationUtils { - private static final Localizer _loc = Localizer.forPackage(ValidationUtils.class); + private static final Localizer _loc = Localizer.forPackage( + ValidationUtils.class); /** * Setup Validation support by determining if the javax.validation APIs @@ -48,76 +50,84 @@ public class ValidationUtils { * @throws If a Validator was required but could not be created. */ public static boolean setupValidation(OpenJPAConfiguration conf) { - if (conf.getValidationMode().equalsIgnoreCase(String.valueOf(ValidationMode.NONE))) { - return false; - } Log log = conf.getConfigurationLog(); boolean brc = false; // only try creating a Validator for JPA2 and if not mode==NONE - if (conf.getSpecificationInstance().getVersion() < 2) { if (log.isTraceEnabled()) { - log.trace("Bean Validator not created because JPA specification version is " + - conf.getSpecificationInstance()); + log.trace("Not creating a ValidatorImpl because " + + "this app is using the JPA 1.0 Spec"); } - return false; } + else if (!(String.valueOf(ValidationMode.NONE) + .equalsIgnoreCase(conf.getValidationMode()))) { // we'll use this in the exception handlers - boolean bValRequired = String.valueOf(ValidationMode.CALLBACK) - .equalsIgnoreCase(conf.getValidationMode()); - try { - // see if the javax.validation spec api is available - @SuppressWarnings("unused") - Class c = Class.forName("javax.validation.ValidationException"); - } catch (ClassNotFoundException e) { - if (bValRequired) { - // fatal error - ValidationMode requires a validator - Message msg = _loc.get("vlem-creation-error"); - log.error(msg, e); - // rethrow as a more descriptive/identifiable exception - throw new ValidationUnavailableException( - msg.getMessage(), - new RuntimeException(e), true); - } else { - // no optional validation provider, so just trace output + boolean bValRequired = String.valueOf(ValidationMode.CALLBACK) + .equalsIgnoreCase(conf.getValidationMode()); + try { + // see if the javax.validation spec api is available if (log.isTraceEnabled()) { - log.trace(_loc.get("vlem-creation-warn", - "No available javax.validation APIs")); + log.trace("Trying to load javax.validation APIs " + + "based on the ValidationMode=" + + conf.getValidationMode()); + } + @SuppressWarnings("unused") + Class c = Class.forName( + "javax.validation.ValidationException"); + } catch (ClassNotFoundException e) { + if (bValRequired) { + // fatal error - ValidationMode requires a validator + Message msg = _loc.get("vlem-creation-error"); + log.error(msg, e); + // rethrow as a more descriptive/identifiable exception + throw new ValidationUnavailableException( + msg.getMessage(), + new RuntimeException(e), true); + } else { + // no optional validation provider, so just trace output + if (log.isTraceEnabled()) { + log.trace(_loc.get("vlem-creation-warn", + "No available javax.validation APIs")); + } + return brc; } - return brc; } - } - // we have the javax.validation APIs - try { - // try loading a validation provider - ValidatorImpl validator = new ValidatorImpl(conf); - // set the Validator into the config - conf.setValidatorInstance(validator); - // update the LifecycleEventManager plugin to use it - conf.setLifecycleEventManager("validating"); - // all done, so return good rc if anyone cares - brc = true; - } catch (RuntimeException e) { - if (bValRequired) { - // fatal error - ValidationMode requires a validator - // rethrow as a WrappedException - Message msg = _loc.get("vlem-creation-error"); - log.error(msg, e); - // rethrow as a more descriptive/identifiable exception - throw new ValidationUnavailableException( - msg.getMessage(), - e, true); + // we have the javax.validation APIs + try { + // try loading a validation provider + ValidatorImpl validator = new ValidatorImpl(conf); + // set the Validator into the config + conf.setValidatorInstance(validator); + // update the LifecycleEventManager plugin to use it + conf.setLifecycleEventManager("validating"); + // all done, so return good rc if anyone cares + brc = true; + } catch (RuntimeException e) { + if (bValRequired) { + // fatal error - ValidationMode requires a validator + // rethrow as a WrappedException + Message msg = _loc.get("vlem-creation-error"); + log.error(msg, e); + // rethrow as a more descriptive/identifiable exception + throw new ValidationUnavailableException( + msg.getMessage(), + e, true); - } else { - // unexpected, but validation is optional, - // so just log it as a warning - String msg = e.getMessage(); - log.warn(_loc.get("vlem-creation-warn", msg == null ? e : msg )); - return brc; + } else { + // unexpected, but validation is optional, + // so just log it as a warning + String msg = e.getMessage(); + log.warn(_loc.get("vlem-creation-warn", msg == null ? e : msg )); + return brc; + } + } + } else { + if (log.isTraceEnabled()) { + log.trace("Not creating a ValidatorImpl because " + + "ValidationMode=" + conf.getValidationMode()); } } - return brc; } diff --git a/openjpa-persistence/src/main/resources/org/apache/openjpa/persistence/localizer.properties b/openjpa-persistence/src/main/resources/org/apache/openjpa/persistence/localizer.properties index c44cd508b..a28363630 100644 --- a/openjpa-persistence/src/main/resources/org/apache/openjpa/persistence/localizer.properties +++ b/openjpa-persistence/src/main/resources/org/apache/openjpa/persistence/localizer.properties @@ -186,10 +186,9 @@ unwrap-em-invalid: EntityManager can not be unwrapped to an instance of "{0}". unwrap-query-invalid: Query can not be unwrapped to an instance of "{0}". invalid_entity_argument: {0} can not be invoked on "{1}". This entity is either \ detached or not persistent or null. -dup-pu: Multiple persistence units named "{0}" were found. \ - The first persistence unit at "{1}" being used. The duplicate units are {2} -dup-pu-unnamed: Multiple persistence units were found while looking for unnamed unit. \ - The first persistence unit at "{0}" being used. The duplicate units are {1} +dup-pu: The persistence unit "{0}" was found multiple times in the following \ + resources "{1}", but persistence unit names should be unique. The first \ + persistence unit matching the provided name in "{2}" is being used. bad-lock-level: Invalid lock mode/level. Valid values are \ "none"(0), "read"(10), "optimistic"(15), "write"(20), \ "optimistic-force-increment"(25), \ diff --git a/openjpa-persistence/src/test/java/org/apache/openjpa/persistence/TestPersistenceProductDerivation.java b/openjpa-persistence/src/test/java/org/apache/openjpa/persistence/TestPersistenceProductDerivation.java index ad6031a1b..4d81080aa 100644 --- a/openjpa-persistence/src/test/java/org/apache/openjpa/persistence/TestPersistenceProductDerivation.java +++ b/openjpa-persistence/src/test/java/org/apache/openjpa/persistence/TestPersistenceProductDerivation.java @@ -123,9 +123,9 @@ public class TestPersistenceProductDerivation extends TestCase { ConfigurationProvider provider = ppd.load( PersistenceProductDerivation.RSRC_DEFAULT, - "encryption_plugin_pu"); + "encryption_plugin_pu", loader); provider.setInto(conf); - EncryptionProvider ep = conf.getEncryptionProviderInstance(); + EncryptionProvider ep = conf.getEncryptionProvider(); assertNotNull(ep); // Cast to test impl TestEncryptionProvider tep = (TestEncryptionProvider) ep; @@ -146,10 +146,10 @@ public class TestPersistenceProductDerivation extends TestCase { ConfigurationProvider provider = ppd.load( PersistenceProductDerivation.RSRC_DEFAULT, - "encryption_plugin_default_pu"); + "encryption_plugin_default_pu", loader); provider.setInto(conf); - assertNull(conf.getEncryptionProviderInstance()); + assertNull(conf.getEncryptionProvider()); } /* @@ -158,8 +158,7 @@ public class TestPersistenceProductDerivation extends TestCase { */ public void testJPA1ExcludeUnlistedClasses() throws Exception { PersistenceProductDerivation.ConfigurationParser cp = - new PersistenceProductDerivation.ConfigurationParser(this.getClass().getClassLoader(), - new HashMap()); + new PersistenceProductDerivation.ConfigurationParser(new HashMap()); List urls = getResourceURL(PersistenceProductDerivation.RSRC_DEFAULT); assertNotNull(urls); @@ -203,8 +202,7 @@ public class TestPersistenceProductDerivation extends TestCase { */ public void testExcludeUnlistedClasses() throws Exception { PersistenceProductDerivation.ConfigurationParser cp = - new PersistenceProductDerivation.ConfigurationParser(this.getClass().getClassLoader(), - new HashMap()); + new PersistenceProductDerivation.ConfigurationParser(new HashMap()); List urls = getResourceURL("META-INF/persistence-2_0.xml"); assertNotNull(urls); diff --git a/openjpa-slice/src/main/java/org/apache/openjpa/slice/jdbc/DistributedJDBCBrokerFactory.java b/openjpa-slice/src/main/java/org/apache/openjpa/slice/jdbc/DistributedJDBCBrokerFactory.java index 15ea640fc..1185d875d 100644 --- a/openjpa-slice/src/main/java/org/apache/openjpa/slice/jdbc/DistributedJDBCBrokerFactory.java +++ b/openjpa-slice/src/main/java/org/apache/openjpa/slice/jdbc/DistributedJDBCBrokerFactory.java @@ -99,7 +99,8 @@ public class DistributedJDBCBrokerFactory extends JDBCBrokerFactory public Slice addSlice(String name, Map properties) { Slice slice = ((DistributedJDBCConfigurationImpl)getConfiguration()).addSlice(name, properties); - synchronizeMappings((JDBCConfiguration)slice.getConfiguration()); + ClassLoader loader = AccessController.doPrivileged(J2DoPrivHelper.getContextClassLoaderAction()); + synchronizeMappings(loader, (JDBCConfiguration)slice.getConfiguration()); Collection brokers = getOpenBrokers(); for (Broker broker : brokers) { ((DistributedBroker)broker).getDistributedStoreManager().addSlice(slice); @@ -117,10 +118,10 @@ public class DistributedJDBCBrokerFactory extends JDBCBrokerFactory return new DistributedBrokerImpl(); } - protected void synchronizeMappings() { + protected void synchronizeMappings(ClassLoader loader) { List slices = getConfiguration().getSlices(Slice.Status.ACTIVE); for (Slice slice : slices) { - synchronizeMappings((JDBCConfiguration) slice.getConfiguration()); + synchronizeMappings(loader, (JDBCConfiguration) slice.getConfiguration()); } } diff --git a/openjpa-slice/src/main/java/org/apache/openjpa/slice/jdbc/DistributedJDBCConfigurationImpl.java b/openjpa-slice/src/main/java/org/apache/openjpa/slice/jdbc/DistributedJDBCConfigurationImpl.java index c6629763d..ad9124a6c 100644 --- a/openjpa-slice/src/main/java/org/apache/openjpa/slice/jdbc/DistributedJDBCConfigurationImpl.java +++ b/openjpa-slice/src/main/java/org/apache/openjpa/slice/jdbc/DistributedJDBCConfigurationImpl.java @@ -79,10 +79,10 @@ public class DistributedJDBCConfigurationImpl extends JDBCConfigurationImpl protected BooleanValue lenientPlugin; protected StringValue masterPlugin; protected StringListValue namesPlugin; - public PluginValue distributionPolicyPlugin; - public PluginValue replicationPolicyPlugin; - public PluginValue queryTargetPolicyPlugin; - public PluginValue finderTargetPolicyPlugin; + public PluginValue distributionPolicyPlugin; + public PluginValue replicationPolicyPlugin; + public PluginValue queryTargetPolicyPlugin; + public PluginValue finderTargetPolicyPlugin; public StringListValue replicatedTypesPlugin; private ReplicatedTypeRepository _replicationRepos; @@ -101,22 +101,22 @@ public class DistributedJDBCConfigurationImpl extends JDBCConfigurationImpl false); // load globals brokerPlugin.setString(DistributedBrokerImpl.class.getName()); - distributionPolicyPlugin = addPlugin(DistributionPolicy.class, PREFIX_SLICE + "DistributionPolicy", true); + distributionPolicyPlugin = addPlugin(PREFIX_SLICE + "DistributionPolicy", true); distributionPolicyPlugin.setAlias("random", DistributionPolicy.Default.class.getName()); distributionPolicyPlugin.setDefault("random"); distributionPolicyPlugin.setString("random"); distributionPolicyPlugin.setDynamic(true); - replicationPolicyPlugin = addPlugin(ReplicationPolicy.class, PREFIX_SLICE + "ReplicationPolicy", true); + replicationPolicyPlugin = addPlugin(PREFIX_SLICE + "ReplicationPolicy", true); replicationPolicyPlugin.setAlias("all", ReplicationPolicy.Default.class.getName()); replicationPolicyPlugin.setDefault("all"); replicationPolicyPlugin.setString("all"); replicationPolicyPlugin.setDynamic(true); - queryTargetPolicyPlugin = addPlugin(QueryTargetPolicy.class, PREFIX_SLICE + "QueryTargetPolicy", true); + queryTargetPolicyPlugin = addPlugin(PREFIX_SLICE + "QueryTargetPolicy", true); queryTargetPolicyPlugin.setDynamic(true); - finderTargetPolicyPlugin = addPlugin(FinderTargetPolicy.class, PREFIX_SLICE + "FinderTargetPolicy", true); + finderTargetPolicyPlugin = addPlugin(PREFIX_SLICE + "FinderTargetPolicy", true); finderTargetPolicyPlugin.setDynamic(true); replicatedTypesPlugin = new StringListValue(PREFIX_SLICE + "ReplicatedTypes"); @@ -212,14 +212,16 @@ public class DistributedJDBCConfigurationImpl extends JDBCConfigurationImpl public DistributionPolicy getDistributionPolicyInstance() { if (distributionPolicyPlugin.get() == null) { - distributionPolicyPlugin.instantiate(this, true); + distributionPolicyPlugin.instantiate(DistributionPolicy.class, + this, true); } return (DistributionPolicy) distributionPolicyPlugin.get(); } public String getDistributionPolicy() { if (distributionPolicyPlugin.get() == null) { - distributionPolicyPlugin.instantiate(this, true); + distributionPolicyPlugin.instantiate(DistributionPolicy.class, + this, true); } return distributionPolicyPlugin.getString(); } @@ -234,14 +236,16 @@ public class DistributedJDBCConfigurationImpl extends JDBCConfigurationImpl public ReplicationPolicy getReplicationPolicyInstance() { if (replicationPolicyPlugin.get() == null) { - replicationPolicyPlugin.instantiate(this, true); + replicationPolicyPlugin.instantiate(ReplicationPolicy.class, + this, true); } - return replicationPolicyPlugin.get(); + return (ReplicationPolicy) replicationPolicyPlugin.get(); } public String getReplicationPolicy() { if (replicationPolicyPlugin.get() == null) { - replicationPolicyPlugin.instantiate(this, true); + replicationPolicyPlugin.instantiate(ReplicationPolicy.class, + this, true); } return replicationPolicyPlugin.getString(); } @@ -256,14 +260,16 @@ public class DistributedJDBCConfigurationImpl extends JDBCConfigurationImpl public QueryTargetPolicy getQueryTargetPolicyInstance() { if (queryTargetPolicyPlugin.get() == null) { - queryTargetPolicyPlugin.instantiate(this, true); + queryTargetPolicyPlugin.instantiate(ReplicationPolicy.class, + this, true); } - return queryTargetPolicyPlugin.get(); + return (QueryTargetPolicy) queryTargetPolicyPlugin.get(); } public String getQueryTargetPolicy() { if (queryTargetPolicyPlugin.get() == null) { - queryTargetPolicyPlugin.instantiate(this, true); + queryTargetPolicyPlugin.instantiate(QueryTargetPolicy.class, + this, true); } return queryTargetPolicyPlugin.getString(); } @@ -278,14 +284,16 @@ public class DistributedJDBCConfigurationImpl extends JDBCConfigurationImpl public FinderTargetPolicy getFinderTargetPolicyInstance() { if (finderTargetPolicyPlugin.get() == null) { - finderTargetPolicyPlugin.instantiate(this, true); + finderTargetPolicyPlugin.instantiate(ReplicationPolicy.class, + this, true); } - return finderTargetPolicyPlugin.get(); + return (FinderTargetPolicy) finderTargetPolicyPlugin.get(); } public String getFinderTargetPolicy() { if (finderTargetPolicyPlugin.get() == null) { - finderTargetPolicyPlugin.instantiate(this, true); + finderTargetPolicyPlugin.instantiate(FinderTargetPolicy.class, + this, true); } return finderTargetPolicyPlugin.getString(); } @@ -301,7 +309,8 @@ public class DistributedJDBCConfigurationImpl extends JDBCConfigurationImpl public DistributedDataSource getConnectionFactory() { if (virtualDataSource == null) { virtualDataSource = createDistributedDataStore(); - DataSourceFactory.installDBDictionary(getDBDictionaryInstance(), virtualDataSource, this, false); + DataSourceFactory.installDBDictionary( + getDBDictionaryInstance(), virtualDataSource, this, false); } return virtualDataSource; } @@ -652,7 +661,7 @@ public class DistributedJDBCConfigurationImpl extends JDBCConfigurationImpl return true; if (_nonreplicatedTypes.contains(cls)) return false; - ClassMetaData meta = repos.getMetaData(cls, false); + ClassMetaData meta = repos.getMetaData(cls, null, false); if (meta == null) { _nonreplicatedTypes.add(cls); return false; diff --git a/openjpa-slice/src/main/java/org/apache/openjpa/slice/jdbc/DistributedStoreQuery.java b/openjpa-slice/src/main/java/org/apache/openjpa/slice/jdbc/DistributedStoreQuery.java index 3aa5c3722..d27b8d328 100644 --- a/openjpa-slice/src/main/java/org/apache/openjpa/slice/jdbc/DistributedStoreQuery.java +++ b/openjpa-slice/src/main/java/org/apache/openjpa/slice/jdbc/DistributedStoreQuery.java @@ -175,7 +175,7 @@ class DistributedStoreQuery extends JDBCStoreQuery { result = new MergedResultObjectProvider(tmp); } if (hasRange) { - result = new RangeResultObjectProvider(result, + result = new RangeResultObjectProvider(result, ctx.getStartRange(), ctx.getEndRange()); } return result; diff --git a/openjpa-slice/src/test/java/org/apache/openjpa/slice/SingleEMFTestCase.java b/openjpa-slice/src/test/java/org/apache/openjpa/slice/SingleEMFTestCase.java index b181ceba6..7f895e26b 100644 --- a/openjpa-slice/src/test/java/org/apache/openjpa/slice/SingleEMFTestCase.java +++ b/openjpa-slice/src/test/java/org/apache/openjpa/slice/SingleEMFTestCase.java @@ -69,6 +69,8 @@ public abstract class SingleEMFTestCase } protected ClassMapping getMapping(String name) { - return (ClassMapping) emf.getConfiguration().getMetaDataRepositoryInstance().getMetaData(name, true); + return (ClassMapping) emf.getConfiguration() + .getMetaDataRepositoryInstance().getMetaData(name, + getClass().getClassLoader(), true); } } diff --git a/openjpa-xmlstore/src/main/java/org/apache/openjpa/xmlstore/XMLFileHandler.java b/openjpa-xmlstore/src/main/java/org/apache/openjpa/xmlstore/XMLFileHandler.java index c29e4a621..cc5a01771 100644 --- a/openjpa-xmlstore/src/main/java/org/apache/openjpa/xmlstore/XMLFileHandler.java +++ b/openjpa-xmlstore/src/main/java/org/apache/openjpa/xmlstore/XMLFileHandler.java @@ -360,7 +360,7 @@ public class XMLFileHandler { // get the metadata for the type we're reading String type = attrs.getValue("class"); ClassMetaData meta = _conf.getMetaDataRepositoryInstance(). - getMetaData(classForName(type), true); + getMetaData(classForName(type), null, true); // construct the oid object Object oid; @@ -578,8 +578,11 @@ public class XMLFileHandler { /** * Return the class for the specified name. */ - private Class classForName(String name) throws Exception { - return Class.forName(name, true, _conf.getClassLoader()); + private Class classForName(String name) + throws Exception { + ClassLoader loader = _conf.getClassResolverInstance(). + getClassLoader(getClass(), null); + return Class.forName(name, true, loader); } }