Example usage for java.beans PropertyDescriptor getPropertyType

List of usage examples for java.beans PropertyDescriptor getPropertyType

Introduction

In this page you can find the example usage for java.beans PropertyDescriptor getPropertyType.

Prototype

public synchronized Class<?> getPropertyType() 

Source Link

Document

Returns the Java type info for the property.

Usage

From source file:de.xwic.sandbox.server.installer.XmlImport.java

/**
 * @param entity//from  w  ww .  j a v  a 2s.  c  om
 * @param property
 * @param elProp
 */
@SuppressWarnings("unchecked")
private void loadPropertyValue(IEntity entity, Property property, Element elProp) throws Exception {

    PropertyDescriptor pd = property.getDescriptor();
    Class<?> type = pd.getPropertyType();
    Method mWrite = pd.getWriteMethod();
    // check if value is null
    boolean isNull = elProp.element(XmlExport.ELM_NULL) != null;

    Object value = null;
    if (!isNull) {

        if (Set.class.isAssignableFrom(type)) {
            // a set.
            Set<IEntity> set = new HashSet<IEntity>();
            Element elSet = elProp.element(XmlExport.ELM_SET);
            for (Iterator<?> itSet = elSet.elementIterator(XmlExport.ELM_ELEMENT); itSet.hasNext();) {
                Element elSetElement = (Element) itSet.next();
                String typeElement = elSetElement.attributeValue("type");
                int refId = Integer.parseInt(elSetElement.getText());

                Integer newId = importedEntities.get(new EntityKey(typeElement, refId));
                if (newId != null) {
                    // its an imported object
                    refId = newId.intValue();
                }
                DAO refDAO = DAOSystem.findDAOforEntity(typeElement);
                IEntity refEntity = refDAO.getEntity(refId);
                set.add(refEntity);
            }
            value = set;

        } else if (IEntity.class.isAssignableFrom(type)) {
            // entity type
            int refId = Integer.parseInt(elProp.getText());
            Integer newId = importedEntities.get(new EntityKey(type.getName(), refId));
            if (newId != null) {
                // its an imported object
                refId = newId.intValue();
            }
            if (IPicklistEntry.class.isAssignableFrom(type)) {
                IPicklisteDAO plDAO = (IPicklisteDAO) DAOSystem.getDAO(IPicklisteDAO.class);
                value = plDAO.getPickListEntryByID(refId);
            } else {
                DAO refDAO = DAOSystem.findDAOforEntity((Class<? extends IEntity>) type);
                IEntity refEntity = refDAO.getEntity(refId);
                value = refEntity;
            }

        } else {
            // basic type
            String text = elProp.getText();
            if (String.class.equals(type)) {
                value = text;
            } else if (int.class.equals(type) || Integer.class.equals(type)) {
                value = Integer.valueOf(text);
            } else if (long.class.equals(type) || Long.class.equals(type)) {
                value = Long.valueOf(text);
            } else if (boolean.class.equals(type) || Boolean.class.equals(type)) {
                value = Boolean.valueOf(text.equals("true"));
            } else if (Date.class.equals(type)) {
                value = new Date(Long.parseLong(text));
            } else if (double.class.equals(type) || Double.class.equals(type)) {
                value = Double.valueOf(text);
            }
        }

    }
    mWrite.invoke(entity, new Object[] { value });

}

From source file:com.easyget.commons.csv.bean.CsvToBean.java

/**
 * Attempt to find custom property editor on descriptor first, else try the propery editor manager.
 *
 * @param desc - PropertyDescriptor./* w w w.  j  av a2  s  .  co m*/
 * @return - the PropertyEditor for the given PropertyDescriptor.
 * @throws InstantiationException - thrown when getting the PropertyEditor for the class.
 * @throws IllegalAccessException - thrown when getting the PropertyEditor for the class.
 */
protected PropertyEditor getPropertyEditor(PropertyDescriptor desc)
        throws InstantiationException, IllegalAccessException {
    Class<?> cls = desc.getPropertyEditorClass();
    if (null != cls) {
        return (PropertyEditor) cls.newInstance();
    }
    return getPropertyEditorValue(desc.getPropertyType());
}

From source file:org.kuali.kfs.module.ld.businessobject.lookup.LedgerBalanceForExpenseTransferLookupableHelperServiceImpl.java

/**
 * @param element//w w  w  .  j ava  2 s. co m
 * @param attributeName
 * @return Column
 *
 * KRAD Conversion: Performs customization of the results columns.
 *
 * Uses data dictionary to get column properties.
 */
protected Column setupResultsColumn(BusinessObject element, String attributeName,
        BusinessObjectRestrictions businessObjectRestrictions) {
    Column col = new Column();

    col.setPropertyName(attributeName);

    String columnTitle = getDataDictionaryService().getAttributeLabel(getBusinessObjectClass(), attributeName);
    if (StringUtils.isBlank(columnTitle)) {
        columnTitle = getDataDictionaryService().getCollectionLabel(getBusinessObjectClass(), attributeName);
    }
    col.setColumnTitle(columnTitle);
    col.setMaxLength(getDataDictionaryService().getAttributeMaxLength(getBusinessObjectClass(), attributeName));

    Class formatterClass = getDataDictionaryService().getAttributeFormatter(getBusinessObjectClass(),
            attributeName);
    Formatter formatter = null;
    if (formatterClass != null) {
        try {
            formatter = (Formatter) formatterClass.newInstance();
            col.setFormatter(formatter);
        } catch (InstantiationException e) {
            LOG.error("Unable to get new instance of formatter class: " + formatterClass.getName());
            throw new RuntimeException(
                    "Unable to get new instance of formatter class: " + formatterClass.getName());
        } catch (IllegalAccessException e) {
            LOG.error("Unable to get new instance of formatter class: " + formatterClass.getName());
            throw new RuntimeException(
                    "Unable to get new instance of formatter class: " + formatterClass.getName());
        }
    }

    // pick off result column from result list, do formatting
    String propValue = KFSConstants.EMPTY_STRING;
    Object prop = ObjectUtils.getPropertyValue(element, attributeName);

    // set comparator and formatter based on property type
    Class propClass = null;
    try {
        PropertyDescriptor propDescriptor = PropertyUtils.getPropertyDescriptor(element, col.getPropertyName());
        if (propDescriptor != null) {
            propClass = propDescriptor.getPropertyType();
        }
    } catch (Exception e) {
        throw new RuntimeException("Cannot access PropertyType for property " + "'" + col.getPropertyName()
                + "' " + " on an instance of '" + element.getClass().getName() + "'.", e);
    }

    // formatters
    if (prop != null) {
        // for Booleans, always use BooleanFormatter
        if (prop instanceof Boolean) {
            formatter = new BooleanFormatter();
        }

        if (formatter != null) {
            propValue = (String) formatter.format(prop);
        } else {
            propValue = prop.toString();
        }
    }

    // comparator
    col.setComparator(CellComparatorHelper.getAppropriateComparatorForPropertyClass(propClass));
    col.setValueComparator(CellComparatorHelper.getAppropriateValueComparatorForPropertyClass(propClass));

    propValue = super.maskValueIfNecessary(element.getClass(), col.getPropertyName(), propValue,
            businessObjectRestrictions);
    col.setPropertyValue(propValue);

    if (StringUtils.isNotBlank(propValue)) {
        col.setColumnAnchor(getInquiryUrl(element, col.getPropertyName()));
    }
    return col;
}

From source file:com.easyget.commons.csv.bean.CsvToBean.java

/**
 * Creates a single object from a line from the csv file.
 * @param mapper - MappingStrategy/*from  w  w w .  j  ava2 s  .c  o  m*/
 * @param line  - array of Strings from the csv file.
 * @return - object containing the values.
 * @throws IllegalAccessException - thrown on error creating bean.
 * @throws InvocationTargetException - thrown on error calling the setters.
 * @throws InstantiationException - thrown on error creating bean.
 * @throws IntrospectionException - thrown on error getting the PropertyDescriptor.
 * @throws ParseException 
 */
protected T processLine(MappingStrategy<T> mapper, Line line, FieldFormater formater)
        throws IllegalAccessException, InvocationTargetException, InstantiationException,
        IntrospectionException, ParseException {
    T bean = mapper.createBean();
    String[] fields = line.getLine();
    for (int col = 0; col < fields.length; col++) {
        PropertyDescriptor prop = mapper.findDescriptor(col);
        String value = checkForTrim(fields[col], prop);
        // ?
        if (formater != null)
            value = formater.parse(value);
        try {
            Class<?> clazz = prop.getPropertyType();
            Object ov = ConvertUtils.convert(value, clazz);
            PropertyUtils.setProperty(bean, prop.getName(), ov);
        } catch (NoSuchMethodException e) {
            // 
        }
    }
    return bean;
}

From source file:org.codehaus.groovy.grails.plugins.couchdb.domain.CouchDomainClassProperty.java

public CouchDomainClassProperty(GrailsDomainClass domain, PropertyDescriptor descriptor) {
    this.ownerClass = domain.getClazz();
    this.domainClass = domain;
    this.descriptor = descriptor;
    this.name = descriptor.getName();
    this.type = descriptor.getPropertyType();
    this.getter = descriptor.getReadMethod();

    try {/*  w  w  w.  j a  v a2 s .co m*/
        this.field = domain.getClazz().getDeclaredField(descriptor.getName());
    } catch (NoSuchFieldException e) {
        // ignore
    }

    this.persistent = checkPersistence(descriptor);

    checkIfTransient();
}

From source file:org.egov.infra.web.struts.actions.BaseFormAction.java

private void setRelationship(final String relationshipName, final Class class1) throws IntrospectionException {
    final String[] ids = parameters.get(relationshipName);
    if (ids != null && ids.length > 0) {
        final String id = ids[0];
        if (isNotBlank(id) && Long.valueOf(id) > 0) {
            final PropertyDescriptor propDiscriptor = new PropertyDescriptor("id", class1);
            if (class1 != null && "Fund".equals(class1.getSimpleName()))
                setValue(relationshipName, getPersistenceService().load(Integer.valueOf(id), class1));
            else if (propDiscriptor.getPropertyType().isAssignableFrom(Long.class))
                setValue(relationshipName, getPersistenceService().getSession().get(class1, Long.valueOf(id)));
            else//from   w  w  w.  ja va2 s . co  m
                setValue(relationshipName, getPersistenceService().load(Integer.valueOf(id), class1));
        }

    }
}

From source file:net.sf.json.util.DynaBeanToBeanMorpher.java

/**
 * DOCUMENT ME!/*from w  ww  .ja  va2 s  .  c  o m*/
 *
 * @param value DOCUMENT ME!
 *
 * @return DOCUMENT ME!
 */
public Object morph(Object value) {
    if (value == null) {
        return null;
    }

    if (!supports(value.getClass())) {
        throw new MorphException("value is not a DynaBean");
    }

    Object bean = null;

    try {
        bean = beanClass.newInstance();

        DynaBean dynaBean = (DynaBean) value;
        DynaClass dynaClass = dynaBean.getDynaClass();
        PropertyDescriptor[] pds = PropertyUtils.getPropertyDescriptors(beanClass);

        for (int i = 0; i < pds.length; i++) {
            PropertyDescriptor pd = pds[i];
            String name = pd.getName();
            DynaProperty dynaProperty = dynaClass.getDynaProperty(name);

            if (dynaProperty != null) {
                Class dynaType = dynaProperty.getType();
                Class type = pd.getPropertyType();

                if (type.isAssignableFrom(dynaType)) {
                    PropertyUtils.setProperty(bean, name, dynaBean.get(name));
                } else {
                    if (IdentityObjectMorpher.getInstance() == morpherRegistry.getMorpherFor(type)) {
                        throw new MorphException("Can't find a morpher for target class " + type);
                    } else {
                        PropertyUtils.setProperty(bean, name, morpherRegistry.morph(type, dynaBean.get(name)));
                    }
                }
            }
        }
    } catch (InstantiationException e) {
        throw new MorphException(e);
    } catch (IllegalAccessException e) {
        throw new MorphException(e);
    } catch (InvocationTargetException e) {
        throw new MorphException(e);
    } catch (NoSuchMethodException e) {
        throw new MorphException(e);
    }

    return bean;
}

From source file:org.apache.activemq.artemis.tests.integration.jms.connection.ConnectionFactorySerializationTest.java

private void populate(StringBuilder sb, BeanUtilsBean bean, ActiveMQConnectionFactory factory)
        throws IllegalAccessException, InvocationTargetException {
    PropertyDescriptor[] descriptors = bean.getPropertyUtils().getPropertyDescriptors(factory);
    for (PropertyDescriptor descriptor : descriptors) {
        if (descriptor.getWriteMethod() != null && descriptor.getReadMethod() != null) {
            if (descriptor.getPropertyType() == String.class) {
                String value = RandomUtil.randomString();
                bean.setProperty(factory, descriptor.getName(), value);
                sb.append("&").append(descriptor.getName()).append("=").append(value);
            } else if (descriptor.getPropertyType() == int.class) {
                int value = RandomUtil.randomPositiveInt();
                bean.setProperty(factory, descriptor.getName(), value);
                sb.append("&").append(descriptor.getName()).append("=").append(value);
            } else if (descriptor.getPropertyType() == long.class) {
                long value = RandomUtil.randomPositiveLong();
                bean.setProperty(factory, descriptor.getName(), value);
                sb.append("&").append(descriptor.getName()).append("=").append(value);
            } else if (descriptor.getPropertyType() == double.class) {
                double value = RandomUtil.randomDouble();
                bean.setProperty(factory, descriptor.getName(), value);
                sb.append("&").append(descriptor.getName()).append("=").append(value);
            }//from  w w  w  . j a  v  a2s  .c  o m
        }
    }
}

From source file:com.panemu.tiwulfx.control.LookupFieldController.java

/**
 * Show lookup dialog./*from w  ww.jav  a 2s.  c  o m*/
 *
 * @param stage parent
 * @param initialValue this value will be returned if user clik the close
 * button instead of double clicking a row or click Select button
 * @param propertyName propertyName corresponds to searchCriteria
 * @param searchCriteria searchCriteria (nullable)
 * @return selected object or the initialValue
 */
public T show(final Window stage, T initialValue, String propertyName, String searchCriteria) {
    if (dialogStage == null) {
        PropertyDescriptor[] props = PropertyUtils.getPropertyDescriptors(recordClass);
        lookupWindow = new LookupWindow();
        for (String clm : getColumns()) {
            for (PropertyDescriptor prop : props) {
                if (prop.getName().equals(clm)) {
                    Class type = prop.getPropertyType();
                    if (type.equals(Boolean.class)) {
                        lookupWindow.table.addColumn(new CheckBoxColumn<T>(clm));
                    } else if (type.equals(String.class)) {
                        lookupWindow.table.addColumn(new TextColumn<T>(clm));
                    } else if (type.equals(Date.class)) {
                        lookupWindow.table.addColumn(new LocalDateColumn<T>(clm));
                    } else if (Number.class.isAssignableFrom(type)) {

                        if (Long.class.isAssignableFrom(type)) {
                            lookupWindow.table.addColumn(new NumberColumn<T, Long>(clm, type));
                        } else {
                            lookupWindow.table.addColumn(new NumberColumn<T, Double>(clm, type));
                        }
                    } else {
                        TableColumn column = new TableColumn();
                        column.setCellValueFactory(new PropertyValueFactory(clm));
                        lookupWindow.table.addColumn(column);
                    }
                    break;
                }
            }

        }
        dialogStage = new Stage();
        if (stage instanceof Stage) {
            dialogStage.initOwner(stage);
            dialogStage.initModality(Modality.WINDOW_MODAL);
        } else {
            dialogStage.initOwner(null);
            dialogStage.initModality(Modality.APPLICATION_MODAL);
        }
        dialogStage.initStyle(StageStyle.UTILITY);
        dialogStage.setResizable(true);
        dialogStage.setScene(new Scene(lookupWindow));
        dialogStage.getIcons().add(new Image(
                LookupFieldController.class.getResourceAsStream("/com/panemu/tiwulfx/res/image/lookup.png")));
        dialogStage.setTitle(getWindowTitle());
        dialogStage.getScene().getStylesheets()
                .add(getClass().getResource("/com/panemu/tiwulfx/res/tiwulfx.css").toExternalForm());
        initCallback(lookupWindow, lookupWindow.table);
    }

    for (TableColumn column : lookupWindow.table.getTableView().getColumns()) {
        if (column instanceof BaseColumn && ((BaseColumn) column).getPropertyName().equals(propertyName)) {
            if (searchCriteria != null && !searchCriteria.isEmpty()) {
                TableCriteria tc = new TableCriteria(propertyName, TableCriteria.Operator.ilike_anywhere,
                        searchCriteria);
                ((BaseColumn) column).setTableCriteria(tc);
            } else {
                ((BaseColumn) column).setTableCriteria(null);
            }

            break;
        }
    }
    selectedValue = initialValue;
    beforeShowCallback(lookupWindow.table);
    lookupWindow.table.reloadFirstPage();

    if (stage != null) {
        /**
         * Since we support multiple monitors, ensure that the stage is
         * located in the center of parent stage. But we don't know the
         * dimension of the stage for the calculation, so we defer the
         * relocation after the stage is actually displayed.
         */
        Runnable runnable = new Runnable() {
            public void run() {
                dialogStage.setX(stage.getX() + stage.getWidth() / 2 - dialogStage.getWidth() / 2);
                dialogStage.setY(stage.getY() + stage.getHeight() / 2 - dialogStage.getHeight() / 2);

                //set the opacity back to fully opaque
                dialogStage.setOpacity(1);
            }
        };

        Platform.runLater(runnable);

        //set the opacity to 0 to minimize flicker effect
        dialogStage.setOpacity(0);
    }

    dialogStage.showAndWait();
    return selectedValue;
}

From source file:cn.chenlichao.web.ssm.service.impl.BaseServiceImpl.java

@Override
public PageResults<E> queryPage(PageParams<E> pageParams) {
    if (pageParams == null) {
        throw new IllegalArgumentException("?null");
    }/*from   w  w  w.ja va2 s . c o m*/
    LOGGER.trace("...");

    // ??
    int pageNum = pageParams.getPageIndex();
    int pageSize = pageParams.getPageSize();
    if (pageSize > 100) {
        LOGGER.warn(", ?[{}] ?, ? 100 ?", pageSize);
        pageSize = 100;
    }

    // ?
    PageHelper.startPage(pageNum, pageSize);

    Example example = new Example(entityClass);
    // ??
    E params = pageParams.getParamEntity();
    if (params != null) {
        Example.Criteria criteria = example.createCriteria();
        PropertyDescriptor[] propArray = BeanUtils.getPropertyDescriptors(entityClass);
        for (PropertyDescriptor pd : propArray) {
            if (pd.getPropertyType().equals(Class.class)) {
                continue;
            }
            try {
                Object value = pd.getReadMethod().invoke(params);
                if (value != null) {
                    if (pd.getPropertyType() == String.class) {
                        String strValue = (String) value;
                        if (strValue.startsWith("%") || strValue.endsWith("%")) {
                            criteria.andLike(pd.getName(), strValue);
                            continue;
                        }
                    }
                    criteria.andEqualTo(pd.getName(), value);
                }
            } catch (IllegalAccessException | InvocationTargetException e) {
                LOGGER.error("example: {}", e.getMessage(), e);
            }
        }
    }
    // ??
    String orderBy = pageParams.getOrderBy();
    if (StringUtils.hasText(orderBy)) {
        processOrder(example, orderBy, pageParams.isAsc());
    }
    List<E> results = baseMapper.selectByExample(example);

    // 
    if (results == null || !(results instanceof Page)) {
        return new PageResults<>(0, new ArrayList<E>(0), pageParams);
    }
    Page page = (Page) results;
    Long totalCount = page.getTotal();
    return new PageResults<>(totalCount.intValue(), Collections.unmodifiableList(results), pageParams);
}