Search in sources :

Example 16 with ApplicationException

use of org.jaffa.exceptions.ApplicationException in project jaffa-framework by jaffa-projects.

the class BeanMoulder method updateBean.

/**
 * Take a source object and try and mold it back it its domain object
 * @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 DomainDAO
 * @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 updateBean(String path, DomainDAO source, UOW uow, MouldHandler handler) throws ApplicationExceptions, FrameworkException {
    log.debug("Update 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);
    }
    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 = 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) {
                aes.add(new DomainObjectNotFoundException(doClass.getName() + " @ " + path));
                throw aes;
            }
            // 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
            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...");
            domainObject = (IPersistent) doClass.newInstance();
            // 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) InvocationTargetException(java.lang.reflect.InvocationTargetException) LinkedHashMap(java.util.LinkedHashMap) ApplicationException(org.jaffa.exceptions.ApplicationException) IPersistent(org.jaffa.persistence.IPersistent) DomainObjectNotFoundException(org.jaffa.exceptions.DomainObjectNotFoundException) Iterator(java.util.Iterator) UOW(org.jaffa.persistence.UOW) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) GraphMapping(org.jaffa.beans.moulding.mapping.GraphMapping)

Example 17 with ApplicationException

use of org.jaffa.exceptions.ApplicationException in project jaffa-framework by jaffa-projects.

the class BeanMoulder method updateBeanData.

private static void updateBeanData(String path, DomainDAO source, UOW uow, MouldHandler handler, GraphMapping mapping, IPersistent domainObject) throws InstantiationException, IllegalAccessException, InvocationTargetException, ApplicationExceptions, FrameworkException {
    try {
        // Fire 'startBean' handler
        if (handler != null)
            handler.startBean(path, source, domainObject);
        // Reflect all normal fields
        for (Iterator it = mapping.getFields().iterator(); it.hasNext(); ) {
            String field = (String) it.next();
            if (source.hasChanged(field)) {
                Object value = getProperty(mapping.getDataFieldDescriptor(field), source);
                // if(value!=null)
                updateProperty(mapping.getDomainFieldDescriptor(field), value, domainObject);
            }
        }
        // Reflect any foreign keys
        for (Iterator it = mapping.getForeignFields().iterator(); it.hasNext(); ) {
            String field = (String) it.next();
            if (source.hasChanged(field)) {
                Object value = getProperty(mapping.getDataFieldDescriptor(field), source);
                if (value != null) {
                    // need to map foreign keys back
                    List targetKeys = mapping.getForeignKeys(field);
                    GraphMapping fMapping = MappingFactory.getInstance(mapping.getDataFieldDescriptor(field).getPropertyType());
                    Set sourceKeys = fMapping.getKeyFields();
                    int i = 0;
                    for (Iterator i2 = sourceKeys.iterator(); i2.hasNext(); i++) {
                        String sourceFld = (String) i2.next();
                        String targetFld = (String) targetKeys.get(i);
                        log.debug("Copy Foreign Key Field from " + sourceFld + " to " + targetFld);
                        Object value2 = getProperty(fMapping.getDataFieldDescriptor(sourceFld), value);
                        updateProperty(mapping.getRealDomainFieldDescriptor(targetFld), value2, domainObject);
                    }
                }
            }
        }
        // Store Record
        if (domainObject.isDatabaseOccurence()) {
            log.debug("UOW.Update Domain Object");
            // Fire 'startBeanUpdate' handler
            if (handler != null)
                handler.startBeanUpdate(path, source, domainObject);
            uow.update(domainObject);
            // Fire 'endBeanUpdate' handler
            if (handler != null)
                handler.endBeanUpdate(path, source, domainObject);
        } else {
            log.debug("UOW.Add Domain Object");
            // Fire 'startBeanAdd' handler
            if (handler != null)
                handler.startBeanAdd(path, source, domainObject);
            uow.add(domainObject);
            // Fire 'endBeanAdd' handler
            if (handler != null)
                handler.endBeanAdd(path, source, domainObject);
        }
        // Reflect any related objects
        for (Iterator it = mapping.getRelatedFields().iterator(); it.hasNext(); ) {
            String field = (String) it.next();
            if (source.hasChanged(field)) {
                // Only do the update if the source object was updated!
                Object value = getProperty(mapping.getDataFieldDescriptor(field), source);
                if (value != null) {
                    if (value.getClass().isArray()) {
                        // The related field is an array of objects (one-to-many)
                        Object[] values = (Object[]) value;
                        for (int i = 0; i < values.length; i++) {
                            // Assumes its a DAO....what else could it be?
                            DomainDAO dao = (DomainDAO) values[i];
                            if (dao != null) {
                                updateChildBean(path + "." + field + "[" + i + "]", dao, uow, handler, domainObject, mapping, field);
                            }
                        }
                    } else {
                        // Or a single Object (one-to-one)
                        // Assumes its a DAO....what else could it be?
                        DomainDAO dao = (DomainDAO) value;
                        updateChildBean(path + "." + field, dao, uow, handler, domainObject, mapping, field);
                    }
                }
            }
        }
        // Fire 'endBean' handler
        if (handler != null)
            handler.endBean(path, source, domainObject);
    } catch (ApplicationException e) {
        ApplicationExceptions aes = new ApplicationExceptions();
        aes.add(e);
        throw aes;
    }
}
Also used : Set(java.util.Set) ApplicationException(org.jaffa.exceptions.ApplicationException) ApplicationExceptions(org.jaffa.exceptions.ApplicationExceptions) Iterator(java.util.Iterator) DomainDAO(org.jaffa.beans.moulding.data.domain.DomainDAO) ArrayList(java.util.ArrayList) List(java.util.List) GraphMapping(org.jaffa.beans.moulding.mapping.GraphMapping)

Example 18 with ApplicationException

use of org.jaffa.exceptions.ApplicationException 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 19 with ApplicationException

use of org.jaffa.exceptions.ApplicationException in project jaffa-framework by jaffa-projects.

the class UserTimeEntryMaintenanceTx method create.

// .//GEN-END:_prevalidateCreate_1_be
// .//GEN-BEGIN:_create_1_be
/**
 * Persists a new instance of UserTimeEntry.
 * @param input The new values for the domain object.
 * @throws ApplicationExceptions This will be thrown if the input contains invalid data.
 * @throws FrameworkException Indicates some system error.
 * @return The object details.
 */
public UserTimeEntryMaintenanceRetrieveOutDto create(UserTimeEntryMaintenanceCreateInDto input) throws FrameworkException, ApplicationExceptions {
    UOW uow = null;
    try {
        // Print Debug Information for the input
        if (log.isDebugEnabled())
            log.debug("Input: " + (input != null ? input.toString() : null));
        // create the UOW
        uow = new UOW();
        // Preprocess the input
        preprocess(uow, input);
        // Do not allow a Duplicate record
        duplicateCheck(uow, input);
        // Validate the foreign objects
        validateForeignObjects(uow, input);
        // Create the domain object
        UserTimeEntry domain = createDomain(uow, input, false);
        uow.add(domain);
        // Perform post create processing
        postCreate(uow, input, domain, false);
        // Commit the changes
        uow.commit();
        // Print Debug Information for the output
        if (log.isDebugEnabled())
            log.debug("Successfully created the domain object. Now retrieving the object details.");
        // Build the outbound dto by performing a retrieve
        UserTimeEntryMaintenanceRetrieveInDto retrieveInDto = new UserTimeEntryMaintenanceRetrieveInDto();
        retrieveInDto.setHeaderDto(input.getHeaderDto());
        retrieveInDto.setUserName(input.getUserName());
        retrieveInDto.setProjectCode(input.getProjectCode());
        retrieveInDto.setTask(input.getTask());
        retrieveInDto.setPeriodStart(input.getPeriodStart());
        retrieveInDto.setPeriodEnd(input.getPeriodEnd());
        UserTimeEntryMaintenanceRetrieveOutDto output = retrieve(retrieveInDto);
        return output;
    } catch (FrameworkException e) {
        // If it is, then re-throw as ApplicationsExceptions, else throw the FrameworkException.
        if (e.getCause() != null && e.getCause() instanceof ApplicationExceptions) {
            throw (ApplicationExceptions) e.getCause();
        } else if (e.getCause() != null && e.getCause() instanceof ApplicationException) {
            ApplicationExceptions appExps = new ApplicationExceptions();
            appExps.add((ApplicationException) e.getCause());
            throw appExps;
        } else
            throw e;
    } finally {
        if (uow != null)
            uow.rollback();
    }
}
Also used : ApplicationExceptions(org.jaffa.exceptions.ApplicationExceptions) ApplicationException(org.jaffa.exceptions.ApplicationException) FrameworkException(org.jaffa.exceptions.FrameworkException) UserTimeEntry(org.jaffa.applications.test.modules.time.domain.UserTimeEntry) UOW(org.jaffa.persistence.UOW)

Example 20 with ApplicationException

use of org.jaffa.exceptions.ApplicationException in project jaffa-framework by jaffa-projects.

the class UserTimeEntryMaintenanceTx method retrieve.

// .//GEN-END:_create_1_be
// .//GEN-BEGIN:_retrieve_1_be
/**
 * Returns the details for UserTimeEntry.
 * @param input The criteria based on which an object will be retrieved.
 * @throws ApplicationExceptions This will be thrown if the criteria contains invalid data.
 * @throws FrameworkException Indicates some system error.
 * @return The object details. A null indicates, the object was not found.
 */
public UserTimeEntryMaintenanceRetrieveOutDto retrieve(UserTimeEntryMaintenanceRetrieveInDto input) throws FrameworkException, ApplicationExceptions {
    UOW uow = null;
    try {
        // Print Debug Information for the input
        if (log.isDebugEnabled())
            log.debug("Input: " + (input != null ? input.toString() : null));
        // create the UOW
        uow = new UOW();
        // Preprocess the input
        preprocess(uow, input);
        // Retrieve the object
        UserTimeEntry domain = load(uow, input);
        // Convert the domain objects into the outbound dto
        UserTimeEntryMaintenanceRetrieveOutDto output = buildRetrieveOutDto(uow, input, domain);
        // Print Debug Information for the output
        if (log.isDebugEnabled())
            log.debug("Output: " + (output != null ? output.toString() : null));
        return output;
    } catch (FrameworkException e) {
        // If it is, then re-throw as ApplicationsExceptions, else throw the FrameworkException.
        if (e.getCause() != null && e.getCause() instanceof ApplicationExceptions) {
            throw (ApplicationExceptions) e.getCause();
        } else if (e.getCause() != null && e.getCause() instanceof ApplicationException) {
            ApplicationExceptions appExps = new ApplicationExceptions();
            appExps.add((ApplicationException) e.getCause());
            throw appExps;
        } else
            throw e;
    } finally {
        if (uow != null)
            uow.rollback();
    }
}
Also used : ApplicationExceptions(org.jaffa.exceptions.ApplicationExceptions) ApplicationException(org.jaffa.exceptions.ApplicationException) FrameworkException(org.jaffa.exceptions.FrameworkException) UserTimeEntry(org.jaffa.applications.test.modules.time.domain.UserTimeEntry) UOW(org.jaffa.persistence.UOW)

Aggregations

ApplicationException (org.jaffa.exceptions.ApplicationException)125 ApplicationExceptions (org.jaffa.exceptions.ApplicationExceptions)114 FrameworkException (org.jaffa.exceptions.FrameworkException)97 UOW (org.jaffa.persistence.UOW)79 InvocationTargetException (java.lang.reflect.InvocationTargetException)12 Iterator (java.util.Iterator)11 FormTemplate (org.jaffa.modules.printing.domain.FormTemplate)11 Criteria (org.jaffa.persistence.Criteria)11 Method (java.lang.reflect.Method)10 ArrayList (java.util.ArrayList)7 HashMap (java.util.HashMap)6 Map (java.util.Map)6 GraphMapping (org.jaffa.beans.moulding.mapping.GraphMapping)6 OutputCommand (org.jaffa.modules.printing.domain.OutputCommand)6 PrinterDefinition (org.jaffa.modules.printing.domain.PrinterDefinition)6 PrinterOutputType (org.jaffa.modules.printing.domain.PrinterOutputType)6 User (org.jaffa.applications.jaffa.modules.admin.domain.User)5 UserRequest (org.jaffa.applications.jaffa.modules.user.domain.UserRequest)5 UserTimeEntry (org.jaffa.applications.test.modules.time.domain.UserTimeEntry)5 Attachment (org.jaffa.components.attachment.domain.Attachment)5