Search in sources :

Example 16 with IPersistent

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

the class DataTransformer method deleteGraph.

/**
 * Take a source object and delete it or delete is children if it has any
 *
 * @param path    The path of this object being processed. This identifies possible parent
 *                and/or indexed entries where this object is contained.
 * @param source  Source object to mould from, typically a GraphDataObject
 * @param uow     Transaction handle all creates/update will be performed within.
 *                Throws an exception if null.
 * @param handler Possible bean handler to be used when processing this source object graph
 * @throws ApplicationExceptions Thrown if one or more application logic errors are generated during moulding
 * @throws FrameworkException    Thrown if any runtime moulding error has occured.
 */
public static void deleteGraph(String path, GraphDataObject source, UOW uow, ITransformationHandler handler) throws ApplicationExceptions, FrameworkException {
    if (log.isDebugEnabled())
        log.debug("Delete Bean " + path);
    try {
        IPersistent domainObject = null;
        GraphMapping mapping = MappingFactory.getInstance(source);
        Map keys = new LinkedHashMap();
        Class doClass = mapping.getDomainClass();
        // Get the key fields used in the domain object
        boolean gotKeys = TransformerUtils.fillInKeys(path, source, mapping, keys);
        // read DO based on key
        if (gotKeys) {
            // get the method on the DO to read via PK
            Method[] ma = doClass.getMethods();
            Method findByPK = null;
            for (int i = 0; i < ma.length; i++) {
                if (ma[i].getName().equals("findByPK")) {
                    if (ma[i].getParameterTypes().length == (keys.size() + 1) && (ma[i].getParameterTypes())[0] == UOW.class) {
                        // Found with name and correct no. of input params
                        findByPK = ma[i];
                        break;
                    }
                }
            }
            if (findByPK == null)
                throw new ApplicationExceptions(new DomainObjectNotFoundException(doClass.getName()));
            // Build input array
            Object[] inputs = new Object[keys.size() + 1];
            {
                inputs[0] = uow;
                int i = 1;
                for (Iterator it = keys.values().iterator(); it.hasNext(); i++) {
                    inputs[i] = it.next();
                }
            }
            // Find Object based on key
            domainObject = (IPersistent) findByPK.invoke(null, inputs);
        } else {
            if (log.isDebugEnabled())
                log.debug("Object " + path + " has either missing or null key values - Assume Create is needed");
        }
        // Error if DO not found
        if (domainObject == null)
            throw new ApplicationExceptions(new DomainObjectNotFoundException(TransformerUtils.findDomainLabel(doClass)));
        // Process the delete, either on this DO, or a related DO if there is one
        TransformerUtils.deleteBeanData(path, source, uow, handler, mapping, domainObject);
        // Invoke the changeDone trigger
        if (handler != null && handler.isChangeDone()) {
            for (ITransformationHandler transformationHandler : handler.getTransformationHandlers()) {
                transformationHandler.changeDone(path, source, domainObject, uow);
            }
        }
    } catch (IllegalAccessException e) {
        TransformException me = new TransformException(TransformException.ACCESS_ERROR, path, e.getMessage());
        log.error(me.getLocalizedMessage(), e);
        throw me;
    } catch (InvocationTargetException e) {
        ApplicationExceptions appExps = ExceptionHelper.extractApplicationExceptions(e);
        if (appExps != null)
            throw appExps;
        FrameworkException fe = ExceptionHelper.extractFrameworkException(e);
        if (fe != null)
            throw fe;
        TransformException me = new TransformException(TransformException.INVOCATION_ERROR, path, e);
        log.error(me.getLocalizedMessage(), me.getCause());
        throw me;
    } catch (InstantiationException e) {
        TransformException me = new TransformException(TransformException.INSTANTICATION_ERROR, path, e.getMessage());
        log.error(me.getLocalizedMessage(), e);
        throw me;
    }
// } catch (Exception e) {
// throw handleException(e,aes);
// }
}
Also used : Method(java.lang.reflect.Method) InvocationTargetException(java.lang.reflect.InvocationTargetException) LinkedHashMap(java.util.LinkedHashMap) IPersistent(org.jaffa.persistence.IPersistent) Iterator(java.util.Iterator) GraphDataObject(org.jaffa.soa.graph.GraphDataObject) AccessibleObject(java.lang.reflect.AccessibleObject) UOW(org.jaffa.persistence.UOW) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map)

Example 17 with IPersistent

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

the class CandidateKeyValidator method validateProperty.

/**
 * {@inheritDoc}
 */
@Override
protected void validateProperty(T targetObject, String targetPropertyName, Object targetPropertyValue, List<RuleMetaData> rules, UOW uow) throws ApplicationException, FrameworkException {
    String targetClassName = getActualClassName(targetObject.getClass());
    IPersistent persistentTargetObject = null;
    try {
        // Use the associated persistentObject for a FlexBean instance
        if (targetObject instanceof FlexBean && ((FlexBean) targetObject).getPersistentObject() != null) {
            persistentTargetObject = ((FlexBean) targetObject).getPersistentObject();
            targetClassName = persistentTargetObject.getClass().getName();
        }
        // This rules makes sense on IPersistent instances only. Bail out on all other instances
        if (!(targetObject instanceof IPersistent)) {
            return;
        } else if (persistentTargetObject == null) {
            persistentTargetObject = (IPersistent) targetObject;
        }
        // Obtain a Map containing key fields and corresponding values
        Map<String, Object> keyValueMap = getKeyValueMap(targetClassName, (IPersistent) targetObject);
        // Create a criteria such that the current object is not included in the search for candidate-key violations
        AtomicCriteria criteriaToDiscardCurrentObject = createCriteriaToDiscardCurrentObject(persistentTargetObject, keyValueMap);
        // Invoke each rule
        for (RuleMetaData rule : rules) {
            invoke(targetClassName, persistentTargetObject, uow, rule, criteriaToDiscardCurrentObject, keyValueMap);
        }
    } catch (ApplicationExceptions e) {
        if (log.isDebugEnabled()) {
            log.debug("Error in validateProperty method for object: " + targetClassName, e);
        }
        throw new JaffaRulesFrameworkException("Error in validateProperty method for object: " + targetClassName, null, e);
    }
}
Also used : ApplicationExceptions(org.jaffa.exceptions.ApplicationExceptions) IPersistent(org.jaffa.persistence.IPersistent) AtomicCriteria(org.jaffa.persistence.AtomicCriteria) RuleMetaData(org.jaffa.rules.meta.RuleMetaData) FlexBean(org.jaffa.flexfields.FlexBean) JaffaRulesFrameworkException(org.jaffa.rules.JaffaRulesFrameworkException)

Example 18 with IPersistent

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

the class PersistentTransaction method updateObject.

/**
 * Adds an object to the transaction to be updated.
 * The PreUpdate trigger will be invoked and the domain object will be validated before the updation to the transaction.
 *
 * @param object                the object to be updated.
 * @param invokeLifecycleEvents Lifecycle events will be invoked if this parameter is true.
 * @throws UpdateFailedException 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 updateObject(IPersistent object, boolean invokeLifecycleEvents) throws UpdateFailedException, 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);
    }
    if (!object.isModified()) {
        if (log.isDebugEnabled())
            log.debug("The Persistent object has not been modified. So it will not be added to the Interceptor queue for an Add");
        return;
    }
    List<ILifecycleHandler> handlers = null;
    if (object != null) {
        handlers = object.getLifecycleHandlers();
    }
    if (invokeLifecycleEvents) {
        if (log.isDebugEnabled())
            log.debug("Invoking the PreUpdate trigger on the Persistent object");
        for (ILifecycleHandler lifecycleHandler : handlers) {
            lifecycleHandler.preUpdate();
        }
    }
    if (updates == null) {
        updates = new ArrayList<IPersistent>();
    }
    updates.add(object);
    if (log.isDebugEnabled()) {
        log.debug("Added the Persistent object to the UPDATE collection");
    }
    object.setQueued(true);
    if (invokeLifecycleEvents) {
        // If there is a persistence logging plugin update the object
        if (persistenceLoggingPlugins != null) {
            try {
                if (log.isDebugEnabled()) {
                    log.debug("Invoking the update method on the IPersistenceLoggingPlugin instances");
                }
                for (IPersistenceLoggingPlugin persistenceLoggingPlugin : persistenceLoggingPlugins) {
                    persistenceLoggingPlugin.update(object);
                }
            } catch (Exception e) {
                log.error("Error in logging the UPDATE event", e);
                throw new UpdateFailedException(null, e);
            }
        }
        if (log.isDebugEnabled()) {
            log.debug("Invoking the PostUpdate trigger on the Persistent object");
        }
        // Invoke the post update behaviors
        for (ILifecycleHandler lifecycleHandler : handlers) {
            lifecycleHandler.postUpdate();
        }
    }
}
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 19 with IPersistent

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

the class AddInterceptor method invoke.

/**
 *Performs the logic associated with adding Persistent objects to the database.
 * This will add each object in the PersistentTransaction's ADD collection to 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.getAdds();
    if (objects != null) {
        // add the objects to the database
        for (Iterator i = objects.iterator(); i.hasNext(); ) {
            IPersistent object = (IPersistent) i.next();
            try {
                if (log.isDebugEnabled())
                    log.debug("Invoking JdbcBridge.executeAdd() for the object " + object);
                JdbcBridge.executeAdd(object, pt.getDataSource());
                pt.getDataSource().clearObjectCache();
            } catch (SQLIntegrityConstraintViolationException e) {
                if (e.getErrorCode() == PRIMARY_KEY_ERROR_CODE) {
                    String str = "The primary-key is not unique: " + this;
                    log.error(str);
                    String labelToken = null;
                    try {
                        labelToken = PersistentHelper.getLabelToken(object.getClass().getName());
                    } catch (Exception ex) {
                    // don't do anything.. just return the domainClassName
                    }
                    if (labelToken == null)
                        labelToken = MessageHelper.tokenize(object.getClass().getName());
                    throw new PreAddFailedException(null, new DuplicateKeyException(labelToken));
                } else {
                    String str = "Error while adding the Persistent object to the database: " + object;
                    log.error(str, e);
                    // was checked in pre-add previously
                    throw new PreAddFailedException(null, e);
                }
            } catch (Exception e) {
                String str = "Error while adding the Persistent object to the database: " + object;
                log.error(str, e);
                throw new AddFailedException(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) PreAddFailedException(org.jaffa.persistence.exceptions.PreAddFailedException) AddFailedException(org.jaffa.persistence.exceptions.AddFailedException) SQLIntegrityConstraintViolationException(java.sql.SQLIntegrityConstraintViolationException) UOWException(org.jaffa.persistence.exceptions.UOWException) PreAddFailedException(org.jaffa.persistence.exceptions.PreAddFailedException) DuplicateKeyException(org.jaffa.exceptions.DuplicateKeyException) SQLIntegrityConstraintViolationException(java.sql.SQLIntegrityConstraintViolationException) AddFailedException(org.jaffa.persistence.exceptions.AddFailedException) DuplicateKeyException(org.jaffa.exceptions.DuplicateKeyException) PreAddFailedException(org.jaffa.persistence.exceptions.PreAddFailedException)

Example 20 with IPersistent

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

the class PersistentHelper method loadFromSerializedKey.

/**
 * This will load the persistent object from the input serialized key, by invoking the findByPK() method of the persistent class encoded in the input String.
 * @param uow The UOW object. If null, then a UOW will be created implicitly by the findByPK method to load the persistent object.
 * @param serializedKey The serialized key which will have the right information to load the persistent object.
 * @throws ClassNotFoundException if the Persistent class or its Meta class are not found.
 * @throws NoSuchMethodException if the Persistent class does not have the 'public static IPersistent findByPK(UOW uow, KeyField1...)'  method or the Meta class does not have the 'public static FieldMetaData[] getKeyFields()' method.
 * @throws IllegalAccessException if the 'public static FieldMetaData[] getKeyFields()' method of the Meta class enforces Java language access control and the underlying method is inaccessible.
 * @throws InvocationTargetException if the 'public static FieldMetaData[] getKeyFields()' method of the Meta class throws an exception.
 * @throws IllegalArgumentException if the input persistent class does not have any key-fields or if any of the key-fields is null.
 * @throws IntrospectionException if an exception occurs during introspection.
 * @throws FrameworkException if the findByPK() method of the persistent class fails.
 * @return a Persistent object.
 */
public static IPersistent loadFromSerializedKey(UOW uow, String serializedKey) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, IllegalArgumentException, IntrospectionException, FrameworkException {
    // Determine the persistent class name
    int beginIndex = 0;
    int endIndex = serializedKey.indexOf(';');
    if (endIndex <= 0) {
        String str = "Persistent object cannot be loaded. The input serialized key does not have the Persistent class name " + serializedKey;
        log.error(str);
        throw new IllegalArgumentException(str);
    }
    String persistentClassName = serializedKey.substring(beginIndex, endIndex);
    if (log.isDebugEnabled())
        log.debug("Found persistent class " + persistentClassName);
    Class persistentClass = Class.forName(persistentClassName);
    // Create an argument List to be passed to the findByPK method of the persistent class
    List arguments = new LinkedList();
    arguments.add(uow);
    // Get the key fields for the persistent class from its meta class
    FieldMetaData[] keyFields = getKeyFields(persistentClassName);
    if (keyFields != null && keyFields.length > 0) {
        for (int i = 0; i < keyFields.length; i++) {
            // Determine the value for a keyfield
            String keyFieldName = keyFields[i].getName();
            String keyFieldValue = null;
            beginIndex = endIndex + 1;
            endIndex = beginIndex + 1;
            if (beginIndex < serializedKey.length()) {
                if (endIndex >= serializedKey.length()) {
                    // We are currently on the last character of the input serializedkey
                    keyFieldValue = serializedKey.substring(beginIndex);
                } else {
                    // Search for the next ';', making sure that its not quoted
                    while (true) {
                        endIndex = serializedKey.indexOf(';', endIndex);
                        if (endIndex < 0) {
                            // No more ';'
                            keyFieldValue = serializedKey.substring(beginIndex);
                            break;
                        } else if (serializedKey.charAt(endIndex - 1) != '\\') {
                            // The ';' is not quoted
                            keyFieldValue = serializedKey.substring(beginIndex, endIndex);
                            break;
                        } else {
                            // We've reached a quoted ';'. Go past it
                            ++endIndex;
                            if (endIndex >= serializedKey.length()) {
                                // No more search possible
                                keyFieldValue = serializedKey.substring(beginIndex);
                                break;
                            }
                        }
                    }
                }
            }
            // Unquote the keyvalue
            keyFieldValue = unquoteSerializedKeyValue(keyFieldValue);
            // Throw an exception if the input serializedkey does not have a value for the keyfield
            if (keyFieldValue == null || keyFieldValue.length() == 0) {
                String str = "Persistent object cannot be loaded. The input serialized key does not have a value for the key field " + keyFieldName;
                log.error(str);
                throw new IllegalArgumentException(str);
            }
            if (log.isDebugEnabled())
                log.debug("Found " + keyFieldName + '=' + keyFieldValue);
            // Convert the keyFieldValue to the appropriate datatype
            Object convertedKeyFieldValue = DataTypeMapper.instance().map(keyFieldValue, Defaults.getClass(keyFields[i].getDataType()));
            if (convertedKeyFieldValue == null) {
                String str = "Persistent object cannot be loaded. The keyField " + keyFieldName + " having the value " + keyFieldValue + " could not be converted to the appropriate datatype";
                log.error(str);
                throw new IllegalArgumentException(str);
            }
            arguments.add(convertedKeyFieldValue);
        }
        // Get a handle on the findByPK method of the persistent class
        Class[] argumentsClassArray = new Class[arguments.size()];
        argumentsClassArray[0] = UOW.class;
        for (int i = 1; i < arguments.size(); i++) argumentsClassArray[i] = arguments.get(i).getClass();
        Method m = persistentClass.getMethod("findByPK", argumentsClassArray);
        try {
            return (IPersistent) m.invoke(null, arguments.toArray());
        } catch (InvocationTargetException e) {
            if (e.getCause() != null && e.getCause() instanceof FrameworkException)
                throw (FrameworkException) e.getCause();
            else
                throw e;
        }
    } else {
        String str = "Persistent object cannot be loaded. The persistent class specified in the input serialzedKey does not have any key fields defined in its meta class: " + persistentClassName;
        log.error(str);
        throw new IllegalArgumentException(str);
    }
}
Also used : FrameworkException(org.jaffa.exceptions.FrameworkException) Method(java.lang.reflect.Method) LinkedList(java.util.LinkedList) InvocationTargetException(java.lang.reflect.InvocationTargetException) FieldMetaData(org.jaffa.metadata.FieldMetaData) IPersistent(org.jaffa.persistence.IPersistent) List(java.util.List) LinkedList(java.util.LinkedList)

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