Search in sources :

Example 6 with FieldMetaData

use of org.jaffa.metadata.FieldMetaData in project jaffa-framework by jaffa-projects.

the class PersistentHelper method getFieldMetaData.

/**
 * Returns the FieldMetaData object from the meta class for the input persistent class for the input field.
 * @param persistentClassName The name of the persistent class.
 * @param fieldName the field name.
 * @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[] getFieldMetaData(String fieldName)' method.
 * @throws IllegalAccessException if the 'public static FieldMetaData[] getFieldMetaData(String fieldName)' method of the Meta class enforces Java language access control and the underlying method is inaccessible.
 * @throws InvocationTargetException if the 'public static FieldMetaData[] getFieldMetaData(String fieldName)' method of the Meta class throws an exception.
 */
public static FieldMetaData getFieldMetaData(String persistentClassName, String fieldName) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
    // Get the meta class
    Class metaClass = getMetaClass(persistentClassName);
    // Get a handle on the method for retrieving the FieldMetaData from the meta class
    Method m = metaClass.getMethod("getFieldMetaData", new Class[] { String.class });
    // Ensure that the method is static and that the method returns FieldMetaData
    if (Modifier.isStatic(m.getModifiers()) && m.getReturnType() == FieldMetaData.class) {
        // Now invoke the method to get the FieldMetaData object
        return (FieldMetaData) m.invoke(null, new Object[] { StringHelper.getUpper1(fieldName) });
    } else {
        String str = "The getFieldMetaData() method in the meta class for the persistent class " + persistentClassName + " should be static and return an instance of the FieldMetaData class";
        if (log.isDebugEnabled())
            log.debug(str);
        throw new NoSuchMethodException(str);
    }
}
Also used : FieldMetaData(org.jaffa.metadata.FieldMetaData) Method(java.lang.reflect.Method)

Example 7 with FieldMetaData

use of org.jaffa.metadata.FieldMetaData in project jaffa-framework by jaffa-projects.

the class FinderMetaDataHelper method determinePropertyMetaData.

/**
 * Returns meta data for the input field.
 */
private static Map<String, String> determinePropertyMetaData(Class outputClass, Class domainClass, GraphMapping graphMapping, String fieldName) throws Exception {
    IPropertyRuleIntrospector i = RulesEngineFactory.getRulesEngine().getPropertyRuleIntrospector(outputClass, fieldName);
    // Apply an optional wrapper that also takes the FieldMetaData into account
    try {
        FieldMetaData fieldMetaData = PersistentHelper.getFieldMetaData(domainClass.getName(), graphMapping != null ? graphMapping.getDomainFieldName(fieldName) : fieldName);
        i = new PropertyRuleIntrospectorUsingFieldMetaData(i, fieldMetaData);
    } catch (Exception ignore) {
    }
    // A Map to hold the various attributes of the field
    Map<String, String> m = new LinkedHashMap<String, String>();
    // determine type
    String type = toJsType(i.getPropertyType());
    if (type == null) {
        // A foreign-key on a Graph will typically be modelled as another Graph, in which case obtain the datatype for that field from the domainClass
        type = toJsType(RulesEngineFactory.getRulesEngine().getPropertyRuleIntrospector(domainClass, fieldName).getPropertyType());
    }
    // Ignore field having unsupported propertyType
    if (type == null)
        return null;
    m.put("type", '\'' + type + '\'');
    // determine label
    String label = i.getLabel();
    if (label == null) {
        label = StringHelper.getSpace(StringHelper.getUpper1(fieldName));
    } else {
        String tmp = label.substring(1);
        tmp = tmp.substring(0, tmp.length() - 1);
        m.put("labelToken", '\'' + tmp + '\'');
        label = StringHelper.escapeJavascript(MessageHelper.replaceTokens(label));
    }
    m.put("label", '\'' + label + '\'');
    // determine maxLength
    Integer maxLength = i.getMaxLength();
    if (maxLength != null)
        m.put("maxLength", maxLength.toString());
    // sortable
    m.put("sortable", "true");
    // determine hidden
    Boolean hidden = i.isHidden();
    if (hidden) {
        m.put("hidden", "true");
        m.put("alwaysHidden", "true");
    }
    // determine caseType
    String caseType = i.getCaseType();
    if (caseType != null && caseType.toLowerCase().startsWith("upper"))
        caseType = "UpperCase";
    else if (caseType != null && caseType.toLowerCase().startsWith("lower"))
        caseType = "LowerCase";
    else
        caseType = null;
    if (caseType != null)
        m.put("caseType", '\'' + caseType + '\'');
    return m;
}
Also used : IPropertyRuleIntrospector(org.jaffa.rules.IPropertyRuleIntrospector) FieldMetaData(org.jaffa.metadata.FieldMetaData) PropertyRuleIntrospectorUsingFieldMetaData(org.jaffa.metadata.PropertyRuleIntrospectorUsingFieldMetaData) PropertyRuleIntrospectorUsingFieldMetaData(org.jaffa.metadata.PropertyRuleIntrospectorUsingFieldMetaData) LinkedHashMap(java.util.LinkedHashMap)

Example 8 with FieldMetaData

use of org.jaffa.metadata.FieldMetaData in project jaffa-framework by jaffa-projects.

the class PersistentHelper method checkMandatoryFields.

/**
 * This will check all the mandatory fields of the persistent object.
 * It utilises the corresponding Meta class for determining the mandatory fields.
 * @param object The persistent object.
 * @throws ApplicationExceptions Will contain a collection of MandatoryFieldExceptions for the all the mandatory fields which do not have values.
 * @throws FrameworkException If any framework error occurs.
 */
public static void checkMandatoryFields(IPersistent object) throws ApplicationExceptions, FrameworkException {
    try {
        FieldMetaData[] fields = getMandatoryFields(object.getClass().getName());
        if (fields != null && fields.length > 0) {
            ApplicationExceptions appExps = new ApplicationExceptions();
            for (int i = 0; i < fields.length; i++) {
                FieldMetaData fieldMetaData = fields[i];
                Object fieldValue = BeanHelper.getField(object, fieldMetaData.getName());
                if (fieldValue == null || (fieldValue instanceof String && ((String) fieldValue).length() == 0)) {
                    if (log.isDebugEnabled())
                        log.debug("Mandatory validation failed for the field " + fieldMetaData.getName());
                    appExps.add(new MandatoryFieldException(fieldMetaData.getLabelToken()));
                }
            }
            if (appExps.size() > 0)
                throw appExps;
        }
    } catch (ClassNotFoundException e) {
        String str = "Exception thrown while validating the domain object " + object;
        log.error(str, e);
        throw new DomainObjectValidationException(null, e);
    } catch (NoSuchMethodException e) {
        String str = "Exception thrown while validating the domain object " + object;
        log.error(str, e);
        throw new DomainObjectValidationException(null, e);
    } catch (IllegalAccessException e) {
        String str = "Exception thrown while validating the domain object " + object;
        log.error(str, e);
        throw new DomainObjectValidationException(null, e);
    } catch (InvocationTargetException e) {
        String str = "Exception thrown while validating the domain object " + object;
        log.error(str, e);
        throw new DomainObjectValidationException(null, e);
    }
}
Also used : FieldMetaData(org.jaffa.metadata.FieldMetaData) ApplicationExceptions(org.jaffa.exceptions.ApplicationExceptions) MandatoryFieldException(org.jaffa.datatypes.exceptions.MandatoryFieldException) DomainObjectValidationException(org.jaffa.persistence.exceptions.DomainObjectValidationException) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 9 with FieldMetaData

use of org.jaffa.metadata.FieldMetaData 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)

Example 10 with FieldMetaData

use of org.jaffa.metadata.FieldMetaData in project jaffa-framework by jaffa-projects.

the class PersistentHelper method exists.

/**
 * This will query the database to see if the primary-key of the input persistent object is already in use.
 * It'll invoke the exists() method of the persistent class perform the check.
 * 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 uow The UOW object. If null, then a UOW will be created implicitly by the exists() method to load the persistent object.
 * @param object 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
 * @throws FrameworkException if the exists() method of the persistent class fails.
 * @return true if the primary-key is already in use. A false will be returned if the key is not in use or if any of the key fields is null.
 */
public static boolean exists(UOW uow, IPersistent object) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, IllegalArgumentException, FrameworkException {
    Class persistentClass = object.getClass();
    // Create an argument List to be passed to the exists() method of the persistent class
    List arguments = new LinkedList();
    arguments.add(uow);
    FieldMetaData[] keyFields = getKeyFields(persistentClass.getName());
    if (keyFields != null && keyFields.length > 0) {
        for (int i = 0; i < keyFields.length; i++) {
            String keyFieldName = keyFields[i].getName();
            Object keyFieldValue = BeanHelper.getField(object, keyFieldName);
            if (keyFieldValue != null) {
                arguments.add(keyFieldValue);
            } else {
                // Return a false if any of the key-fields is null
                return false;
            }
        }
        // Get a handle on the exists 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("exists", argumentsClassArray);
        try {
            Boolean result = (Boolean) m.invoke(null, arguments.toArray());
            return result != null ? result.booleanValue() : false;
        } catch (InvocationTargetException e) {
            if (e.getCause() != null && e.getCause() instanceof FrameworkException)
                throw (FrameworkException) e.getCause();
            else
                throw e;
        }
    } else {
        String str = "Exists check cannot be performed. The input persistent object does not have any key fields defined in its meta class: " + object.getClass().getName();
        if (log.isDebugEnabled())
            log.debug(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) List(java.util.List) LinkedList(java.util.LinkedList)

Aggregations

FieldMetaData (org.jaffa.metadata.FieldMetaData)16 FrameworkException (org.jaffa.exceptions.FrameworkException)7 ApplicationException (org.jaffa.exceptions.ApplicationException)4 PropertyRuleIntrospectorUsingFieldMetaData (org.jaffa.metadata.PropertyRuleIntrospectorUsingFieldMetaData)4 IPropertyRuleIntrospector (org.jaffa.rules.IPropertyRuleIntrospector)4 InvocationTargetException (java.lang.reflect.InvocationTargetException)3 Method (java.lang.reflect.Method)3 IOException (java.io.IOException)2 LinkedList (java.util.LinkedList)2 List (java.util.List)2 JspException (javax.servlet.jsp.JspException)2 ValidationException (org.jaffa.datatypes.ValidationException)2 DuplicateKeyException (org.jaffa.exceptions.DuplicateKeyException)2 DateOnlyFieldMetaData (org.jaffa.metadata.DateOnlyFieldMetaData)2 DateTimeFieldMetaData (org.jaffa.metadata.DateTimeFieldMetaData)2 DecimalFieldMetaData (org.jaffa.metadata.DecimalFieldMetaData)2 IntegerFieldMetaData (org.jaffa.metadata.IntegerFieldMetaData)2 StringFieldMetaData (org.jaffa.metadata.StringFieldMetaData)2 EditBoxModel (org.jaffa.presentation.portlet.widgets.model.EditBoxModel)2 MissingParametersRuntimeException (org.jaffa.presentation.portlet.widgets.taglib.exceptions.MissingParametersRuntimeException)2