Example usage for org.springframework.beans BeanWrapperImpl setWrappedInstance

List of usage examples for org.springframework.beans BeanWrapperImpl setWrappedInstance

Introduction

In this page you can find the example usage for org.springframework.beans BeanWrapperImpl setWrappedInstance.

Prototype

public void setWrappedInstance(Object object) 

Source Link

Document

Switch the target object, replacing the cached introspection results only if the class of the new object is different to that of the replaced object.

Usage

From source file:com.fmguler.ven.QueryMapper.java

protected void mapRecursively(ResultSet rs, Set columns, String tableName, Class objectClass, List parentList) {
    try {/*from   www. j  a v a2s.  c o  m*/
        if (!columns.contains(tableName + "_id"))
            return; //this object does not exist in the columns
        Object id = rs.getObject(tableName + "_id");
        if (id == null)
            return; //this object exists in the columns but null, probably because of left join

        //create bean wrapper for the object class
        BeanWrapperImpl wr = new BeanWrapperImpl(objectClass); //already caches class introspection (CachedIntrospectionResults.forClass())
        wr.setPropertyValue("id", id); //set the id property
        Object object = wr.getWrappedInstance();
        boolean map = true;

        //check if this object exists in the parent list (since SQL joins are cartesian products, do not create new object if this row is just the same as previous)
        for (Iterator it = parentList.iterator(); it.hasNext();) {
            Object objectInList = (Object) it.next();
            if (objectIdEquals(objectInList, id)) {
                wr.setWrappedInstance(objectInList); //already exists in the list, use that instance
                map = false; // and do not map again
                break;
            }
        }
        if (map)
            parentList.add(object); //could not find in the parent list, add the new object

        PropertyDescriptor[] pdArr = wr.getPropertyDescriptors();
        for (int i = 0; i < pdArr.length; i++) {
            PropertyDescriptor pd = pdArr[i];
            Class fieldClass = pd.getPropertyType(); //field class
            String fieldName = Convert.toDB(pd.getName()); //field name
            Object fieldValue = wr.getPropertyValue(pd.getName());
            String columnName = tableName + "_" + fieldName;

            //database class (primitive property)
            if (map && dbClasses.contains(fieldClass)) {
                if (columns.contains(columnName)) {
                    if (debug)
                        System.out.println(">>field is found: " + columnName);
                    wr.setPropertyValue(pd.getName(), rs.getObject(columnName));
                } else {
                    if (debug)
                        System.out.println("--field not found: " + columnName);
                }
                continue; //if this is a primitive property, it cannot be an object or list
            }

            //many to one association (object property)
            if (fieldClass.getPackage() != null && domainPackages.contains(fieldClass.getPackage().getName())) {
                if (columns.contains(columnName + "_id")) {
                    if (debug)
                        System.out.println(">>object is found " + columnName);
                    List list = new ArrayList(1); //we know there will be single result
                    if (!map)
                        list.add(fieldValue); //otherwise we cannot catch one to many assc. (lists) of many to one (object) assc.
                    mapRecursively(rs, columns, columnName, fieldClass, list);
                    if (list.size() > 0)
                        wr.setPropertyValue(pd.getName(), list.get(0));
                } else {
                    if (debug)
                        System.out.println("--object not found: " + columnName);
                }
            }

            //one to many association (list property)
            if (fieldValue instanceof List) { //Note: here recurring row's list property is mapped and add to parent's list
                if (columns.contains(columnName + "_id")) {
                    Class elementClass = VenList.findElementClass((List) fieldValue);
                    if (debug)
                        System.out.println(">>list is found " + columnName);
                    mapRecursively(rs, columns, columnName, elementClass, (List) fieldValue);
                } else {
                    if (debug)
                        System.out.println("--list not found: " + columnName);
                }
            }
        }
    } catch (Exception ex) {
        System.out.println("Ven - error while mapping row, table: " + tableName + " object class: "
                + objectClass + " error: " + ex.getMessage());
        if (debug) {
            ex.printStackTrace();
        }
    }
}

From source file:org.gvnix.web.datatables.util.DatatablesUtils.java

/**
 * Populate a {@link DataSet} from given entity list.
 * <p/>/*from  w w w.  ja v a 2 s.com*/
 * Field values will be converted to String using given
 * {@link ConversionService} and Date fields will be converted to Date using
 * {@link DateFormat} with given date patterns.
 * 
 * @param entities List of T entities to convert to Datatables data
 * @param pkFieldName The T entity field that contains the PK
 * @param totalRecords Total amount of records
 * @param totalDisplayRecords Amount of records found
 * @param columns {@link ColumnDef} list
 * @param datePatterns Patterns to convert Date fields to String. The Map
 *        contains one pattern for each entity Date field keyed by field
 *        name. For Roo compatibility the key could follow the pattern
 *        {@code uncapitalize( ENTITY ) + "_" + lower_case( FIELD ) + "_date_format"}
 *        too
 * @param conversionService
 * @return
 */
public static <T> DataSet<Map<String, String>> populateDataSet(List<T> entities, String pkFieldName,
        long totalRecords, long totalDisplayRecords, List<ColumnDef> columns, Map<String, Object> datePatterns,
        ConversionService conversionService) {

    // Check arguments aren't null
    Assert.notNull(pkFieldName);
    Assert.notNull(columns);
    Assert.notNull(conversionService);

    // Map of data rows
    List<Map<String, String>> rows = new ArrayList<Map<String, String>>(entities.size());

    if (CollectionUtils.isEmpty(entities)) {
        return new DataSet<Map<String, String>>(rows, 0l, 0l);
    }

    // If null, create empty Map to avoid control code overload
    if (CollectionUtils.isEmpty(datePatterns)) {
        datePatterns = new HashMap<String, Object>();
    }
    Map<String, SimpleDateFormat> dateFormatters = new HashMap<String, SimpleDateFormat>(datePatterns.size());

    // Prepare required fields
    Set<String> fields = new HashSet<String>();
    fields.add(pkFieldName);

    // Add fields from request
    for (ColumnDef colum : columns) {
        fields.add(colum.getName());
    }

    BeanWrapperImpl entityBean = null;
    String valueStr = null;
    // Populate each row, note a row is a Map containing
    // fieldName = fieldValue
    for (T entity : entities) {
        Map<String, String> row = new HashMap<String, String>(fields.size());
        if (entityBean == null) {
            entityBean = new BeanWrapperImpl(entity);
        } else {
            entityBean.setWrappedInstance(entity);
        }
        for (String fieldName : fields) {

            String unescapedFieldName = unescapeDot(fieldName);

            // check if property exists (trace it else)
            if (!entityBean.isReadableProperty(unescapedFieldName)) {
                if (LOGGER.isTraceEnabled()) {
                    LOGGER.trace("Property [{}] not fond in bean {} [{}]", unescapedFieldName,
                            entity.getClass().getSimpleName(), entity);
                }
                row.put(fieldName, "");
                continue;
            }

            // Convert field value to string
            valueStr = convertFieldValueToString(datePatterns, dateFormatters, conversionService, entityBean,
                    entity, fieldName, unescapedFieldName);
            row.put(fieldName, valueStr);

            // Set PK value as DT_RowId
            // Note when entity has composite PK Roo generates the need
            // convert method and adds it to ConversionService, so
            // when processed field is the PK the valueStr is the
            // composite PK instance marshalled to JSON notation and
            // Base64 encoded
            if (pkFieldName.equalsIgnoreCase(fieldName)) {
                row.put("DT_RowId", valueStr);
            }
        }
        rows.add(row);
    }
    DataSet<Map<String, String>> dataSet = new DataSet<Map<String, String>>(rows, totalRecords,
            totalDisplayRecords);
    return dataSet;
}

From source file:de.iteratec.iteraplan.businesslogic.exchange.nettoExport.OverviewPageColumnStructure.java

/**{@inheritDoc}**/
@Override/*from   w  ww . j a  v a2 s.  c o  m*/
public Object resolveValue(Object bean) {

    // Same logic like in Results.jsp here:

    BeanWrapperImpl wrapper = new BeanWrapperImpl(false);
    wrapper.setWrappedInstance(bean);
    Object resolvedObject = wrapper.getPropertyValue(columnDefinition.getBeanPropertyPath());

    AttributeType attrType = columnDefinition.getAttributeType();
    boolean multiValueType = (attrType instanceof MultiassignementType)
            && ((MultiassignementType) attrType).isMultiassignmenttype();

    if (attrType != null) {

        if (resolvedObject instanceof List<?>) {
            List<?> allValues = (List<?>) resolvedObject;

            if (multiValueType) {
                List<String> attributeValues = Lists.newArrayList();
                for (Object attrObj : allValues) {
                    if (attrObj instanceof DateAV) {
                        Date dateValue = ((DateAV) attrObj).getValue();
                        attributeValues.add(dateValue.toString());
                    } else if (attrObj instanceof ResponsibilityAV) {
                        attributeValues.add(((ResponsibilityAV) attrObj).getName());
                    } else {
                        attributeValues.add(((AttributeValue) attrObj).getValueString());
                    }
                }

                return Joiner.on(MULTIVALUE_SEPARATOR).join(attributeValues);
            } else {
                if (allValues == null || allValues.size() == 0) {
                    return NOT_FOUND;
                }

                Object singleValue = allValues.get(0);
                if (singleValue instanceof ResponsibilityAV) {
                    return ((ResponsibilityAV) singleValue).getName();
                } else {
                    return ((AttributeValue) singleValue).getValue();
                }
            }
        }

    } else {
        if ("direction".equals(columnDefinition.getModelPath()) && (resolvedObject instanceof String)) {
            Direction directionForValue = Direction.getDirectionForValue(String.valueOf(resolvedObject));
            if (directionForValue != null) {
                return SHOW_DIRECTION_ARROWS ? directionForValue.toString() : directionForValue.name();
            }
        }

        if (columnDefinition.isInternationalized()) {
            return MessageAccess.getString(String.valueOf(resolvedObject));
        }

        return String.valueOf(resolvedObject);
    }

    return StringUtils.defaultString(String.valueOf(resolvedObject), NOT_FOUND);
}

From source file:de.iteratec.iteraplan.businesslogic.exchange.nettoExport.SpreadsheetReportColumnStructure.java

/**{@inheritDoc}**/
@Override/*from ww  w .  ja  va  2s. c  o m*/
public String resolveValue(Object bean) {

    // Use same logic like in ResultPageTile.jsp:

    BeanWrapperImpl wrapper = new BeanWrapperImpl(false);
    wrapper.setWrappedInstance(bean);
    Object resolvedObject = wrapper.getPropertyValue(beanPath);

    switch (colType) {

    case ATTRIBUTE:
        return resolveAttributeValue(resolvedObject);

    case LIST:
        if (resolvedObject instanceof Iterable<?>) {
            List<String> valuesList = Lists.newArrayList();
            for (Object obj : (Iterable<?>) resolvedObject) {
                valuesList.add(String.valueOf(obj));
            }
            if (valuesList.size() > 0) {
                return Joiner.on(MULTIVALUE_SEPARATOR).join(valuesList);
            }
        }
        break;

    case SEAL:
        if (resolvedObject instanceof SealState) {
            SealState sealState = (SealState) resolvedObject;
            return MessageAccess.getString(sealState.toString());
        }
        break;

    case AVAILABLE_FOR_INTERFACES:
        if (resolvedObject instanceof Boolean) {
            boolean availableForInterfaces = ((Boolean) resolvedObject).booleanValue();
            if (availableForInterfaces) {
                return MessageAccess.getString("global.yes");
            } else {
                return MessageAccess.getString("global.no");
            }
        }
        break;

    case DIRECTION:
        if (resolvedObject instanceof String) {
            Direction directionForValue = Direction.getDirectionForValue(String.valueOf(resolvedObject));
            if (directionForValue != null) {
                return SHOW_DIRECTION_ARROWS ? directionForValue.toString() : directionForValue.name();
            }
        }
        return StringUtils.defaultString(String.valueOf(resolvedObject), NOT_FOUND);

    case DATE:
        if (resolvedObject instanceof Date) {
            return getDateFormat().format((Date) resolvedObject);
        }
        break;

    case TYPE_OF_STATUS:
        if (resolvedObject instanceof de.iteratec.iteraplan.model.InformationSystemRelease.TypeOfStatus) {
            de.iteratec.iteraplan.model.InformationSystemRelease.TypeOfStatus statusISR = (de.iteratec.iteraplan.model.InformationSystemRelease.TypeOfStatus) resolvedObject;
            return MessageAccess.getString(statusISR.toString());
        } else if (resolvedObject instanceof de.iteratec.iteraplan.model.TechnicalComponentRelease.TypeOfStatus) {
            de.iteratec.iteraplan.model.TechnicalComponentRelease.TypeOfStatus statusTCR = (de.iteratec.iteraplan.model.TechnicalComponentRelease.TypeOfStatus) resolvedObject;
            return MessageAccess.getString(statusTCR.toString());
        }
        break;

    default:
        if (resolvedObject != null) {
            return String.valueOf(resolvedObject);
        }
        break;
    }
    return NOT_FOUND;
}

From source file:org.gvnix.web.datatables.util.impl.DatatablesUtilsBeanImpl.java

/**
 * {@inheritDoc}//  w w  w .j  a  v a2s.c o  m
 */
@Override
public <T> DataSet<Map<String, String>> populateDataSet(List<T> entities, String pkFieldName, long totalRecords,
        long totalDisplayRecords, List<ColumnDef> columns, Map<String, Object> datePatterns) {

    // Check arguments aren't null
    Assert.notNull(pkFieldName);
    Assert.notNull(columns);
    Assert.notNull(conversionService);

    // Map of data rows
    List<Map<String, String>> rows = new ArrayList<Map<String, String>>(entities.size());

    if (CollectionUtils.isEmpty(entities)) {
        return new DataSet<Map<String, String>>(rows, 0l, 0l);
    }

    // If null, create empty Map to avoid control code overload
    if (CollectionUtils.isEmpty(datePatterns)) {
        datePatterns = new HashMap<String, Object>();
    }
    Map<String, SimpleDateFormat> dateFormatters = new HashMap<String, SimpleDateFormat>(datePatterns.size());

    // Prepare required fields
    Set<String> fields = new HashSet<String>();
    fields.add(pkFieldName);

    // Add fields from request
    for (ColumnDef colum : columns) {
        fields.add(colum.getName());
    }

    BeanWrapperImpl entityBean = null;
    String valueStr = null;
    // Populate each row, note a row is a Map containing
    // fieldName = fieldValue
    for (T entity : entities) {
        Map<String, String> row = new HashMap<String, String>(fields.size());
        if (entityBean == null) {
            entityBean = new BeanWrapperImpl(entity);
        } else {
            entityBean.setWrappedInstance(entity);
        }
        for (String fieldName : fields) {

            String unescapedFieldName = unescapeDot(fieldName);

            // check if property exists (trace it else)
            if (!entityBean.isReadableProperty(unescapedFieldName)) {
                if (LOGGER.isTraceEnabled()) {
                    LOGGER.trace("Property [{}] not fond in bean {} [{}]", unescapedFieldName,
                            entity.getClass().getSimpleName(), entity);
                }
                row.put(fieldName, "");
                continue;
            }

            // Convert field value to string
            valueStr = convertFieldValueToString(datePatterns, dateFormatters, entityBean, entity, fieldName,
                    unescapedFieldName);
            row.put(fieldName, valueStr);

            // Set PK value as DT_RowId
            // Note when entity has composite PK Roo generates the need
            // convert method and adds it to ConversionService, so
            // when processed field is the PK the valueStr is the
            // composite PK instance marshalled to JSON notation and
            // Base64 encoded
            if (pkFieldName.equalsIgnoreCase(fieldName)) {
                row.put("DT_RowId", valueStr);
            }
        }
        rows.add(row);
    }
    DataSet<Map<String, String>> dataSet = new DataSet<Map<String, String>>(rows, totalRecords,
            totalDisplayRecords);
    return dataSet;
}