use of org.datanucleus.exceptions.ClassNotResolvedException in project datanucleus-api-jdo by datanucleus.
the class JDOPersistenceManagerFactory method processLifecycleListenersFromProperties.
/**
* Convenience method to extract lifecycle listeners that are specified by way of persistence properties.
* @param props Persistence props.
*/
protected void processLifecycleListenersFromProperties(Map props) {
if (props != null) {
// Process any lifecycle listeners defined in persistent properties
Iterator<Map.Entry> propsIter = props.entrySet().iterator();
while (propsIter.hasNext()) {
Map.Entry entry = propsIter.next();
String key = (String) entry.getKey();
if (key.startsWith(Constants.PROPERTY_INSTANCE_LIFECYCLE_LISTENER)) {
String listenerClsName = key.substring(45);
String listenerClasses = (String) entry.getValue();
ClassLoaderResolver clr = nucleusContext.getClassLoaderResolver(null);
Class listenerCls = null;
try {
listenerCls = clr.classForName(listenerClsName);
} catch (ClassNotResolvedException cnre) {
throw new JDOUserException(Localiser.msg("012022", listenerClsName));
}
InstanceLifecycleListener listener = null;
// Find method getInstance()
Method method = ClassUtils.getMethodForClass(listenerCls, "getInstance", null);
if (method != null) {
// Create instance via getInstance()
try {
listener = (InstanceLifecycleListener) method.invoke(null);
} catch (Exception e) {
throw new JDOUserException(Localiser.msg("012021", listenerClsName), e);
}
} else {
// Try default constructor
try {
listener = (InstanceLifecycleListener) listenerCls.newInstance();
} catch (Exception e) {
throw new JDOUserException(Localiser.msg("012020", listenerClsName), e);
}
}
Class[] classes = null;
if (!StringUtils.isWhitespace(listenerClasses)) {
String[] classNames = StringUtils.split(listenerClasses, ",");
classes = new Class[classNames.length];
for (int i = 0; i < classNames.length; i++) {
classes[i] = clr.classForName(classNames[i]);
}
}
addInstanceLifecycleListener(listener, classes);
}
}
}
}
use of org.datanucleus.exceptions.ClassNotResolvedException in project datanucleus-api-jdo by datanucleus.
the class JDOPersistenceManagerFactory method getManagedClasses.
/**
* Accessor for the classes that are managed (have metadata loaded).
* @return Collection of classes
*/
public Collection<Class> getManagedClasses() {
checkJDOPermission(JDOPermission.GET_METADATA);
MetaDataManager mmgr = nucleusContext.getMetaDataManager();
Collection<String> classNames = mmgr.getClassesWithMetaData();
Collection<Class> classes = new HashSet<Class>();
if (classNames != null) {
ClassLoaderResolver clr = nucleusContext.getClassLoaderResolver(null);
Iterator<String> iter = classNames.iterator();
while (iter.hasNext()) {
try {
Class cls = clr.classForName(iter.next());
classes.add(cls);
} catch (ClassNotResolvedException cnre) {
// Do nothing
}
}
}
return classes;
}
use of org.datanucleus.exceptions.ClassNotResolvedException in project datanucleus-core by datanucleus.
the class CreatorExpression method bind.
/**
* Method to bind the expression to the symbol table as appropriate.
* @param symtbl Symbol table
* @return The symbol for this expression
*/
public Symbol bind(SymbolTable symtbl) {
if (symtbl.hasSymbol(getId())) {
symbol = symtbl.getSymbol(getId());
} else {
try {
// Try to find this as a complete class name (e.g as used in "instanceof")
Class cls = symtbl.getSymbolResolver().resolveClass(getId());
symbol = new PropertySymbol(getId(), cls);
} catch (ClassNotResolvedException cnre) {
throw new NucleusUserException("CreatorExpression defined with class of " + getId() + " yet this class is not found");
}
}
return symbol;
}
use of org.datanucleus.exceptions.ClassNotResolvedException in project datanucleus-core by datanucleus.
the class PersistenceNucleusContextImpl method initialiseAutoStart.
/**
* Method to initialise the auto-start mechanism, loading up the classes
* from its store into memory so that we start from what is required to be loaded.
* @param clr The ClassLoaderResolver
* @throws DatastoreInitialisationException if an error occurs
*/
protected void initialiseAutoStart(ClassLoaderResolver clr) throws DatastoreInitialisationException {
String autoStartMechanism = config.getStringProperty(PropertyNames.PROPERTY_AUTOSTART_MECHANISM);
String mode = config.getStringProperty(PropertyNames.PROPERTY_AUTOSTART_MODE);
if ("Classes".equalsIgnoreCase(autoStartMechanism)) {
starter = new ClassesAutoStarter(storeMgr, clr);
} else if ("XML".equalsIgnoreCase(autoStartMechanism)) {
try {
starter = new XMLAutoStarter(storeMgr, clr);
} catch (MalformedURLException mue) {
NucleusLogger.PERSISTENCE.warn("Unable to create XML AutoStarter due to ", mue);
starter = null;
}
} else if ("MetaData".equalsIgnoreCase(autoStartMechanism)) {
starter = new MetaDataAutoStarter(storeMgr, clr);
} else {
// Fallback to the plugin mechanism
String autoStarterClassName = getPluginManager().getAttributeValueForExtension("org.datanucleus.autostart", "name", autoStartMechanism, "class-name");
if (autoStarterClassName != null) {
Class[] argsClass = new Class[] { ClassConstants.STORE_MANAGER, ClassConstants.CLASS_LOADER_RESOLVER };
Object[] args = new Object[] { storeMgr, clr };
try {
starter = (AutoStartMechanism) getPluginManager().createExecutableExtension("org.datanucleus.autostart", "name", autoStartMechanism, "class-name", argsClass, args);
} catch (Exception e) {
NucleusLogger.PERSISTENCE.error(StringUtils.getStringFromStackTrace(e));
}
}
}
if (starter == null) {
return;
}
if (mode.equalsIgnoreCase("None")) {
starter.setMode(org.datanucleus.store.autostart.AutoStartMechanism.Mode.NONE);
} else if (mode.equalsIgnoreCase("Checked")) {
starter.setMode(org.datanucleus.store.autostart.AutoStartMechanism.Mode.CHECKED);
} else if (mode.equalsIgnoreCase("Quiet")) {
starter.setMode(org.datanucleus.store.autostart.AutoStartMechanism.Mode.QUIET);
} else if (mode.equalsIgnoreCase("Ignored")) {
starter.setMode(org.datanucleus.store.autostart.AutoStartMechanism.Mode.IGNORED);
}
if (NucleusLogger.PERSISTENCE.isDebugEnabled()) {
NucleusLogger.PERSISTENCE.debug(Localiser.msg("034005", autoStartMechanism));
}
boolean illegalState = false;
try {
if (!starter.isOpen()) {
starter.open();
}
Collection existingData = starter.getAllClassData();
if (existingData != null && !existingData.isEmpty()) {
List classesNeedingAdding = new ArrayList();
Iterator existingDataIter = existingData.iterator();
while (existingDataIter.hasNext()) {
StoreData data = (StoreData) existingDataIter.next();
if (data.isFCO()) {
// Catch classes that don't exist (e.g in use by a different app)
Class classFound = null;
try {
classFound = clr.classForName(data.getName());
} catch (ClassNotResolvedException cnre) {
if (data.getInterfaceName() != null) {
try {
getImplementationCreator().newInstance(clr.classForName(data.getInterfaceName()), clr);
classFound = clr.classForName(data.getName());
} catch (ClassNotResolvedException cnre2) {
// Do nothing
}
}
// Thrown if class not found
}
if (classFound != null) {
NucleusLogger.PERSISTENCE.info(Localiser.msg("032003", data.getName()));
classesNeedingAdding.add(data.getName());
if (data.getMetaData() == null) {
// StoreData doesnt have its metadata set yet so load it
// This ensures that the MetaDataManager always knows about these classes
AbstractClassMetaData acmd = getMetaDataManager().getMetaDataForClass(classFound, clr);
if (acmd != null) {
data.setMetaData(acmd);
} else {
String msg = Localiser.msg("034004", data.getName());
if (starter.getMode() == AutoStartMechanism.Mode.CHECKED) {
NucleusLogger.PERSISTENCE.error(msg);
throw new DatastoreInitialisationException(msg);
} else if (starter.getMode() == AutoStartMechanism.Mode.IGNORED) {
NucleusLogger.PERSISTENCE.warn(msg);
} else if (starter.getMode() == AutoStartMechanism.Mode.QUIET) {
NucleusLogger.PERSISTENCE.warn(msg);
NucleusLogger.PERSISTENCE.warn(Localiser.msg("034001", data.getName()));
starter.deleteClass(data.getName());
}
}
}
} else {
String msg = Localiser.msg("034000", data.getName());
if (starter.getMode() == AutoStartMechanism.Mode.CHECKED) {
NucleusLogger.PERSISTENCE.error(msg);
throw new DatastoreInitialisationException(msg);
} else if (starter.getMode() == AutoStartMechanism.Mode.IGNORED) {
NucleusLogger.PERSISTENCE.warn(msg);
} else if (starter.getMode() == AutoStartMechanism.Mode.QUIET) {
NucleusLogger.PERSISTENCE.warn(msg);
NucleusLogger.PERSISTENCE.warn(Localiser.msg("034001", data.getName()));
starter.deleteClass(data.getName());
}
}
}
}
String[] classesToLoad = new String[classesNeedingAdding.size()];
Iterator classesNeedingAddingIter = classesNeedingAdding.iterator();
int n = 0;
while (classesNeedingAddingIter.hasNext()) {
classesToLoad[n++] = (String) classesNeedingAddingIter.next();
}
// Load the classes into the StoreManager
try {
storeMgr.manageClasses(clr, classesToLoad);
} catch (Exception e) {
// Exception while adding so some of the (referenced) classes dont exist
NucleusLogger.PERSISTENCE.warn(Localiser.msg("034002", e));
// if an exception happens while loading AutoStart data, them we disable it, since it was unable to load the data from AutoStart. The memory state of AutoStart does
// not represent the database, and if we don't disable it, we could think that the autostart store is empty, and we would try to insert new entries in
// the autostart store that are already in there
illegalState = true;
// TODO Go back and add classes one-by-one to eliminate the class(es) with the problem
}
}
} finally {
if (starter.isOpen()) {
starter.close();
}
if (illegalState) {
NucleusLogger.PERSISTENCE.warn(Localiser.msg("034003"));
starter = null;
}
if (NucleusLogger.PERSISTENCE.isDebugEnabled()) {
NucleusLogger.PERSISTENCE.debug(Localiser.msg("034006", autoStartMechanism));
}
}
}
use of org.datanucleus.exceptions.ClassNotResolvedException in project datanucleus-core by datanucleus.
the class MetaDataManagerImpl method loadPersistenceUnit.
/* (non-Javadoc)
* @see org.datanucleus.metadata.MetaDataManager#loadPersistenceUnit(org.datanucleus.metadata.PersistenceUnitMetaData, java.lang.ClassLoader)
*/
@Override
public FileMetaData[] loadPersistenceUnit(PersistenceUnitMetaData pumd, ClassLoader loader) {
if (!allowMetaDataLoad) {
return null;
}
boolean originatingLoadCall = false;
if (listenersLoadedMetaData == null && listeners != null) {
originatingLoadCall = true;
listenersLoadedMetaData = new ArrayList<AbstractClassMetaData>();
}
try {
if (originatingLoadCall) {
updateLock.lock();
}
if (NucleusLogger.METADATA.isDebugEnabled()) {
NucleusLogger.METADATA.debug(Localiser.msg("044007", pumd.getName()));
}
Properties puProps = pumd.getProperties();
if (puProps != null) {
// Apply any properties from this persistence unit to the metadata manager
if (puProps.containsKey(PropertyNames.PROPERTY_METADATA_XML_VALIDATE)) {
Boolean val = Boolean.valueOf((String) puProps.get(PropertyNames.PROPERTY_METADATA_XML_VALIDATE));
if (val != null) {
validateXML = val;
}
}
if (puProps.containsKey(PropertyNames.PROPERTY_METADATA_XML_NAMESPACE_AWARE)) {
Boolean val = Boolean.valueOf((String) puProps.get(PropertyNames.PROPERTY_METADATA_XML_NAMESPACE_AWARE));
if (val != null) {
supportXMLNamespaces = val;
}
}
}
ClassLoaderResolver clr = nucleusContext.getClassLoaderResolver(loader);
Set<Throwable> exceptions = new HashSet<>();
List<FileMetaData> fileMetaData = new ArrayList<>();
// Generate list of XML files
Set<String> mappingFileNames = new HashSet<>();
if (allowXML) {
if (nucleusContext.getApiName().equalsIgnoreCase("JPA")) {
// Default location for JPA
mappingFileNames.add("META-INF/orm.xml");
}
if (pumd.getMappingFiles() != null) {
// <mapping-file>
mappingFileNames.addAll(pumd.getMappingFiles());
}
if (// When in JDO mode grab any package.jdo
nucleusContext.getApiName().equalsIgnoreCase("JDO")) {
// <jar-file>
Set jarFileNames = pumd.getJarFiles();
if (jarFileNames != null) {
Iterator iter = jarFileNames.iterator();
while (iter.hasNext()) {
Object jarFile = iter.next();
if (jarFile instanceof String) {
String[] packageJdoFiles = ClassUtils.getPackageJdoFilesForJarFile((String) jarFile);
if (packageJdoFiles != null) {
for (String packageJdoFile : packageJdoFiles) {
mappingFileNames.add(packageJdoFile);
}
}
} else if (jarFile instanceof URL) {
String[] packageJdoFiles = ClassUtils.getPackageJdoFilesForJarFile((URL) jarFile);
if (packageJdoFiles != null) {
for (String packageJdoFile : packageJdoFiles) {
mappingFileNames.add(packageJdoFile);
}
}
} else if (jarFile instanceof URI) {
String[] packageJdoFiles = ClassUtils.getPackageJdoFilesForJarFile((URI) jarFile);
if (packageJdoFiles != null) {
for (String packageJdoFile : packageJdoFiles) {
mappingFileNames.add(packageJdoFile);
}
}
}
}
}
}
}
// Generate list of (possibly annotated) class names
Set<String> classNames = new HashSet<>();
if (allowAnnotations) {
if (pumd.getClassNames() != null) {
classNames.addAll(pumd.getClassNames());
}
// TODO Process pumd.getConverters
if (// TODO Why not when enhancing? document it
getNucleusContext() instanceof PersistenceNucleusContext) {
Set jarFileNames = pumd.getJarFiles();
if (jarFileNames != null) {
Iterator iter = jarFileNames.iterator();
while (iter.hasNext()) {
Object jarFile = iter.next();
if (jarFile instanceof String) {
String[] jarClassNames = ClassUtils.getClassNamesForJarFile((String) jarFile);
if (jarClassNames != null) {
for (String jarClassName : jarClassNames) {
classNames.add(jarClassName);
}
}
} else if (jarFile instanceof URL) {
String[] jarClassNames = ClassUtils.getClassNamesForJarFile((URL) jarFile);
if (jarClassNames != null) {
for (String jarClassName : jarClassNames) {
classNames.add(jarClassName);
}
}
} else if (jarFile instanceof URI) {
String[] jarClassNames = ClassUtils.getClassNamesForJarFile((URI) jarFile);
if (jarClassNames != null) {
for (String jarClassName : jarClassNames) {
classNames.add(jarClassName);
}
}
}
}
}
}
if (!pumd.getExcludeUnlistedClasses()) {
MetaDataScanner scanner = getScanner(clr);
if (scanner != null) {
Set<String> scannedClassNames = scanner.scanForPersistableClasses(pumd);
if (scannedClassNames != null) {
classNames.addAll(scannedClassNames);
}
} else {
// Classpath scan for other classes
try {
if (pumd.getRootURI() != null && pumd.getRootURI().getScheme().equals("file")) {
// File-based root so load all classes under the root URL of the persistence-unit
File rootDir = new File(pumd.getRootURI());
String[] scannedClassNames = ClassUtils.getClassNamesForDirectoryAndBelow(rootDir);
if (scannedClassNames != null) {
for (String scannedClassName : scannedClassNames) {
NucleusLogger.METADATA.debug(Localiser.msg("044026", scannedClassName, pumd.getName()));
classNames.add(scannedClassName);
}
}
}
} catch (IllegalArgumentException iae) {
NucleusLogger.METADATA.debug("Ignoring scan of classes for this persistence-unit since the URI root is " + pumd.getRootURI() + " and is not hierarchical");
// Ignore the scan for classes
}
}
}
}
if (allowXML && !mappingFileNames.isEmpty()) {
// Load XML metadata for all <mapping-file> specifications
for (String mappingFileName : mappingFileNames) {
try {
Enumeration files = clr.getResources(mappingFileName, Thread.currentThread().getContextClassLoader());
if (!files.hasMoreElements()) {
NucleusLogger.METADATA.debug("Not found any metadata mapping files for resource name " + mappingFileName + " in CLASSPATH");
} else {
while (files.hasMoreElements()) {
URL url = (URL) files.nextElement();
if (url != null && fileMetaDataByURLString.get(url.toString()) == null) {
FileMetaData filemd = parseFile(url);
if (filemd != null) {
// Register the file
registerFile(url.toString(), filemd, clr);
fileMetaData.add(filemd);
}
}
}
}
} catch (InvalidMetaDataException imde) {
// Error in the metadata for this file
NucleusLogger.METADATA.error(StringUtils.getStringFromStackTrace(imde));
exceptions.add(imde);
} catch (IOException ioe) {
NucleusLogger.METADATA.error(Localiser.msg("044027", pumd.getName(), mappingFileName, ioe.getMessage()), ioe);
}
}
}
if (allowAnnotations && !classNames.isEmpty()) {
// Load annotation metadata for all classes
for (String className : classNames) {
// Check for MetaData for this class (take precedence over annotations if they exist)
AbstractClassMetaData cmd = classMetaDataByClass.get(className);
if (cmd == null) {
// No MetaData so try annotations
try {
Class cls = clr.classForName(className);
FileMetaData filemd = loadAnnotationsForClass(cls, clr, true, false);
if (filemd != null) {
fileMetaData.add(filemd);
} else {
NucleusLogger.METADATA.debug("Class " + className + " was specified in persistence-unit (maybe by not putting exclude-unlisted-classes) " + pumd.getName() + " but not annotated, so ignoring");
}
} catch (ClassNotResolvedException e) {
// log and ignore this exception
NucleusLogger.METADATA.error(StringUtils.getStringFromStackTrace(e));
} catch (Throwable e) {
exceptions.add(e);
}
} else {
// We have MetaData, and any annotations will be merged in during the populate process
}
}
}
if (!exceptions.isEmpty()) {
throw new NucleusUserException(Localiser.msg("044023", pumd.getName()), exceptions.toArray(new Throwable[exceptions.size()]));
}
if (!fileMetaData.isEmpty()) {
// Populate/Initialise all loaded FileMetaData
initialiseFileMetaDataForUse(fileMetaData, clr);
}
// TODO Really need a Set of unpopulated/uninitialised metadata and continue til all done
for (AbstractClassMetaData cmd : classMetaDataByClass.values()) {
boolean populated = cmd.isPopulated();
if (!cmd.isPopulated()) {
populated = populateAbstractClassMetaData(cmd, clr, loader);
}
if (populated && !cmd.isInitialised()) {
initialiseAbstractClassMetaData(cmd, clr);
}
}
if (NucleusLogger.METADATA.isDebugEnabled()) {
NucleusLogger.METADATA.debug(Localiser.msg("044010"));
}
if (originatingLoadCall) {
processListenerLoadingCall();
}
return fileMetaData.toArray(new FileMetaData[fileMetaData.size()]);
} finally {
if (originatingLoadCall) {
updateLock.unlock();
}
}
}
Aggregations