Search in sources :

Example 6 with IPersistent

use of org.jaffa.persistence.IPersistent in project jaffa-framework by jaffa-projects.

the class BeanMoulder method updateChildBean.

/**
 *  Take a source object and try and mold it back it its domain object.
 *  This is the same as updateParent, except from the way it retrieved the
 *  record, and the way it creates a new record.
 */
private static void updateChildBean(String path, DomainDAO source, UOW uow, MouldHandler handler, IPersistent parentDomain, GraphMapping parentMapping, String parentField) throws ApplicationExceptions, FrameworkException {
    log.debug("Update Child Bean " + path);
    // Call custom validation code in the DAO
    source.validate();
    ApplicationExceptions aes = new ApplicationExceptions();
    if (uow == null) {
        String err = "UOW Required";
        log.error(err);
        throw new RuntimeException(err);
    }
    String relationshipName = parentMapping.getDomainFieldName(parentField);
    if (relationshipName.endsWith("Array"))
        relationshipName = relationshipName.substring(0, relationshipName.length() - 5);
    if (relationshipName.endsWith("Object"))
        relationshipName = relationshipName.substring(0, relationshipName.length() - 6);
    try {
        IPersistent domainObject = null;
        GraphMapping mapping = MappingFactory.getInstance(source);
        Map keys = new LinkedHashMap();
        Class doClass = mapping.getDomainClass();
        boolean gotKeys = false;
        if (mapping.getKeyFields() == null || mapping.getKeyFields().size() == 0) {
            // No keys, must be one-to-one
            log.debug("Find 'one-to-one' object - " + path);
            // Just use the getXxxObject method to get the related domain object,
            // if there is one...
            domainObject = (IPersistent) getProperty(parentMapping.getDomainFieldDescriptor(parentField), parentDomain);
            if (domainObject == null)
                log.debug("Not Found - " + path);
        } else {
            // Get the key fields used in the domain object. Use the findXxxxxCriteria() method,
            // then add the extra fields to the criteria object, to get the unique record.
            gotKeys = fillInKeys(path, source, mapping, keys);
            // read DO based on key
            if (gotKeys) {
                // get the method to get the PK criteria (i.e. public Criteria findVendorSiteCriteria(); )
                Method findCriteria = null;
                String methodName = "find" + StringHelper.getUpper1(relationshipName) + "Criteria";
                try {
                    findCriteria = parentDomain.getClass().getMethod(methodName, new Class[] {});
                } catch (NoSuchMethodException e) {
                    log.error("Find method '" + methodName + "' not found!");
                }
                if (findCriteria == null) {
                    throw new MouldException(MouldException.METHOD_NOT_FOUND, path, methodName);
                }
                // Find Criteria For Related Object
                Criteria criteria = (Criteria) findCriteria.invoke(parentDomain, new Object[] {});
                // Add extra key info...
                for (Iterator it = keys.keySet().iterator(); it.hasNext(); ) {
                    String keyField = (String) it.next();
                    Object value = keys.get(keyField);
                    keyField = StringHelper.getUpper1(mapping.getDomainFieldName(keyField));
                    criteria.addCriteria(keyField, value);
                    log.debug(path + "- Add to criteria:" + keyField + "=" + value);
                }
                // See if we get an object :-)
                Iterator itr = uow.query(criteria).iterator();
                if (itr.hasNext())
                    domainObject = (IPersistent) itr.next();
                if (itr.hasNext()) {
                    // Error, multiple objects found
                    MultipleDomainObjectsFoundException m = new MultipleDomainObjectsFoundException(criteria.getTable() + " @ " + path);
                    aes.add(m);
                    throw aes;
                }
            } else {
                log.debug("Object " + path + " has either missing or null key values - Assume Create is needed");
            }
        }
        // Create object if not found
        if (domainObject == null) {
            // NEW OBJECT, create and reflect keys
            log.debug("DO '" + mapping.getDomainClassShortName() + "' not found with key, create a new one...");
            // find method on parent used to create object
            Method newObject = null;
            String methodName = "new" + StringHelper.getUpper1(relationshipName) + "Object";
            try {
                newObject = parentDomain.getClass().getMethod(methodName, new Class[] {});
            } catch (NoSuchMethodException e) {
                log.error("Method '" + methodName + "()' not found!");
            }
            if (newObject == null)
                throw new MouldException(MouldException.METHOD_NOT_FOUND, path, methodName);
            // Call method to create object
            domainObject = (IPersistent) newObject.invoke(parentDomain, new Object[] {});
            // Set the key fields
            for (Iterator it = keys.keySet().iterator(); it.hasNext(); ) {
                String keyField = (String) it.next();
                Object value = keys.get(keyField);
                updateProperty(mapping.getDomainFieldDescriptor(keyField), value, domainObject);
            }
        } else {
            log.debug("Found DO '" + mapping.getDomainClassShortName() + "' with key,");
        }
        // Now update all domain fields
        updateBeanData(path, source, uow, handler, mapping, domainObject);
    } catch (IllegalAccessException e) {
        MouldException me = new MouldException(MouldException.ACCESS_ERROR, path, e.getMessage());
        log.error(me.getLocalizedMessage(), e);
        throw me;
    } catch (InvocationTargetException e) {
        if (e.getCause() != null) {
            if (e.getCause() instanceof FrameworkException)
                throw (FrameworkException) e.getCause();
            if (e.getCause() instanceof ApplicationExceptions)
                throw (ApplicationExceptions) e.getCause();
            if (e.getCause() instanceof ApplicationException) {
                aes.add((ApplicationException) e.getCause());
                throw aes;
            }
        }
        MouldException me = new MouldException(MouldException.INVOCATION_ERROR, path, e);
        log.error(me.getLocalizedMessage(), me.getCause());
        throw me;
    } catch (InstantiationException e) {
        MouldException me = new MouldException(MouldException.INSTANTICATION_ERROR, path, e.getMessage());
        log.error(me.getLocalizedMessage(), e);
        throw me;
    }
}
Also used : ApplicationExceptions(org.jaffa.exceptions.ApplicationExceptions) FrameworkException(org.jaffa.exceptions.FrameworkException) Method(java.lang.reflect.Method) Criteria(org.jaffa.persistence.Criteria) InvocationTargetException(java.lang.reflect.InvocationTargetException) LinkedHashMap(java.util.LinkedHashMap) ApplicationException(org.jaffa.exceptions.ApplicationException) IPersistent(org.jaffa.persistence.IPersistent) MultipleDomainObjectsFoundException(org.jaffa.exceptions.MultipleDomainObjectsFoundException) Iterator(java.util.Iterator) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) GraphMapping(org.jaffa.beans.moulding.mapping.GraphMapping)

Example 7 with IPersistent

use of org.jaffa.persistence.IPersistent in project jaffa-framework by jaffa-projects.

the class PersistentTransaction method addObject.

/**
 * Adds an object to the transaction to be written.
 * The PreAdd trigger for will be invoked and the domain object will be validated before the addition to the transaction.
 *
 * @param object                the object to be created.
 * @param invokeLifecycleEvents Lifecycle events will be invoked if this parameter is true.
 * @throws AddFailedException if any error occurs during the validation of the persistent object.
 * @throws IllegalPersistentStateRuntimeException
 *                            this RuntimeException will be thrown if the domain object has been submitted to the UOW for an Add/Update/Delete and commit hasnt yet been performed.
 */
public void addObject(IPersistent object, boolean invokeLifecycleEvents) throws AddFailedException, IllegalPersistentStateRuntimeException {
    if (object.isQueued()) {
        String str = "The domain object has already been submitted to the UOW for an Add/Update/Delete. No more updates can be performed until after a commit";
        log.error(str);
        throw new IllegalPersistentStateRuntimeException(str);
    }
    List<ILifecycleHandler> handlers = null;
    if (object != null) {
        handlers = object.getLifecycleHandlers();
    }
    if (invokeLifecycleEvents) {
        if (log.isDebugEnabled())
            log.debug("Invoking the PreAdd trigger on the Persistent object");
        for (ILifecycleHandler lifeCycleHandler : handlers) {
            lifeCycleHandler.preAdd();
        }
    }
    if (adds == null) {
        adds = new ArrayList<IPersistent>();
    }
    adds.add(object);
    if (log.isDebugEnabled()) {
        log.debug("Added the Persistent object to the ADD collection");
    }
    object.setQueued(true);
    if (invokeLifecycleEvents) {
        // If there is a persistence logging plugin add the object to it
        if (persistenceLoggingPlugins != null) {
            try {
                if (log.isDebugEnabled()) {
                    log.debug("Invoking the add method on the IPersistenceLoggingPlugin instances");
                }
                for (IPersistenceLoggingPlugin persistenceLoggingPlugin : persistenceLoggingPlugins) {
                    persistenceLoggingPlugin.add(object);
                }
            } catch (Exception e) {
                log.error("Error in logging the ADD event", e);
                throw new AddFailedException(null, e);
            }
        }
        if (log.isDebugEnabled()) {
            log.debug("Invoking the PostAdd trigger on the Persistent object");
        }
        // Invoke the post add behaviors
        for (ILifecycleHandler lifecycleHandler : handlers) {
            lifecycleHandler.postAdd();
        }
    }
}
Also used : ILifecycleHandler(org.jaffa.persistence.ILifecycleHandler) IPersistent(org.jaffa.persistence.IPersistent) IPersistenceLoggingPlugin(org.jaffa.persistence.logging.IPersistenceLoggingPlugin) DataSourceCreationException(org.jaffa.persistence.engines.jdbcengine.datasource.exceptions.DataSourceCreationException) FrameworkException(org.jaffa.exceptions.FrameworkException) SQLException(java.sql.SQLException)

Example 8 with IPersistent

use of org.jaffa.persistence.IPersistent in project jaffa-framework by jaffa-projects.

the class PersistentTransaction method deleteObject.

/**
 * Adds an object to the transaction to be deleted.
 * The PreDelete trigger will be invoked before the deletion from the transaction.
 *
 * @param object                the object to be deleted.
 * @param invokeLifecycleEvents Lifecycle events will be invoked if this parameter is true.
 * @throws DeleteFailedException if any error occurs during the process.
 * @throws IllegalPersistentStateRuntimeException
 *                               this RuntimeException will be thrown if the domain object has been submitted to the UOW for an Add/Update/Delete and commit hasnt yet been performed.
 */
public void deleteObject(IPersistent object, boolean invokeLifecycleEvents) throws DeleteFailedException, IllegalPersistentStateRuntimeException {
    if (object.isQueued()) {
        String str = "The domain object has already been submitted to the UOW for an Add/Update/Delete. No more updates can be performed until after a commit";
        log.error(str);
        throw new IllegalPersistentStateRuntimeException(str);
    }
    List<ILifecycleHandler> handlers = null;
    if (object != null) {
        handlers = object.getLifecycleHandlers();
    }
    if (invokeLifecycleEvents) {
        if (log.isDebugEnabled())
            log.debug("Invoking the PreDelete trigger on the Persistent object");
        for (ILifecycleHandler lifecycleHandler : handlers) {
            lifecycleHandler.preDelete();
        }
    }
    if (deletes == null) {
        deletes = new ArrayList<IPersistent>();
    }
    deletes.add(object);
    if (log.isDebugEnabled()) {
        log.debug("Added the Persistent object to the DELETE collection");
    }
    object.setQueued(true);
    if (invokeLifecycleEvents) {
        // If there is a persistence logging plugin delete the object
        if (persistenceLoggingPlugins != null) {
            try {
                if (log.isDebugEnabled()) {
                    log.debug("Invoking the delete method on the IPersistenceLoggingPlugin instances");
                }
                for (IPersistenceLoggingPlugin persistenceLoggingPlugin : persistenceLoggingPlugins) {
                    persistenceLoggingPlugin.delete(object);
                }
            } catch (Exception e) {
                log.error("Error in logging the DELETE event", e);
                throw new DeleteFailedException(null, e);
            }
        }
        if (log.isDebugEnabled()) {
            log.debug("Invoking the PostDelete trigger on the Persistent object");
        }
        // Invoke the post delete behaviors
        for (ILifecycleHandler lifecycleHandler : handlers) {
            lifecycleHandler.postDelete();
        }
    }
}
Also used : ILifecycleHandler(org.jaffa.persistence.ILifecycleHandler) IPersistent(org.jaffa.persistence.IPersistent) IPersistenceLoggingPlugin(org.jaffa.persistence.logging.IPersistenceLoggingPlugin) DataSourceCreationException(org.jaffa.persistence.engines.jdbcengine.datasource.exceptions.DataSourceCreationException) FrameworkException(org.jaffa.exceptions.FrameworkException) SQLException(java.sql.SQLException)

Example 9 with IPersistent

use of org.jaffa.persistence.IPersistent in project jaffa-framework by jaffa-projects.

the class DeleteInterceptor method invoke.

/**
 *Performs the logic associated with deleting Persistent objects from the database.
 * This will delete each object in the PersistentTransaction's DELETE collection from the database, utilising the JdbcBridge.
 * It will then pass on the control to the next Interceptor in the chain.
 * @param pt The PersistentTransaction object, on which the Interceptor is to be executed.
 * @throws UOWException if any error occurs.
 * @return the output from the next Interceptor in the chain.
 */
public Object invoke(PersistentTransaction pt) throws UOWException {
    Collection objects = pt.getDeletes();
    if (objects != null) {
        // deletes the objects from the database
        for (Iterator i = objects.iterator(); i.hasNext(); ) {
            IPersistent object = (IPersistent) i.next();
            try {
                if (log.isDebugEnabled())
                    log.debug("Invoking JdbcBridge.executeDelete() for the object " + object);
                JdbcBridge.executeDelete(object, pt.getDataSource());
                pt.getDataSource().clearObjectCache();
            } catch (Exception e) {
                String str = "Error while deleting the Persistent object from the database: " + object;
                log.error(str, e);
                throw new DeleteFailedException(null, e);
            }
            i.remove();
        }
    }
    // pass control to the next interceptor in the chain
    if (getNextInterceptor() != null) {
        if (log.isDebugEnabled())
            log.debug("Invoking the next Interceptor in the chain " + getNextInterceptor().getClass().getName());
        return getNextInterceptor().invoke(pt);
    } else {
        if (log.isDebugEnabled())
            log.debug("This is the end of the Interceptor chain");
        return null;
    }
}
Also used : IPersistent(org.jaffa.persistence.IPersistent) DeleteFailedException(org.jaffa.persistence.exceptions.DeleteFailedException) DeleteFailedException(org.jaffa.persistence.exceptions.DeleteFailedException) UOWException(org.jaffa.persistence.exceptions.UOWException)

Example 10 with IPersistent

use of org.jaffa.persistence.IPersistent in project jaffa-framework by jaffa-projects.

the class UpdateInterceptor method invoke.

/**
 *Performs the logic associated with updating Persistent objects in the database.
 * This will update each object in the PersistentTransaction's UPDATE collection in the database, utilising the JdbcBridge.
 * It will then pass on the control to the next Interceptor in the chain.
 * @param pt The PersistentTransaction object, on which the Interceptor is to be executed.
 * @throws UOWException if any error occurs.
 * @return the output from the next Interceptor in the chain.
 */
public Object invoke(PersistentTransaction pt) throws UOWException {
    Collection objects = pt.getUpdates();
    if (objects != null) {
        // updates the objects in the database
        for (Iterator i = objects.iterator(); i.hasNext(); ) {
            IPersistent object = (IPersistent) i.next();
            try {
                if (log.isDebugEnabled())
                    log.debug("Invoking JdbcBridge.executeUpdate() for the object " + object);
                JdbcBridge.executeUpdate(object, pt.getDataSource());
                pt.getDataSource().clearObjectCache();
            } catch (Exception e) {
                String str = "Error while updating the Persistent object in the database: " + object;
                log.error(str, e);
                throw new UpdateFailedException(null, e);
            }
            i.remove();
        }
    }
    // pass control to the next interceptor in the chain
    if (getNextInterceptor() != null) {
        if (log.isDebugEnabled())
            log.debug("Invoking the next Interceptor in the chain " + getNextInterceptor().getClass().getName());
        return getNextInterceptor().invoke(pt);
    } else {
        if (log.isDebugEnabled())
            log.debug("This is the end of the Interceptor chain");
        return null;
    }
}
Also used : IPersistent(org.jaffa.persistence.IPersistent) UpdateFailedException(org.jaffa.persistence.exceptions.UpdateFailedException) UpdateFailedException(org.jaffa.persistence.exceptions.UpdateFailedException) UOWException(org.jaffa.persistence.exceptions.UOWException)

Aggregations

IPersistent (org.jaffa.persistence.IPersistent)29 FrameworkException (org.jaffa.exceptions.FrameworkException)14 InvocationTargetException (java.lang.reflect.InvocationTargetException)11 Criteria (org.jaffa.persistence.Criteria)11 Method (java.lang.reflect.Method)10 UOW (org.jaffa.persistence.UOW)10 Iterator (java.util.Iterator)9 Map (java.util.Map)9 LinkedHashMap (java.util.LinkedHashMap)8 ApplicationException (org.jaffa.exceptions.ApplicationException)7 ApplicationExceptions (org.jaffa.exceptions.ApplicationExceptions)7 DomainObjectNotFoundException (org.jaffa.exceptions.DomainObjectNotFoundException)5 MultipleDomainObjectsFoundException (org.jaffa.exceptions.MultipleDomainObjectsFoundException)5 GraphDataObject (org.jaffa.soa.graph.GraphDataObject)5 AccessibleObject (java.lang.reflect.AccessibleObject)4 HashMap (java.util.HashMap)4 GraphMapping (org.jaffa.beans.moulding.mapping.GraphMapping)4 SQLException (java.sql.SQLException)3 ILifecycleHandler (org.jaffa.persistence.ILifecycleHandler)3 DataSourceCreationException (org.jaffa.persistence.engines.jdbcengine.datasource.exceptions.DataSourceCreationException)3