Search in sources :

Example 6 with GraphDataObject

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

the class TransformerUtils method generateSerializedKey.

/**
 * This will generate a unique string for the input persistent object, based on the persistent class name and its key values.
 * The format of the generated key will be: package.classname;key1value;key2value;key3value
 * For eg:
 * For a Person persistent object having a primary key PersonId, the serialized key could be "org.example.Person;P0021"
 * For an EventEntry persistent object having a composite primary key of EventId and PersonId primary, the serialized key could be "org.example.EventEntry;E01;P0021"
 * The back-slash '\' will be the escape character.
 * Hence, if the key-value contains a '\', then it'll be replaced by '\\'
 * If the key value contains a semi-colon, then it'll be replaced by '\;'
 * <p/>
 * Note: This method will determine the key fields by looking up the getKeyFields method in the corresponding meta class for the input persistent object.
 *
 * @param source The persistent object.
 * @return a unique String for identifying the persistent object.
 * @throws ClassNotFoundException    if the Meta class for the input persistent class is not found.
 * @throws NoSuchMethodException     if 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.
 */
public static String generateSerializedKey(GraphDataObject source) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, IllegalArgumentException {
    GraphMapping mapping = MappingFactory.getInstance(source);
    Set<String> keyFields = mapping.getKeyFields();
    Class doClass = mapping.getDomainClass();
    StringBuffer buf = new StringBuffer(doClass.getName());
    if (keyFields != null && keyFields.size() > 0) {
        for (String keyFieldName : keyFields) {
            Object keyFieldValue = BeanHelper.getField(source, keyFieldName);
            if (keyFieldValue != null) {
                buf.append(';').append(quoteSerializedKeyValue(keyFieldValue.toString()));
            } else {
                String str = "SerializedKey cannot be generated. The input Graph object has a null value for its key-field " + source + ':' + keyFieldName;
                if (log.isDebugEnabled())
                    log.debug(str);
                throw new IllegalArgumentException(str);
            }
        }
    } else {
        String str = "SerializedKey cannot be generated. The input persistent object does not have any key fields defined in its meta class: " + doClass.getName();
        if (log.isDebugEnabled())
            log.debug(str);
        throw new IllegalArgumentException(str);
    }
    return buf.toString();
}
Also used : GraphDataObject(org.jaffa.soa.graph.GraphDataObject)

Example 7 with GraphDataObject

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

the class TransformerUtils method fillInKeys.

/**
 * Pass in an empty map and it fills it with Key = Value for the source
 * object. It returns false if one or more key values are null, or if this
 * object has no keys defined
 */
static boolean fillInKeys(String path, GraphDataObject source, GraphMapping mapping, Map map) throws InvocationTargetException, TransformException {
    try {
        Set keys = mapping.getKeyFields();
        boolean nullKey = false;
        if (keys == null || keys.size() == 0) {
            if (log.isDebugEnabled())
                log.debug("Object Has No KEYS! - " + source.getClass().getName());
            return false;
        }
        // Loop through all the keys get het the values
        for (Iterator k = keys.iterator(); k.hasNext(); ) {
            String keyField = (String) k.next();
            PropertyDescriptor pd = mapping.getDataFieldDescriptor(keyField);
            if (pd != null && pd.getReadMethod() != null) {
                Method m = pd.getReadMethod();
                if (!m.isAccessible())
                    m.setAccessible(true);
                Object value = m.invoke(source, new Object[] {});
                map.put(keyField, value);
                if (log.isDebugEnabled())
                    log.debug("Key " + keyField + "='" + value + "' on object '" + source.getClass().getName() + '\'');
                if (value == null) {
                    nullKey = true;
                }
            } else {
                TransformException me = new TransformException(TransformException.NO_KEY_ON_OBJECT, path, keyField, source.getClass().getName());
                log.error(me.getLocalizedMessage());
                throw me;
            }
        }
        return !nullKey;
    } catch (IllegalAccessException e) {
        TransformException me = new TransformException(TransformException.ACCESS_ERROR, path, e.getMessage());
        log.error(me.getLocalizedMessage(), e);
        throw me;
    // } catch (InvocationTargetException e) {
    // TransformException me = new TransformException(TransformException.INVOCATION_ERROR, path, e );
    // log.error(me.getLocalizedMessage(),me.getCause());
    // throw me;
    }
}
Also used : Set(java.util.Set) PropertyDescriptor(java.beans.PropertyDescriptor) Iterator(java.util.Iterator) GraphDataObject(org.jaffa.soa.graph.GraphDataObject) Method(java.lang.reflect.Method)

Example 8 with GraphDataObject

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

the class TransformerUtils method printGraph.

/**
 * Same as printGraph(Object source), except the objectStack lists all the parent
 * objects its printed, and if this is one of them, it stops. This allows detection
 * of possible infinite recusion.
 *
 * @param source      Javabean who's contents should be printed
 * @param objectStack List of objects already traversed
 * @return multi-line string of this beans properties and their values
 */
public static String printGraph(Object source, List objectStack) {
    if (source == null)
        return null;
    // Prevent infinite object recursion
    if (objectStack != null)
        if (objectStack.contains(source))
            return "Object Already Used. " + source.getClass().getName() + '@' + source.hashCode();
        else
            objectStack.add(source);
    else {
        objectStack = new ArrayList();
        objectStack.add(source);
    }
    StringBuffer out = new StringBuffer();
    out.append(source.getClass().getName());
    out.append("\n");
    try {
        BeanInfo sInfo = Introspector.getBeanInfo(source.getClass());
        PropertyDescriptor[] sDescriptors = sInfo.getPropertyDescriptors();
        if (sDescriptors != null && sDescriptors.length != 0)
            for (int i = 0; i < sDescriptors.length; i++) {
                PropertyDescriptor sDesc = sDescriptors[i];
                Method sm = sDesc.getReadMethod();
                if (sm != null && sDesc.getWriteMethod() != null) {
                    if (!sm.isAccessible())
                        sm.setAccessible(true);
                    Object sValue = sm.invoke(source, (Object[]) null);
                    out.append("  ");
                    out.append(sDesc.getName());
                    if (source instanceof GraphDataObject) {
                        if (((GraphDataObject) source).hasChanged(sDesc.getName()))
                            out.append('*');
                    }
                    out.append('=');
                    if (sValue == null)
                        out.append("<--NULL-->\n");
                    else if (sm.getReturnType().isArray() && !sm.getReturnType().getComponentType().isPrimitive()) {
                        StringBuffer out2 = new StringBuffer();
                        out2.append("Array of ");
                        out2.append(sm.getReturnType().getComponentType().getName());
                        out2.append("\n");
                        // Loop through array
                        Object[] a = (Object[]) sValue;
                        for (int j = 0; j < a.length; j++) {
                            out2.append('[');
                            out2.append(j);
                            out2.append("] ");
                            if (a[j] == null)
                                out2.append("<--NULL-->");
                            else if (GraphDataObject.class.isAssignableFrom(a[j].getClass()))
                                out2.append(((GraphDataObject) a[j]).toString(objectStack));
                            else
                                // out2.append(StringHelper.linePad(a[j].toString(), 4, " ",true));
                                out2.append(a[j].toString());
                        }
                        out.append(StringHelper.linePad(out2.toString(), 4, " ", true));
                    } else {
                        if (GraphDataObject.class.isAssignableFrom(sValue.getClass()))
                            out.append(StringHelper.linePad(((GraphDataObject) sValue).toString(objectStack), 4, " ", true));
                        else {
                            out.append(StringHelper.linePad(sValue.toString(), 4, " ", true));
                            out.append("\n");
                        }
                    }
                }
            }
    } catch (IllegalAccessException e) {
        TransformException me = new TransformException(TransformException.ACCESS_ERROR, "???", e.getMessage());
        log.error(me.getLocalizedMessage(), e);
    // throw me;
    } catch (InvocationTargetException e) {
        TransformException me = new TransformException(TransformException.INVOCATION_ERROR, "???", e);
        log.error(me.getLocalizedMessage(), me.getCause());
    // throw me;
    } catch (IntrospectionException e) {
        TransformException me = new TransformException(TransformException.INTROSPECT_ERROR, "???", e.getMessage());
        log.error(me.getLocalizedMessage(), e);
    // throw me;
    }
    return out.toString();
}
Also used : PropertyDescriptor(java.beans.PropertyDescriptor) BeanInfo(java.beans.BeanInfo) ArrayList(java.util.ArrayList) GraphDataObject(org.jaffa.soa.graph.GraphDataObject) IntrospectionException(java.beans.IntrospectionException) Method(java.lang.reflect.Method) InvocationTargetException(java.lang.reflect.InvocationTargetException) GraphDataObject(org.jaffa.soa.graph.GraphDataObject)

Example 9 with GraphDataObject

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

the class GraphCreateThread method run.

@Override
public void run() {
    UserContextWrapper ucw = null;
    ApplicationExceptions appExps = new ApplicationExceptions();
    try {
        synchronized (this) {
            ucw = UserContextWrapperFactory.instance(userId);
        }
        List<GraphDataObject> graphs = new ArrayList<GraphDataObject>();
        graphs.add(this.graph);
        GraphService service = (GraphService) serviceClazz.newInstance();
        Object graphArray = Array.newInstance(graph.getClass(), 1);
        Array.set(graphArray, 0, graph);
        Method m = serviceClazz.getDeclaredMethod("update", graphArray.getClass());
        GraphUpdateResponse[] responses = (GraphUpdateResponse[]) m.invoke(serviceClazz.newInstance(), graphArray);
        if (responses != null && responses.length > 0) {
            for (GraphUpdateResponse response : responses) {
                ServiceError[] faults = response.getErrors();
                if (faults != null && faults.length > 0) {
                    for (ServiceError fault : faults) {
                        appExps.add(new ApplicationException("error", new String[] { fault.getLocalizedMessage() }));
                    }
                }
                synchronized (this) {
                    test.getUpdateResponses().add(response);
                }
            }
        }
        if (appExps.size() > 0)
            throw appExps;
    } catch (ApplicationExceptions | UserSessionSetupException | InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
        log.error(e);
    } finally {
        synchronized (this) {
            if (ucw != null)
                ucw.unsetContext();
        }
    }
}
Also used : ServiceError(org.jaffa.soa.graph.ServiceError) ApplicationExceptions(org.jaffa.exceptions.ApplicationExceptions) GraphDataObject(org.jaffa.soa.graph.GraphDataObject) ArrayList(java.util.ArrayList) Method(java.lang.reflect.Method) UserSessionSetupException(org.jaffa.presentation.portlet.session.UserSessionSetupException) InvocationTargetException(java.lang.reflect.InvocationTargetException) GraphService(org.jaffa.soa.dataaccess.GraphService) ApplicationException(org.jaffa.exceptions.ApplicationException) UserContextWrapper(org.jaffa.modules.user.services.UserContextWrapper) GraphDataObject(org.jaffa.soa.graph.GraphDataObject) GraphUpdateResponse(org.jaffa.soa.graph.GraphUpdateResponse)

Example 10 with GraphDataObject

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

the class TransformerUtils method domainObjectChangedTest.

/**
 * Performs the dirty-read check to ensure that the underlying record in the database hasn't
 * been changed by another user, while the current user has been trying to modify it.
 */
private static void domainObjectChangedTest(String path, GraphDataObject source, GraphMapping mapping, IPersistent domainObject) throws InstantiationException, IllegalAccessException, InvocationTargetException, FrameworkException, ApplicationExceptions {
    if (source.getPerformDirtyReadCheck() != null && source.getPerformDirtyReadCheck() && mapping.getDirtyReadDataFieldName() != null) {
        if (log.isDebugEnabled())
            log.debug("Performing dirty-read check for " + domainObject);
        Object lastKnownValue = getProperty(mapping.getDataFieldDescriptor(mapping.getDirtyReadDataFieldName()), source);
        Object currentValue = getProperty(mapping.getDomainFieldDescriptor(mapping.getDirtyReadDataFieldName()), domainObject);
        if (lastKnownValue == null ? currentValue != null : !lastKnownValue.equals(currentValue)) {
            if (log.isDebugEnabled())
                log.debug("Dirty-read check failed: lastKnownValue='" + lastKnownValue + "', currentValue='" + currentValue + '\'');
            if (!domainObject.isDatabaseOccurence()) {
                if (log.isDebugEnabled())
                    log.debug("Dirty-read check failed: " + domainObject + " may have been removed.");
                throw new ApplicationExceptions(new ApplicationExceptionWithContext(path, new ApplicationException(DomainObjectChangedException.OBJECT_REMOVED, null, null)));
            } else {
                String[] errorParamNames = mapping.getDirtyReadErrorParams();
                Object[] errorParamValues = new Object[errorParamNames.length];
                try {
                    for (int i = 0; i < errorParamNames.length; i++) errorParamValues[i] = BeanHelper.getField(domainObject, errorParamNames[i]);
                } catch (Exception e) {
                    log.warn("Error in creation of the argument array to pass to the DomainObjectChangedException from the list: " + Arrays.toString(mapping.getDirtyReadErrorParams()), e);
                }
                throw new ApplicationExceptions(new ApplicationExceptionWithContext(path, new DomainObjectChangedException(mapping.getDirtyReadErrorLabelToken(), errorParamValues, null)));
            }
        } else {
            if (log.isDebugEnabled())
                log.debug("Dirty-read check succeeded. Both lastKnownValue and currentValue equal '" + currentValue + '\'');
        }
    }
}
Also used : ApplicationExceptions(org.jaffa.exceptions.ApplicationExceptions) ApplicationException(org.jaffa.exceptions.ApplicationException) ApplicationExceptionWithContext(org.jaffa.exceptions.ApplicationExceptionWithContext) GraphDataObject(org.jaffa.soa.graph.GraphDataObject) DomainObjectChangedException(org.jaffa.exceptions.DomainObjectChangedException) DomainObjectChangedException(org.jaffa.exceptions.DomainObjectChangedException) FrameworkException(org.jaffa.exceptions.FrameworkException) ApplicationException(org.jaffa.exceptions.ApplicationException) DomainObjectNotFoundException(org.jaffa.exceptions.DomainObjectNotFoundException) IntrospectionException(java.beans.IntrospectionException) InvocationTargetException(java.lang.reflect.InvocationTargetException) MultipleDomainObjectsFoundException(org.jaffa.exceptions.MultipleDomainObjectsFoundException)

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