Search in sources :

Example 11 with ClassNotResolvedException

use of org.datanucleus.exceptions.ClassNotResolvedException in project datanucleus-core by datanucleus.

the class ExecutionContextImpl method findObjectsById.

/**
 * Accessor for objects with the specified identities.
 * @param identities Ids of the object(s).
 * @param validate Whether to validate the object state
 * @return The Objects with these ids (same order)
 * @throws NucleusObjectNotFoundException if an object doesn't exist in the datastore
 */
public Object[] findObjectsById(Object[] identities, boolean validate) {
    if (identities == null) {
        return null;
    } else if (identities.length == 1) {
        return new Object[] { findObject(identities[0], validate, validate, null) };
    }
    for (int i = 0; i < identities.length; i++) {
        if (identities[i] == null) {
            throw new NucleusUserException(Localiser.msg("010044"));
        }
    }
    // Set the identities array
    Object[] ids = new Object[identities.length];
    for (int i = 0; i < identities.length; i++) {
        // Translate the identity if required
        if (identities[i] instanceof String) {
            IdentityStringTranslator idStringTranslator = getNucleusContext().getIdentityManager().getIdentityStringTranslator();
            if (idStringTranslator != null) {
                // DataNucleus extension to translate input identities into valid persistent identities.
                ids[i] = idStringTranslator.getIdentity(this, (String) identities[i]);
                continue;
            }
        }
        ids[i] = identities[i];
    }
    Map pcById = new HashMap(identities.length);
    List idsToFind = new ArrayList();
    ApiAdapter api = getApiAdapter();
    // Check the L1 cache
    for (int i = 0; i < ids.length; i++) {
        Object pc = getObjectFromLevel1Cache(ids[i]);
        if (pc != null) {
            if (ids[i] instanceof SCOID) {
                if (api.isPersistent(pc) && !api.isNew(pc) && !api.isDeleted(pc) && !api.isTransactional(pc)) {
                    // JDO [5.4.4] Can't return HOLLOW nondurable objects
                    throw new NucleusUserException(Localiser.msg("010005"));
                }
            }
            pcById.put(ids[i], pc);
        } else {
            idsToFind.add(ids[i]);
        }
    }
    if (!idsToFind.isEmpty() && l2CacheEnabled) {
        // Check the L2 cache for those not found
        Map pcsById = getObjectsFromLevel2Cache(idsToFind);
        if (!pcsById.isEmpty()) {
            // Found some so add to the values, and remove from the "toFind" list
            Iterator<Map.Entry> entryIter = pcsById.entrySet().iterator();
            while (entryIter.hasNext()) {
                Map.Entry entry = entryIter.next();
                pcById.put(entry.getKey(), entry.getValue());
                idsToFind.remove(entry.getKey());
            }
        }
    }
    boolean performValidationWhenCached = nucCtx.getConfiguration().getBooleanProperty(PropertyNames.PROPERTY_FIND_OBJECT_VALIDATE_WHEN_CACHED);
    List<ObjectProvider> opsToValidate = new ArrayList<>();
    if (validate) {
        if (performValidationWhenCached) {
            // Mark all ObjectProviders for validation (performed at end)
            Collection pcValues = pcById.values();
            for (Object pc : pcValues) {
                if (api.isTransactional(pc)) {
                    // This object is transactional, so no need to validate
                    continue;
                }
                // Mark this object for validation
                ObjectProvider op = findObjectProvider(pc);
                opsToValidate.add(op);
            }
        }
    }
    Object[] foundPcs = null;
    if (!idsToFind.isEmpty()) {
        // Try to find unresolved objects direct from the datastore if supported by the datastore (e.g ODBMS)
        foundPcs = getStoreManager().getPersistenceHandler().findObjects(this, idsToFind.toArray());
    }
    int foundPcIdx = 0;
    for (Object id : idsToFind) {
        // Id target class could change due to inheritance level
        Object idOrig = id;
        Object pc = foundPcs != null ? foundPcs[foundPcIdx++] : null;
        ObjectProvider op = null;
        if (pc != null) {
            // Object created by store plugin
            op = findObjectProvider(pc);
            putObjectIntoLevel1Cache(op);
        } else {
            // Object not found yet, so maybe class name is not correct inheritance level
            ClassDetailsForId details = getClassDetailsForId(id, null, validate);
            String className = details.className;
            id = details.id;
            if (details.pc != null) {
                // Found in cache from updated id
                pc = details.pc;
                op = findObjectProvider(pc);
                if (performValidationWhenCached && validate) {
                    if (!api.isTransactional(pc)) {
                        // Mark this object for validation
                        opsToValidate.add(op);
                    }
                }
            } else {
                // Still not found so create a Hollow instance with the supplied field values
                try {
                    Class pcClass = clr.classForName(className, (id instanceof DatastoreId) ? null : id.getClass().getClassLoader());
                    if (Modifier.isAbstract(pcClass.getModifiers())) {
                        // This class is abstract so impossible to have an instance of this type
                        throw new NucleusObjectNotFoundException(Localiser.msg("010027", IdentityUtils.getPersistableIdentityForId(id), className));
                    }
                    op = nucCtx.getObjectProviderFactory().newForHollow(this, pcClass, id);
                    pc = op.getObject();
                    if (!validate) {
                        // Mark the ObjectProvider as needing to validate this object before loading fields
                        op.markForInheritanceValidation();
                    }
                    // Cache it in case we have bidir relations
                    putObjectIntoLevel1Cache(op);
                } catch (ClassNotResolvedException e) {
                    NucleusLogger.PERSISTENCE.warn(Localiser.msg("010027", IdentityUtils.getPersistableIdentityForId(id)));
                    throw new NucleusUserException(Localiser.msg("010027", IdentityUtils.getPersistableIdentityForId(id)), e);
                }
                if (validate) {
                    // Mark this object for validation
                    opsToValidate.add(op);
                }
            }
        }
        // Put in map under input id, so we find it later
        pcById.put(idOrig, pc);
    }
    if (!opsToValidate.isEmpty()) {
        // Validate the objects that need it
        try {
            getStoreManager().getPersistenceHandler().locateObjects(opsToValidate.toArray(new ObjectProvider[opsToValidate.size()]));
        } catch (NucleusObjectNotFoundException nonfe) {
            NucleusObjectNotFoundException[] nonfes = (NucleusObjectNotFoundException[]) nonfe.getNestedExceptions();
            if (nonfes != null) {
                for (int i = 0; i < nonfes.length; i++) {
                    Object missingId = nonfes[i].getFailedObject();
                    removeObjectFromLevel1Cache(missingId);
                }
            }
            throw nonfe;
        }
    }
    Object[] objs = new Object[ids.length];
    for (int i = 0; i < ids.length; i++) {
        Object id = ids[i];
        objs[i] = pcById.get(id);
    }
    return objs;
}
Also used : IdentityStringTranslator(org.datanucleus.identity.IdentityStringTranslator) Entry(java.util.Map.Entry) ApiAdapter(org.datanucleus.api.ApiAdapter) ConcurrentReferenceHashMap(org.datanucleus.util.ConcurrentReferenceHashMap) HashMap(java.util.HashMap) DatastoreId(org.datanucleus.identity.DatastoreId) NucleusUserException(org.datanucleus.exceptions.NucleusUserException) ArrayList(java.util.ArrayList) SCOID(org.datanucleus.identity.SCOID) NucleusObjectNotFoundException(org.datanucleus.exceptions.NucleusObjectNotFoundException) ClassNotResolvedException(org.datanucleus.exceptions.ClassNotResolvedException) Entry(java.util.Map.Entry) Collection(java.util.Collection) List(java.util.List) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) ObjectProvider(org.datanucleus.state.ObjectProvider) ConcurrentReferenceHashMap(org.datanucleus.util.ConcurrentReferenceHashMap) Map(java.util.Map) HashMap(java.util.HashMap)

Example 12 with ClassNotResolvedException

use of org.datanucleus.exceptions.ClassNotResolvedException in project datanucleus-core by datanucleus.

the class ExecutionContextImpl method findObject.

/**
 * Accessor for an object given the object id. If validate is false, we return the object
 * if found in the cache, or otherwise a Hollow object with that id. If validate is true
 * we check with the datastore and return an object with the FetchPlan fields loaded.
 * TODO Would be nice, when using checkInheritance, to be able to specify the "id" is an instance of class X or subclass. See IdentityUtils where we have the min class
 * @param id Id of the object.
 * @param validate Whether to validate the object state
 * @param checkInheritance Whether look to the database to determine which class this object is.
 * @param objectClassName Class name for the object with this id (if known, optional)
 * @return The Object with this id
 * @throws NucleusObjectNotFoundException if the object doesn't exist in the datastore
 */
public Object findObject(Object id, boolean validate, boolean checkInheritance, String objectClassName) {
    if (id == null) {
        throw new NucleusUserException(Localiser.msg("010044"));
    }
    IdentityStringTranslator translator = getNucleusContext().getIdentityManager().getIdentityStringTranslator();
    if (translator != null && id instanceof String) {
        // DataNucleus extension to translate input identities into valid persistent identities.
        id = translator.getIdentity(this, (String) id);
    }
    ApiAdapter api = getApiAdapter();
    boolean fromCache = false;
    // try to find object in cache(s)
    Object pc = getObjectFromCache(id);
    ObjectProvider op = null;
    if (pc != null) {
        // Found in L1/L2 cache
        fromCache = true;
        if (id instanceof SCOID) {
            if (api.isPersistent(pc) && !api.isNew(pc) && !api.isDeleted(pc) && !api.isTransactional(pc)) {
                // JDO [5.4.4] Cant return HOLLOW nondurable objects
                throw new NucleusUserException(Localiser.msg("010005"));
            }
        }
        if (api.isTransactional(pc)) {
            // JDO [12.6.5] If there's already an object with the same id and it's transactional, return it
            return pc;
        }
        op = findObjectProvider(pc);
    } else {
        // Find it direct from the store if the store supports that
        pc = getStoreManager().getPersistenceHandler().findObject(this, id);
        if (pc != null) {
            op = findObjectProvider(pc);
            putObjectIntoLevel1Cache(op);
            putObjectIntoLevel2Cache(op, false);
        } else {
            // Object not found yet, so maybe class name is not correct inheritance level
            ClassDetailsForId details = getClassDetailsForId(id, objectClassName, checkInheritance);
            String className = details.className;
            id = details.id;
            if (details.pc != null) {
                // Found during inheritance check via the cache
                pc = details.pc;
                op = findObjectProvider(pc);
                fromCache = true;
            } else {
                // Still not found, so create a Hollow instance with supplied PK values if possible
                try {
                    Class pcClass = clr.classForName(className, (id instanceof DatastoreId) ? null : id.getClass().getClassLoader());
                    if (Modifier.isAbstract(pcClass.getModifiers())) {
                        // This class is abstract so impossible to have an instance of this type
                        throw new NucleusObjectNotFoundException(Localiser.msg("010027", IdentityUtils.getPersistableIdentityForId(id), className));
                    }
                    op = nucCtx.getObjectProviderFactory().newForHollow(this, pcClass, id);
                    pc = op.getObject();
                    if (!checkInheritance && !validate) {
                        // Mark the ObjectProvider as needing to validate this object before loading fields
                        op.markForInheritanceValidation();
                    }
                    // Cache the object in case we have bidirectional relations that would need to find this
                    putObjectIntoLevel1Cache(op);
                } catch (ClassNotResolvedException e) {
                    NucleusLogger.PERSISTENCE.warn(Localiser.msg("010027", IdentityUtils.getPersistableIdentityForId(id)));
                    throw new NucleusUserException(Localiser.msg("010027", IdentityUtils.getPersistableIdentityForId(id)), e);
                }
            }
        }
    }
    boolean performValidationWhenCached = nucCtx.getConfiguration().getBooleanProperty(PropertyNames.PROPERTY_FIND_OBJECT_VALIDATE_WHEN_CACHED);
    if (validate && (!fromCache || performValidationWhenCached)) {
        // loading any fetchplan fields that are needed in the process.
        if (!fromCache) {
            // Cache the object in case we have bidirectional relations that would need to find this
            putObjectIntoLevel1Cache(op);
        }
        try {
            op.validate();
            if (op.getObject() != pc) {
                // Underlying object was changed in the validation process. This can happen when the datastore
                // is responsible for managing object references and it no longer recognises the cached value.
                fromCache = false;
                pc = op.getObject();
                putObjectIntoLevel1Cache(op);
            }
        } catch (NucleusObjectNotFoundException onfe) {
            // Object doesn't exist, so remove from L1 cache
            removeObjectFromLevel1Cache(op.getInternalObjectId());
            throw onfe;
        }
    }
    if (!fromCache) {
        // Cache the object (update it if already present)
        putObjectIntoLevel2Cache(op, false);
    }
    return pc;
}
Also used : IdentityStringTranslator(org.datanucleus.identity.IdentityStringTranslator) ApiAdapter(org.datanucleus.api.ApiAdapter) DatastoreId(org.datanucleus.identity.DatastoreId) NucleusUserException(org.datanucleus.exceptions.NucleusUserException) SCOID(org.datanucleus.identity.SCOID) NucleusObjectNotFoundException(org.datanucleus.exceptions.NucleusObjectNotFoundException) ClassNotResolvedException(org.datanucleus.exceptions.ClassNotResolvedException) ObjectProvider(org.datanucleus.state.ObjectProvider)

Example 13 with ClassNotResolvedException

use of org.datanucleus.exceptions.ClassNotResolvedException in project datanucleus-core by datanucleus.

the class ExecutionContextImpl method findObject.

/**
 * Accessor for an object given the object id and a set of field values to apply to it.
 * This is intended for use where we have done a query and have the id from the results, and we want to
 * create the object, preferably using the cache, and then apply any field values to it.
 * @param id Id of the object.
 * @param fv Field values for the object (to copy in)
 * @param cls the type which the object is (optional). Used to instantiate the object
 * @param ignoreCache true if it must ignore the cache
 * @param checkInheritance Whether to check the inheritance on the id of the object
 * @return The Object
 */
public Object findObject(Object id, FieldValues fv, Class cls, boolean ignoreCache, boolean checkInheritance) {
    assertIsOpen();
    Object pc = null;
    ObjectProvider op = null;
    if (!ignoreCache) {
        // Check if an object exists in the L1/L2 caches for this id
        pc = getObjectFromCache(id);
    }
    if (pc == null) {
        // Find direct from the datastore if supported
        pc = getStoreManager().getPersistenceHandler().findObject(this, id);
    }
    boolean createdHollow = false;
    if (pc == null) {
        // Determine the class details for this "id" if not provided, including checking of inheritance level
        String className = cls != null ? cls.getName() : null;
        if (!(id instanceof SCOID)) {
            ClassDetailsForId details = getClassDetailsForId(id, className, checkInheritance);
            if (details.className != null && cls != null && !cls.getName().equals(details.className)) {
                cls = clr.classForName(details.className);
            }
            className = details.className;
            id = details.id;
            if (details.pc != null) {
                // Found following inheritance check via the cache
                pc = details.pc;
                op = findObjectProvider(pc);
            }
        }
        if (pc == null) {
            // Still not found so create a Hollow instance with the supplied field values
            if (cls == null) {
                try {
                    cls = clr.classForName(className, id.getClass().getClassLoader());
                } catch (ClassNotResolvedException e) {
                    String msg = Localiser.msg("010027", IdentityUtils.getPersistableIdentityForId(id));
                    NucleusLogger.PERSISTENCE.warn(msg);
                    throw new NucleusUserException(msg, e);
                }
            }
            createdHollow = true;
            // Will put object in L1 cache
            op = nucCtx.getObjectProviderFactory().newForHollow(this, cls, id, fv);
            pc = op.getObject();
            putObjectIntoLevel2Cache(op, false);
        }
    }
    if (pc != null && fv != null && !createdHollow) {
        // Object found in the cache so load the requested fields
        if (op == null) {
            op = findObjectProvider(pc);
        }
        if (op != null) {
            // Load the requested fields
            fv.fetchNonLoadedFields(op);
        }
    }
    return pc;
}
Also used : NucleusUserException(org.datanucleus.exceptions.NucleusUserException) ObjectProvider(org.datanucleus.state.ObjectProvider) SCOID(org.datanucleus.identity.SCOID) ClassNotResolvedException(org.datanucleus.exceptions.ClassNotResolvedException)

Example 14 with ClassNotResolvedException

use of org.datanucleus.exceptions.ClassNotResolvedException in project datanucleus-core by datanucleus.

the class RuntimeEnhancer method enhance.

public byte[] enhance(final String className, byte[] classdefinition, ClassLoader loader) {
    EnhancerClassLoader runtimeLoader = runtimeLoaderByLoader.get(loader);
    if (runtimeLoader == null) {
        runtimeLoader = new EnhancerClassLoader(loader);
        runtimeLoaderByLoader.put(loader, runtimeLoader);
    }
    // load unenhanced versions of classes from the EnhancerClassLoader
    clr.setPrimary(runtimeLoader);
    try {
        Class clazz = null;
        try {
            clazz = clr.classForName(className);
        } catch (ClassNotResolvedException e1) {
            DataNucleusEnhancer.LOGGER.debug(StringUtils.getStringFromStackTrace(e1));
            return null;
        }
        AbstractClassMetaData acmd = nucleusContext.getMetaDataManager().getMetaDataForClass(clazz, clr);
        if (acmd == null) {
            // metadata/class not found, ignore. happens in two conditions:
            // -class not in classpath
            // -class does not have metadata or annotation, so it's not supposed to be persistent
            DataNucleusEnhancer.LOGGER.debug("Class " + className + " cannot be enhanced because no metadata has been found.");
            return null;
        }
        // Create a ClassEnhancer to enhance this class
        ClassEnhancer classEnhancer = new ClassEnhancerImpl((ClassMetaData) acmd, clr, nucleusContext.getMetaDataManager(), JDOEnhancementNamer.getInstance(), classdefinition);
        // TODO Allow use of JPAEnhancementNamer?
        classEnhancer.setOptions(classEnhancerOptions);
        classEnhancer.enhance();
        return classEnhancer.getClassBytes();
    } catch (Throwable ex) {
        DataNucleusEnhancer.LOGGER.error(StringUtils.getStringFromStackTrace(ex));
    }
    return null;
}
Also used : ClassNotResolvedException(org.datanucleus.exceptions.ClassNotResolvedException) AbstractClassMetaData(org.datanucleus.metadata.AbstractClassMetaData)

Example 15 with ClassNotResolvedException

use of org.datanucleus.exceptions.ClassNotResolvedException in project datanucleus-core by datanucleus.

the class StateManagerImpl method checkInheritance.

/**
 * Look to the database to determine which class this object is. This parameter is a hint. Set false, if it's
 * already determined the correct pcClass for this pc "object" in a certain
 * level in the hierarchy. Set to true and it will look to the database.
 * TODO This is only called by some outdated code in LDAPUtils; remove it when that is fixed
 * @param fv the initial field values of the object.
 * @deprecated Dont use this, to be removed
 */
public void checkInheritance(FieldValues fv) {
    // Inheritance case, check the level of the instance
    ClassLoaderResolver clr = myEC.getClassLoaderResolver();
    String className = getStoreManager().getClassNameForObjectID(myID, clr, myEC);
    if (className == null) {
        // className is null when id class exists, and object has been validated and doesn't exist.
        throw new NucleusObjectNotFoundException(Localiser.msg("026013", IdentityUtils.getPersistableIdentityForId(myID)), myID);
    } else if (!cmd.getFullClassName().equals(className)) {
        Class pcClass;
        try {
            // load the class and make sure the class is initialized
            pcClass = clr.classForName(className, myID.getClass().getClassLoader(), true);
            cmd = myEC.getMetaDataManager().getMetaDataForClass(pcClass, clr);
        } catch (ClassNotResolvedException e) {
            NucleusLogger.PERSISTENCE.warn(Localiser.msg("026014", IdentityUtils.getPersistableIdentityForId(myID)));
            throw new NucleusUserException(Localiser.msg("026014", IdentityUtils.getPersistableIdentityForId(myID)), e);
        }
        if (cmd == null) {
            throw new NucleusUserException(Localiser.msg("026012", pcClass)).setFatal();
        }
        if (cmd.getIdentityType() != IdentityType.APPLICATION) {
            throw new NucleusUserException("This method should only be used for objects using application identity.").setFatal();
        }
        myFP = myEC.getFetchPlan().getFetchPlanForClass(cmd);
        int fieldCount = cmd.getMemberCount();
        dirtyFields = new boolean[fieldCount];
        loadedFields = new boolean[fieldCount];
        // Create new PC at right inheritance level
        myPC = HELPER.newInstance(pcClass, this);
        if (myPC == null) {
            throw new NucleusUserException(Localiser.msg("026018", cmd.getFullClassName())).setFatal();
        }
        // Note that this will mean the fields are loaded twice (loaded earlier in this method)
        // and also that postLoad will be called twice
        loadFieldValues(fv);
        // Create the id for the new PC
        myID = myEC.getNucleusContext().getIdentityManager().getApplicationId(myPC, cmd);
    }
}
Also used : NucleusUserException(org.datanucleus.exceptions.NucleusUserException) ClassLoaderResolver(org.datanucleus.ClassLoaderResolver) FetchPlanForClass(org.datanucleus.FetchPlanForClass) NucleusObjectNotFoundException(org.datanucleus.exceptions.NucleusObjectNotFoundException) ClassNotResolvedException(org.datanucleus.exceptions.ClassNotResolvedException)

Aggregations

ClassNotResolvedException (org.datanucleus.exceptions.ClassNotResolvedException)34 NucleusUserException (org.datanucleus.exceptions.NucleusUserException)18 ClassLoaderResolver (org.datanucleus.ClassLoaderResolver)13 NucleusException (org.datanucleus.exceptions.NucleusException)10 HashSet (java.util.HashSet)8 ArrayList (java.util.ArrayList)6 Iterator (java.util.Iterator)6 AbstractClassMetaData (org.datanucleus.metadata.AbstractClassMetaData)6 IOException (java.io.IOException)5 Collection (java.util.Collection)5 Method (java.lang.reflect.Method)4 List (java.util.List)4 ApiAdapter (org.datanucleus.api.ApiAdapter)4 Field (java.lang.reflect.Field)3 NucleusObjectNotFoundException (org.datanucleus.exceptions.NucleusObjectNotFoundException)3 SCOID (org.datanucleus.identity.SCOID)3 ObjectProvider (org.datanucleus.state.ObjectProvider)3 Constructor (java.lang.reflect.Constructor)2 InvocationTargetException (java.lang.reflect.InvocationTargetException)2 URL (java.net.URL)2