Issue Details (XML | Word | Printable)

Key: APF-81
Type: Improvement Improvement
Status: Resolved Resolved
Resolution: Won't Fix
Priority: Major Major
Assignee: Matt Raible
Reporter: beno?t moraillon
Votes: 1
Watchers: 0
Operations

If you were logged in you would be able to see more operations.
AppFuse

Convert, ConvertLists in one ConvertAll

Created: 24/Jun/05 01:22 AM   Updated: 03/Oct/06 11:55 AM   Resolved: 03/Oct/06 11:55 AM
Component/s: Web - Struts
Affects Version/s: None
Fix Version/s: 1.9


 Description  « Hide
This code is able to perform a global convert on pojo or struts form.
 Also, it keeps the original state of the object pass through the method.
 (convertLists change the original object and i think it's boring)
 
 
 public static Object convertAll(Object o) throws Exception {
         if (o == null) {
             return null;
         }
         Object targetO = getOpposingObject(o);
         BeanUtils.copyProperties(targetO, o);
 
         Object target = null;
 
         PropertyDescriptor[] origDescriptors =
                 PropertyUtils.getPropertyDescriptors(o);
 
         for (int i = 0; i < origDescriptors.length; i++) {
             String name = origDescriptors[i].getName();
 
             if (origDescriptors[i].getPropertyType().equals(List.class)) {
                 List list = (List) PropertyUtils.getProperty(o, name);
                 List b =null;
                 if(list!=null)
                     b = new ArrayList(list.size());
 
                 for (int j=0; j < list.size(); j++) {
                     Object origin = list.get(j);
                     // je convertit l'objet dans la liste
                     target = convert(origin);
 
                     b.add(target);
                 }
                 PropertyUtils.setProperty(targetO, name, b);
             }
         }
         return targetO;
    }

and add to the BaseAction class the method convertAll


Sort Order: Ascending order - Click to sort in descending order
David Carter added a comment - 15/Sep/05 02:02 PM
Is there any reason this method shouldn't be recursive? In other words, shouldn't it call convertAll(origin) rather than convert(origin) in the inner loop? This would handle lists inside of lists.

Looks like a good idea overall.

Matt Raible added a comment - 21/Sep/05 05:25 PM
I'd rather just add convertLists() to the convert() method, but there's an ugly side-effect I've found - lazy loaded collections will get instantiated:

    public static Object convert(Object o) throws Exception {
        if (o == null) {
         return null;
        }
        Object target = getOpposingObject(o);
        BeanUtils.copyProperties(target, o);
 + convertLists(target);
        return target;
    }

I believe this convertAll would have the same effect, and that doesn't seem like a wise thing to do IMO.