Search in sources :

Example 1 with GraphDataObject

use of org.jaffa.soa.graph.GraphDataObject in project jaffa-framework by jaffa-projects.

the class NotNullBeanConverter method convertOutbound.

/* (non-Javadoc)
     * @see org.directwebremoting.Converter#convertOutbound(java.lang.Object, org.directwebremoting.OutboundContext)
     *
     * Copied from BasicObjectConverter
     */
public OutboundVariable convertOutbound(Object data, OutboundContext outctx) throws MarshallException {
    // Where we collect out converted children
    Map ovs = new TreeMap();
    // We need to do this before collecing the children to save recurrsion
    ObjectOutboundVariable ov = new ObjectOutboundVariable(outctx);
    outctx.put(data, ov);
    try {
        Map properties = getPropertyMapFromObject(data, true, false);
        for (Iterator it = properties.entrySet().iterator(); it.hasNext(); ) {
            Map.Entry entry = (Map.Entry) it.next();
            String name = (String) entry.getKey();
            Property property = (Property) entry.getValue();
            Object value = property.getValue(data);
            if (value != null || (data instanceof GraphDataObject && ((GraphDataObject) data).hasChanged(name))) {
                // Added check to exclude null fields
                OutboundVariable nested = getConverterManager().convertOutbound(value, outctx);
                ovs.put(name, nested);
            }
        }
        // Add the className to the object
        if (data != null) {
            String className = data.getClass().getSimpleName();
            OutboundVariable var = getConverterManager().convertOutbound(className, outctx);
            ovs.put("className", var);
        }
    } catch (MarshallException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new MarshallException(data.getClass(), ex);
    }
    ov.init(ovs, getJavascript());
    return ov;
}
Also used : OutboundVariable(org.directwebremoting.extend.OutboundVariable) ObjectOutboundVariable(org.directwebremoting.dwrp.ObjectOutboundVariable) GraphDataObject(org.jaffa.soa.graph.GraphDataObject) TreeMap(java.util.TreeMap) MarshallException(org.directwebremoting.extend.MarshallException) ObjectOutboundVariable(org.directwebremoting.dwrp.ObjectOutboundVariable) MarshallException(org.directwebremoting.extend.MarshallException) Iterator(java.util.Iterator) GraphDataObject(org.jaffa.soa.graph.GraphDataObject) TreeMap(java.util.TreeMap) Map(java.util.Map) Property(org.directwebremoting.extend.Property)

Example 2 with GraphDataObject

use of org.jaffa.soa.graph.GraphDataObject in project jaffa-framework by jaffa-projects.

the class DataTransformer method updateGraph.

/**
 * 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 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
 * @return In VALIDATE_ONLY mode the source object will be returned with default data. Else a GraphDataObject with just the key-fields of the root object will be returned if that object was newly created. Else a null will be returned.
 * @throws ApplicationExceptions Thrown if one or more application logic errors are generated during moulding
 * @throws FrameworkException    Thrown if any runtime moulding error has occured.
 */
private static GraphDataObject updateGraph(String path, GraphDataObject source, UOW uow, ITransformationHandler handler, Mode mode, GraphDataObject newGraph) throws ApplicationExceptions, FrameworkException {
    if (log.isDebugEnabled())
        log.debug("Update Bean " + path);
    if (source.getDeleteObject() != null && source.getDeleteObject()) {
        if (mode == Mode.VALIDATE_ONLY) {
            if (log.isDebugEnabled())
                log.debug("The 'deleteObject' property is true. No prevalidations will be performed. The input object will be returned as is.");
            return source;
        } else {
            if (log.isDebugEnabled())
                log.debug("The 'deleteObject' property is true. Invoking deleteGraph()");
            deleteGraph(path, source, uow, handler);
            return null;
        }
    } else {
        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
            // In CLONE mode, get the keys from the new graph, and force the creation of the domain object
            boolean gotKeys = false;
            if (mode == Mode.CLONE) {
                if (newGraph != null)
                    gotKeys = TransformerUtils.fillInKeys(path, newGraph, mapping, keys);
            } else
                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(TransformerUtils.findDomainLabel(doClass)));
                // 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);
                if (domainObject != null && mode == Mode.CLONE)
                    throw new ApplicationExceptions(new DuplicateKeyException(TransformerUtils.findDomainLabel(doClass)));
            } else {
                if (log.isDebugEnabled())
                    log.debug("Object " + path + " has either missing or null key values - Assume Create is needed");
            }
            // Create object if not found
            boolean createMode = false;
            if (domainObject == null) {
                // In MASS_UPDATE mode, error if DO not found
                if (mode == Mode.MASS_UPDATE)
                    throw new ApplicationExceptions(new DomainObjectNotFoundException(TransformerUtils.findDomainLabel(doClass)));
                // NEW OBJECT, create and reflect keys
                if (log.isDebugEnabled())
                    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();
                    if (mapping.isReadOnly(keyField))
                        continue;
                    Object value = keys.get(keyField);
                    TransformerUtils.updateProperty(mapping.getDomainFieldDescriptor(keyField), value, domainObject);
                }
                createMode = true;
            } else {
                if (log.isDebugEnabled())
                    log.debug("Found DO '" + mapping.getDomainClassShortName() + "' with key,");
            }
            // Now update all domain fields
            TransformerUtils.updateBeanData(path, source, uow, handler, mapping, domainObject, mode, newGraph);
            // Invoke the changeDone trigger
            if (handler != null && handler.isChangeDone()) {
                for (ITransformationHandler transformationHandler : handler.getTransformationHandlers()) {
                    transformationHandler.changeDone(path, source, domainObject, uow);
                }
            }
            // Return an appropriate output
            if (mode == Mode.VALIDATE_ONLY) {
                // In VALIDATE_ONLY mode, return the input graph (with defaulted data)
                return source;
            } else if (createMode) {
                // In create-mode, Create a new graph and stamp just the keys
                GraphDataObject outputGraph = source.getClass().newInstance();
                for (Iterator i = keys.keySet().iterator(); i.hasNext(); ) {
                    String keyField = (String) i.next();
                    PropertyDescriptor pd = mapping.getDomainFieldDescriptor(keyField);
                    if (pd != null && pd.getReadMethod() != null) {
                        Method m = pd.getReadMethod();
                        if (!m.isAccessible())
                            m.setAccessible(true);
                        Object value = m.invoke(domainObject, (Object[]) null);
                        AccessibleObject accessibleObject = mapping.getDataMutator(keyField);
                        setValue(accessibleObject, outputGraph, value);
                    } else {
                        TransformException me = new TransformException(TransformException.NO_KEY_ON_OBJECT, path, keyField, source.getClass().getName());
                        log.error(me.getLocalizedMessage());
                        throw me;
                    }
                }
                return outputGraph;
            } else {
                // In update-mode, return a null
                return null;
            }
        } 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;
        }
    }
}
Also used : LinkedHashMap(java.util.LinkedHashMap) IPersistent(org.jaffa.persistence.IPersistent) Iterator(java.util.Iterator) AccessibleObject(java.lang.reflect.AccessibleObject) PropertyDescriptor(java.beans.PropertyDescriptor) GraphDataObject(org.jaffa.soa.graph.GraphDataObject) Method(java.lang.reflect.Method) InvocationTargetException(java.lang.reflect.InvocationTargetException) 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 3 with GraphDataObject

use of org.jaffa.soa.graph.GraphDataObject 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 4 with GraphDataObject

use of org.jaffa.soa.graph.GraphDataObject in project jaffa-framework by jaffa-projects.

the class DataTransformer method buildGraphFromDomain.

/**
 * Mould data from domain object and its related objects into a new JavaBean based
 * domain object graph, based on the defined mapping rules.
 *
 * @param source           Source object to mould data from, typically extends Persistent
 * @param target           Target object to mould data to, typically extends GraphDataObject
 * @param graph            The mapping class with the rules of how to map this source object
 * @param filter           Filter object that it is used to control what fields are populated or the target objects
 * @param objectPath       The path of this object being processed. This identifies possible parent
 *                         and/or indexed entries where this object is contained.
 * @param includeKeys      true if key fields should be included in results regardless of the filters
 * @param originalCriteria the original graph criteria.
 * @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 buildGraphFromDomain(Object source, Object target, GraphMapping graph, MappingFilter filter, String objectPath, boolean includeKeys, GraphCriteria originalCriteria, ITransformationHandler handler) throws ApplicationExceptions, FrameworkException {
    if (graph == null)
        graph = MappingFactory.getInstance(target);
    boolean useQueryDomain = graph.getQueryDomainClass() != null && source.getClass().isAssignableFrom(graph.getQueryDomainClass());
    // throw new InstantiationException("A GraphMapping must be supplied");
    if (filter == null)
        filter = MappingFilter.getInstance(graph);
    try {
        // get list of target fileds to populate
        String[] tFields = graph.getDataFieldNames();
        if (tFields != null && tFields.length != 0)
            for (int i = 0; i < tFields.length; i++) {
                // Try to map a source to a target
                String tName = tFields[i];
                String fullName = tName;
                if (objectPath != null)
                    fullName = objectPath + "." + fullName;
                if (filter == null || filter.isFieldIncluded(fullName) || (includeKeys && graph.isKeyField(tName))) {
                    String sName = graph.getDomainFieldName(tName);
                    AccessibleObject tAccessibleObject = graph.getDataMutator(tName);
                    PropertyDescriptor tDesc = graph.getDataFieldDescriptor(tName);
                    PropertyDescriptor sDesc = useQueryDomain ? graph.getQueryDomainFieldDescriptor(tName) : graph.getDomainFieldDescriptor(tName);
                    if (useQueryDomain && sDesc == null)
                        continue;
                    // GraphObject descriptor with a setter, and a DO descriptor with a getter
                    if (sDesc == null)
                        log.error("No Getter for " + tName + " in path " + fullName);
                    // incase getter is not public, make it available
                    Method sm = sDesc.getReadMethod();
                    if (!sm.isAccessible())
                        sm.setAccessible(true);
                    // Set the value if the source and target are the same datatype
                    Class tClass = tDesc.getPropertyType();
                    Class sClass = sDesc.getPropertyType();
                    if (tClass.isAssignableFrom(sClass)) {
                        // Get the value being copied
                        Object sValue = sm.invoke(source, (Object[]) null);
                        setValue(tAccessibleObject, target, sValue);
                        if (log.isDebugEnabled())
                            log.debug("Set " + tName + " = " + sValue);
                    // See if there is a datatype mapper for these classes
                    } else if (DataTypeMapper.instance().isMappable(sClass, tClass)) {
                        // Get the value being copied
                        Object sValue = sm.invoke(source, (Object[]) null);
                        if (sValue != null) {
                            sValue = DataTypeMapper.instance().map(sValue, tClass);
                            if (log.isDebugEnabled())
                                log.debug("Set " + tName + " = " + sValue);
                        }
                        setValue(tAccessibleObject, target, sValue);
                    // See if target is a GraphObject, this could be a foreign object or one-to-one relationship...
                    } else if (GraphDataObject.class.isAssignableFrom(tClass) && IPersistent.class.isAssignableFrom(sClass)) {
                        // Get the mapper for the related GraphObject, if it has keys, it must be a foriegn object
                        if (graph.isForeignField(tName)) {
                            // look at foreign key fields, and make sure they are not null
                            List foreignKeys = graph.getForeignKeys(tName);
                            List foreignKeyValues = new ArrayList();
                            boolean nullKey = false;
                            for (Iterator k = foreignKeys.iterator(); k.hasNext(); ) {
                                String doProp = (String) k.next();
                                Object value = null;
                                PropertyDescriptor doPd = graph.getRealDomainFieldDescriptor(doProp);
                                if (doPd != null && doPd.getReadMethod() != null) {
                                    Method m = doPd.getReadMethod();
                                    if (!m.isAccessible())
                                        m.setAccessible(true);
                                    value = m.invoke(source, new Object[] {});
                                    if (value == null)
                                        nullKey = true;
                                    foreignKeyValues.add(value);
                                } else {
                                    throw new TransformException(TransformException.INVALID_FK_MAPPING, objectPath, doProp, graph.getDomainClassShortName());
                                }
                            }
                            if (nullKey) {
                                if (log.isDebugEnabled())
                                    log.debug("Did not create skeleton object '" + tClass.getName() + "': one or more foreign key values missing.");
                            } else {
                                // Create the foreign object
                                if (log.isDebugEnabled())
                                    log.debug("Creating foreign object - " + tClass.getName());
                                Object newGDO = newGraphDataObject(tClass);
                                boolean createSkeleton = true;
                                // Only retrieve related domain object and introspect if need
                                if (filter.areSubFieldsIncluded(fullName)) {
                                    // read object and introspect all
                                    if (log.isDebugEnabled())
                                        log.debug("Read foreign object '" + fullName + "' and mold");
                                    try {
                                        Object sValue = sm.invoke(source, (Object[]) null);
                                        if (sValue != null) {
                                            DataTransformer.buildGraphFromDomain(sValue, newGDO, null, filter, fullName, true, originalCriteria, handler);
                                            createSkeleton = false;
                                        }
                                    } catch (InvocationTargetException e) {
                                        // If the foreign object is not found, create the skeleton
                                        if (e.getCause() != null && e.getCause() instanceof InvalidForeignKeyException) {
                                            if (log.isDebugEnabled())
                                                log.debug("All foreign keys present, but foreign object does not exist", e);
                                        } else
                                            throw e;
                                    }
                                }
                                if (createSkeleton) {
                                    // just set foreign keys from current object
                                    if (log.isDebugEnabled())
                                        log.debug("Set keys on skeleton foreign object only");
                                    GraphMapping graph2 = MappingFactory.getInstance(newGDO);
                                    Set keys = graph2.getKeyFields();
                                    if (keys == null || keys.size() != foreignKeyValues.size()) {
                                        throw new TransformException(TransformException.MISMATCH_FK_MAPPING, objectPath, target.getClass().getName(), newGDO.getClass().getName());
                                    }
                                    int k2 = 0;
                                    // Look through all the foreign keys on the skeleton object
                                    for (Iterator k = keys.iterator(); k.hasNext(); k2++) {
                                        String keyField = (String) k.next();
                                        Object keyValue = foreignKeyValues.get(k2);
                                        AccessibleObject accessibleObject = graph2.getDataMutator(keyField);
                                        if (accessibleObject != null) {
                                            setValue(accessibleObject, newGDO, keyValue);
                                        } else {
                                            throw new TransformException(TransformException.CANT_SET_KEY_FIELD, objectPath, keyField, newGDO.getClass().getName());
                                        }
                                    }
                                }
                                setValue(tAccessibleObject, target, newGDO);
                                if (log.isDebugEnabled())
                                    log.debug("Set " + tName + " = " + newGDO);
                            }
                        } else {
                            // This is not a foreign object, must be a related object
                            if (filter.areSubFieldsIncluded(fullName)) {
                                // Create the related object
                                if (log.isDebugEnabled())
                                    log.debug("Creating One-To-One object - " + tClass.getName());
                                Object newGDO = newGraphDataObject(tClass);
                                // read object and introspect all
                                if (log.isDebugEnabled())
                                    log.debug("Read related object '" + fullName + "' and mold");
                                Object sValue = sm.invoke(source, (Object[]) null);
                                if (sValue != null) {
                                    DataTransformer.buildGraphFromDomain(sValue, newGDO, null, filter, fullName, false, originalCriteria, handler);
                                    setValue(tAccessibleObject, target, newGDO);
                                    if (log.isDebugEnabled())
                                        log.debug("Set " + tName + " = " + newGDO);
                                } else {
                                    if (log.isDebugEnabled())
                                        log.debug("Related object '" + fullName + "' not found. Ignore it!");
                                }
                            } else {
                                if (log.isDebugEnabled())
                                    log.debug("No subfields for object " + fullName + " included. Object not retrieved");
                            }
                        }
                    // END-related object
                    // See if Target may be an array of GraphObject's
                    } else if (tClass.isArray() && GraphDataObject.class.isAssignableFrom(tClass.getComponentType()) && filter.areSubFieldsIncluded(fullName)) {
                        if (log.isDebugEnabled())
                            log.debug("Target is an array of GraphObject's");
                        if (sClass.isArray() && IPersistent.class.isAssignableFrom(sClass.getComponentType())) {
                            if (log.isDebugEnabled()) {
                                log.debug("Source is an array of Persistent Objects");
                                log.debug("Read related objects '" + fullName + "' and mold");
                            }
                            Object[] sArray = findRelatedObjects(source, sClass, sm, handler, originalCriteria, fullName);
                            if (sArray != null && sArray.length > 0) {
                                Object[] tArray = (Object[]) Array.newInstance(tClass.getComponentType(), sArray.length);
                                if (log.isDebugEnabled())
                                    log.debug("Translate Array of Size " + sArray.length);
                                for (int j = 0; j < sArray.length; j++) {
                                    Object newGDO = newGraphDataObject(tClass.getComponentType());
                                    DataTransformer.buildGraphFromDomain(sArray[j], newGDO, null, filter, fullName, false, originalCriteria, handler);
                                    tArray[j] = newGDO;
                                    if (log.isDebugEnabled())
                                        log.debug("Add to array [" + j + "] : " + newGDO);
                                }
                                setValue(tAccessibleObject, target, tArray);
                                if (log.isDebugEnabled())
                                    log.debug("Set Array " + tName);
                            } else {
                                if (log.isDebugEnabled())
                                    log.debug("Source Array is empty! Do Nothing");
                            }
                        }
                    // source is DO array
                    // Error... No way to map property
                    } else {
                        String err = "Can't Mold Property " + fullName + " from " + sClass.getName() + " to " + tClass.getName();
                        log.error(err);
                        throw new RuntimeException(err);
                    }
                }
            // is included in filtered fields
            }
        // By default all the domain-mapped flex fields will be loaded; unless excluded by a rule
        if (source instanceof IFlexFields && target instanceof IFlexFields) {
            String fullName = (objectPath != null ? objectPath + '.' : "") + "flexBean";
            if (filter == null || filter.isFieldIncluded(fullName)) {
                if (log.isDebugEnabled())
                    log.debug("Loading FlexBean " + fullName);
                FlexBean sFlexBean = ((IFlexFields) source).getFlexBean();
                FlexBean tFlexBean = ((IFlexFields) target).getFlexBean();
                if (sFlexBean != null && tFlexBean != null) {
                    for (DynaProperty flexProperty : sFlexBean.getDynaClass().getDynaProperties()) {
                        String name = flexProperty.getName();
                        Boolean include = filter.includeField(fullName + '.' + name);
                        if (include != null ? include : ((FlexProperty) flexProperty).getFlexInfo().getProperty("domain-mapping") != null) {
                            Object value = sFlexBean.get(name);
                            if (value != null) {
                                if (log.isDebugEnabled())
                                    log.debug("Loaded flex field '" + name + '=' + value + '\'');
                                tFlexBean.set(name, value);
                            }
                        }
                    }
                }
            }
        }
        // Clear changed fields on updated GraphObject
        if (target != null && target instanceof GraphDataObject)
            ((GraphDataObject) target).clearChanges();
        // Invoke the handler
        if (handler != null) {
            if (log.isDebugEnabled()) {
                log.debug("Invoking the endBeanLoad on the handler");
            }
            for (ITransformationHandler transformationHandler : handler.getTransformationHandlers()) {
                transformationHandler.endBeanLoad(objectPath, source, target, filter, originalCriteria);
            }
        }
    } catch (ApplicationException e) {
        throw new ApplicationExceptions(e);
    } catch (IllegalAccessException e) {
        TransformException me = new TransformException(TransformException.ACCESS_ERROR, objectPath, 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, objectPath, e);
        log.error(me.getLocalizedMessage(), me.getCause());
        throw me;
    } catch (InstantiationException e) {
        TransformException me = new TransformException(TransformException.INSTANTICATION_ERROR, objectPath, e.getMessage());
        log.error(me.getLocalizedMessage(), e);
        throw me;
    }
}
Also used : Set(java.util.Set) ArrayList(java.util.ArrayList) IPersistent(org.jaffa.persistence.IPersistent) Iterator(java.util.Iterator) AccessibleObject(java.lang.reflect.AccessibleObject) ArrayList(java.util.ArrayList) List(java.util.List) PropertyDescriptor(java.beans.PropertyDescriptor) InvalidForeignKeyException(org.jaffa.datatypes.exceptions.InvalidForeignKeyException) GraphDataObject(org.jaffa.soa.graph.GraphDataObject) Method(java.lang.reflect.Method) IFlexFields(org.jaffa.flexfields.IFlexFields) InvocationTargetException(java.lang.reflect.InvocationTargetException) FlexBean(org.jaffa.flexfields.FlexBean) DynaProperty(org.apache.commons.beanutils.DynaProperty) GraphDataObject(org.jaffa.soa.graph.GraphDataObject) AccessibleObject(java.lang.reflect.AccessibleObject)

Example 5 with GraphDataObject

use of org.jaffa.soa.graph.GraphDataObject in project jaffa-framework by jaffa-projects.

the class TransformerUtils method deleteBeanData.

static void deleteBeanData(String path, GraphDataObject source, UOW uow, ITransformationHandler handler, GraphMapping mapping, IPersistent domainObject) throws InstantiationException, IllegalAccessException, InvocationTargetException, ApplicationExceptions, FrameworkException {
    try {
        // Ensure the domain object has not been modified
        domainObjectChangedTest(path, source, mapping, domainObject);
        List<ITransformationHandler> handlers = null;
        if (handler != null) {
            handlers = handler.getTransformationHandlers();
        }
        // Fire 'startBean' handler
        if (handlers != null) {
            for (ITransformationHandler transformationHandler : handlers) {
                transformationHandler.startBean(path, source, domainObject);
            }
        }
        // ----------------------------------------------------------------
        // Now loop through children, if there is one, delete it, and leave parent alone
        boolean deleteChild = false;
        // Reflect any related objects
        for (Iterator it = mapping.getRelatedFields().iterator(); it.hasNext(); ) {
            String field = (String) it.next();
            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?
                        GraphDataObject dao = (GraphDataObject) values[i];
                        if (dao != null) {
                            deleteChild = true;
                            deleteChildBean(path + '.' + field + '[' + i + ']', dao, uow, handler, domainObject, mapping, field);
                        }
                    }
                } else {
                    // The related field is a single object (one-to-many)
                    // Assumes its a DAO....what else could it be?
                    GraphDataObject dao = (GraphDataObject) value;
                    deleteChild = true;
                    deleteChildBean(path + '.' + field, dao, uow, handler, domainObject, mapping, field);
                }
            }
        }
        // Delete this record, as it had no children
        if (!deleteChild) {
            if (log.isDebugEnabled())
                log.debug("UOW.Delete Domain Object");
            // Fire 'startBeanDelete' handler
            if (handlers != null) {
                for (ITransformationHandler transformationHandler : handlers) {
                    transformationHandler.startBeanDelete(path, source, domainObject);
                }
            }
            uow.delete(domainObject);
            if (handlers != null) {
                for (ITransformationHandler transformationHandler : handlers) {
                    transformationHandler.setChangeDone(true);
                }
            }
            // Fire 'endBeanDelete' handler
            if (handlers != null) {
                for (ITransformationHandler transformationHandler : handlers) {
                    transformationHandler.endBeanDelete(path, source, domainObject);
                }
            }
        }
        // Fire 'endBean' handler
        if (handlers != null) {
            for (ITransformationHandler transformationHandler : handlers) {
                transformationHandler.endBean(path, source, domainObject);
            }
        }
    } catch (SkipTransformException e) {
        if (log.isDebugEnabled())
            log.debug("Processing of " + path + " will be skipped", e);
    } catch (ApplicationException e) {
        throw new ApplicationExceptions(e);
    }
}
Also used : ApplicationException(org.jaffa.exceptions.ApplicationException) ApplicationExceptions(org.jaffa.exceptions.ApplicationExceptions) Iterator(java.util.Iterator) GraphDataObject(org.jaffa.soa.graph.GraphDataObject) GraphDataObject(org.jaffa.soa.graph.GraphDataObject)

Aggregations

GraphDataObject (org.jaffa.soa.graph.GraphDataObject)13 Method (java.lang.reflect.Method)9 Iterator (java.util.Iterator)9 InvocationTargetException (java.lang.reflect.InvocationTargetException)8 ApplicationExceptions (org.jaffa.exceptions.ApplicationExceptions)6 PropertyDescriptor (java.beans.PropertyDescriptor)5 Map (java.util.Map)5 IPersistent (org.jaffa.persistence.IPersistent)5 ArrayList (java.util.ArrayList)4 LinkedHashMap (java.util.LinkedHashMap)4 ApplicationException (org.jaffa.exceptions.ApplicationException)4 AccessibleObject (java.lang.reflect.AccessibleObject)3 Set (java.util.Set)3 ApplicationExceptionWithContext (org.jaffa.exceptions.ApplicationExceptionWithContext)3 DomainObjectNotFoundException (org.jaffa.exceptions.DomainObjectNotFoundException)3 FrameworkException (org.jaffa.exceptions.FrameworkException)3 MultipleDomainObjectsFoundException (org.jaffa.exceptions.MultipleDomainObjectsFoundException)3 IntrospectionException (java.beans.IntrospectionException)2 List (java.util.List)2 DynaProperty (org.apache.commons.beanutils.DynaProperty)2