Search in sources :

Example 1 with NullHandler

use of com.opensymphony.xwork2.conversion.NullHandler in project struts by apache.

the class OgnlUtilTest method testCanSetADependentObject.

public void testCanSetADependentObject() {
    String dogName = "fido";
    OgnlRuntime.setNullHandler(Owner.class, new NullHandler() {

        public Object nullMethodResult(Map map, Object o, String s, Object[] objects) {
            return null;
        }

        public Object nullPropertyValue(Map map, Object o, Object o1) {
            String methodName = o1.toString();
            String getter = "set" + methodName.substring(0, 1).toUpperCase() + methodName.substring(1);
            Method[] methods = o.getClass().getDeclaredMethods();
            System.out.println(getter);
            for (Method method : methods) {
                String name = method.getName();
                if (getter.equals(name) && (method.getParameterTypes().length == 1)) {
                    Class<?> clazz = method.getParameterTypes()[0];
                    try {
                        Object param = clazz.newInstance();
                        method.invoke(o, param);
                        return param;
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
            }
            return null;
        }
    });
    Owner owner = new Owner();
    Map<String, Object> context = ognlUtil.createDefaultContext(owner);
    Map<String, Object> props = new HashMap<>();
    props.put("dog.name", dogName);
    ognlUtil.setProperties(props, owner, context);
    assertNotNull("expected Ognl to create an instance of Dog", owner.getDog());
    assertEquals(dogName, owner.getDog().getName());
}
Also used : Owner(com.opensymphony.xwork2.util.Owner) NullHandler(ognl.NullHandler) HashMap(java.util.HashMap) Method(java.lang.reflect.Method) HashMap(java.util.HashMap) Map(java.util.Map) NoSuchPropertyException(ognl.NoSuchPropertyException) MethodFailedException(ognl.MethodFailedException) InappropriateExpressionException(ognl.InappropriateExpressionException) ConfigurationException(com.opensymphony.xwork2.config.ConfigurationException) IntrospectionException(java.beans.IntrospectionException) StrutsException(org.apache.struts2.StrutsException) OgnlException(ognl.OgnlException)

Aggregations

ConfigurationException (com.opensymphony.xwork2.config.ConfigurationException)1 Owner (com.opensymphony.xwork2.util.Owner)1 IntrospectionException (java.beans.IntrospectionException)1 Method (java.lang.reflect.Method)1 HashMap (java.util.HashMap)1 Map (java.util.Map)1 InappropriateExpressionException (ognl.InappropriateExpressionException)1 MethodFailedException (ognl.MethodFailedException)1 NoSuchPropertyException (ognl.NoSuchPropertyException)1 NullHandler (ognl.NullHandler)1 OgnlException (ognl.OgnlException)1 StrutsException (org.apache.struts2.StrutsException)1