Example usage for java.beans PropertyDescriptor getDisplayName

List of usage examples for java.beans PropertyDescriptor getDisplayName

Introduction

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

Prototype

public String getDisplayName() 

Source Link

Document

Gets the localized display name of this feature.

Usage

From source file:com.ebay.jetstream.management.HtmlResourceFormatter.java

protected void formatProperty(Object bean, PropertyDescriptor pd) throws Exception {
    PrintWriter pw = getWriter();
    Method getter = pd.getReadMethod();
    Class<?> pclass = pd.getPropertyType();
    ManagedAttribute attr = getter.getAnnotation(ManagedAttribute.class);
    String text = attr != null ? attr.description() : null;
    if (CommonUtils.isEmptyTrimmed(text)) {
        text = pd.getDisplayName();
    } else {/*from  www. j av  a 2s  .c  o  m*/
        text = pd.getDisplayName() + " (" + text + ")";
    }
    pw.print(text + ": " + pclass.getName() + " = ");
    getter.setAccessible(true);
    Object value = getter.invoke(bean);
    Method setter = pd.getWriteMethod();
    attr = setter == null ? null : setter.getAnnotation(ManagedAttribute.class);
    boolean isComplex = !(String.class.isAssignableFrom(pclass) || ClassUtils.isPrimitiveOrWrapper(pclass));
    if (isComplex) {
        value = StringEscapeUtils.escapeXml(getSerializer().getXMLStringRepresentation(value));
    }
    if (attr == null) {
        if (isComplex) {
            pushElement("code", null);
        }
        pw.println(value);
        if (isComplex) {
            popElement();
        }
    } else {
        pw.println(attr.description());
        pushElement("form",
                "action=" + makePath(getPrefix(), getPath(), isComplex ? "?form" : "?" + pd.getName())
                        + " method=" + (isComplex ? "POST" : "GET"));
        if (isComplex) {
            pw.print("<TEXTAREA name=" + pd.getName() + " rows=4 cols=32>" + value + "</TEXTAREA>");
        } else {
            pw.print("<input type=text name=" + pd.getName() + " value=\"" + value + "\"/>");
        }
        pw.println("<input type=submit Value=\"Go\"/>");
        popElement();
    }
    pw.println("<P/>");
}

From source file:edu.harvard.med.screensaver.model.AbstractEntity.java

/**
 * Determine if a given property should be used in determining equivalence.
 * //from   ww w  . j  a  v a2 s . c o  m
 * @return boolean (see code, since this is private method)
 * @see #isEquivalent(AbstractEntity)
 */
// TODO: can we annotate a bean's properties with "@equivalence" and do some
// introspection to retrieve these annotated "equivalence" properties, rather
// than relying upon the below heuristics?
private boolean isEquivalenceProperty(PropertyDescriptor property) {
    Method method = property.getReadMethod();
    if (method == null) {
        // this can occur if there is a public setter method, but a non-public
        // getter method
        log.debug("no corresponding getter method for property " + property.getDisplayName());
        return false;
    }
    // only test methods that are declared by subclasses of AbstractEntity
    if (method.getDeclaringClass().equals(AbstractEntity.class)
            || !AbstractEntity.class.isAssignableFrom(method.getDeclaringClass())) {
        return false;
    }
    if (method.getAnnotation(Transient.class) != null) {
        return false;
    }
    if (method.getAnnotation(Column.class) != null
            && method.getAnnotation(Column.class).isNotEquivalenceProperty()) {
        return false;
    }
    // do not check embeddable types (as this would require descending into the embeddable to check equivalence)
    if (property.getPropertyType().getAnnotation(Embeddable.class) != null) {
        return false;
    }

    return !(Collection.class.isAssignableFrom(property.getPropertyType())
            || Map.class.isAssignableFrom(property.getPropertyType())
            || AbstractEntity.class.isAssignableFrom(property.getPropertyType()));
}

From source file:com.opensymphony.xwork2.ognl.OgnlUtil.java

/**
 * Creates a Map with read properties for the given source object.
 * <p>//  ww w. j a  v a2s.  c om
 * If the source object does not have a read property (i.e. write-only) then
 * the property is added to the map with the value <code>here is no read method for property-name</code>.
 * </p>
 *
 * @param source the source object.
 * @return a Map with (key = read property name, value = value of read property).
 * @throws IntrospectionException is thrown if an exception occurs during introspection.
 * @throws OgnlException          is thrown by OGNL if the property value could not be retrieved
 */
public Map<String, Object> getBeanMap(final Object source) throws IntrospectionException, OgnlException {
    Map<String, Object> beanMap = new HashMap<>();
    final Map sourceMap = createDefaultContext(source, null);
    PropertyDescriptor[] propertyDescriptors = getPropertyDescriptors(source);
    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
        final String propertyName = propertyDescriptor.getDisplayName();
        Method readMethod = propertyDescriptor.getReadMethod();
        if (readMethod != null) {
            final Object value = compileAndExecute(propertyName, null, new OgnlTask<Object>() {
                public Object execute(Object expr) throws OgnlException {
                    return Ognl.getValue(expr, sourceMap, source);
                }
            });
            beanMap.put(propertyName, value);
        } else {
            beanMap.put(propertyName, "There is no read method for " + propertyName);
        }
    }
    return beanMap;
}

From source file:de.jwic.base.Control.java

/**
 * Builds Json object string of all methods marked with 
 * IncludeJsOption Annotation.//from w  w w.  j  a  v  a  2 s  . c  o  m
 * If Enums are used getCode needs to be implemented, which returns the value
 * @return
 */
public String buildJsonOptions() {
    try {
        StringWriter sw = new StringWriter();
        JSONWriter writer = new JSONWriter(sw);
        writer.object();
        BeanInfo beanInfo;
        beanInfo = Introspector.getBeanInfo(getClass());

        PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();

        for (PropertyDescriptor pd : pds) {
            Method getter = pd.getReadMethod();
            if (getter != null && pd.getReadMethod().getAnnotation(IncludeJsOption.class) != null) {
                Object o = getter.invoke(this);
                if (o != null) {
                    if (o instanceof Enum) {
                        Method m = o.getClass().getMethod("getCode", null);
                        if (m != null) {
                            writer.key(pd.getDisplayName()).value(m.invoke(o));
                            continue;
                        }
                    } else if (o instanceof Date) {
                        writer.key(pd.getDisplayName())
                                .value(new JsDateString((Date) o, getSessionContext().getTimeZone()));
                        continue;
                    }

                    // if name has been changed use that one.
                    IncludeJsOption annotation = pd.getReadMethod().getAnnotation(IncludeJsOption.class);
                    if (annotation.jsPropertyName() != null && annotation.jsPropertyName().length() > 0) {
                        writer.key(annotation.jsPropertyName());
                    } else {
                        writer.key(pd.getDisplayName());
                    }
                    writer.value(o);
                }
            }
        }
        writer.endObject();
        return sw.toString();
    } catch (Exception e) {
        throw new RuntimeException("Error while configuring Json Option for " + this.getClass().getName());
    }
}

From source file:org.jdal.swing.ListTableModel.java

/** 
 * Initialize table. Load propertyDescriptors based on columNames or 
 * model introspection. /*w w  w .j a  v  a 2s .  c  o m*/
 */
// FIXME: PropertyDescriptors  are now unused, review to remove.
public void init() {
    if (modelClass == null) {
        log.warn("Cannot initilize without  modelClass, set a list of models o specify a model class");
        return;
    }

    columnCount = 0;

    if (usingIntrospection) {
        pds = Arrays.asList(BeanUtils.getPropertyDescriptors(modelClass));
        Collections.reverse(pds);
        columnNames = new ArrayList<String>(pds.size());
        displayNames = new ArrayList<String>(pds.size());

        for (PropertyDescriptor propertyDescriptor : pds) {
            columnNames.add(propertyDescriptor.getName());
            displayNames.add(propertyDescriptor.getDisplayName());
        }
    }

    else {
        pds = new ArrayList<PropertyDescriptor>(columnNames.size());
        for (String name : columnNames) {
            PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(modelClass, name);
            if (pd == null)
                throw new RuntimeException(
                        "Invalid property [" + name + "]" + " for model class [" + modelClass.getName() + "]");
            pds.add(pd);
        }
    }

    columnCount += pds.size();

    if (usingChecks) {
        columnCount++;
        buildCheckArray();
    }

    if (usingActions) {
        columnCount += actions.size();
    }
}

From source file:com.diversityarrays.kdxplore.editing.EntityPropertiesTable.java

@Override
public boolean editCellAt(int row, int column, EventObject e) {
    if (e instanceof MouseEvent) {
        MouseEvent me = (MouseEvent) e;
        if (SwingUtilities.isLeftMouseButton(me) && 2 != me.getClickCount()) {
            return false;
        }/*from   w w  w. jav  a 2s .  c  om*/
        me.consume();
    }

    @SuppressWarnings("unchecked")
    EntityPropertiesTableModel<T> eptm = (EntityPropertiesTableModel<T>) getModel();
    if (!eptm.isCellEditable(row, column)) {
        return false;
    }

    if (handleEditCellAt(eptm, row, column)) {
        return false;
    }

    PropertyDescriptor pd = eptm.getPropertyDescriptor(row);
    if (pd == null) {
        return super.editCellAt(row, column);
    }

    Class<?> propertyClass = pd.getPropertyType();

    if (propertyChangeConfirmer != null && !propertyChangeConfirmer.isChangeAllowed(pd)) {
        return false;
    }

    if (java.util.Date.class.isAssignableFrom(propertyClass)) {
        try {
            java.util.Date dateValue = (Date) pd.getReadMethod().invoke(eptm.getEntity());

            if (propertyChangeConfirmer != null) {
                propertyChangeConfirmer.setValueBeforeChange(dateValue);
            }

            Closure<Date> onComplete = new Closure<Date>() {
                @Override
                public void execute(Date result) {
                    if (result != null) {
                        if (propertyChangeConfirmer == null
                                || propertyChangeConfirmer.valueChangeCanCommit(pd, result)) {
                            getModel().setValueAt(result, row, column);
                        }
                    }
                }
            };

            String title = pd.getDisplayName();
            DatePickerDialog datePicker = new DatePickerDialog(GuiUtil.getOwnerWindow(this), title, onComplete);
            datePicker.setDate(dateValue);
            datePicker.setVisible(true);

        } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e1) {
            e1.printStackTrace();
        }
        return false;
    }
    // else if (Enum.class.isAssignableFrom(propertyClass)) {
    // }

    Log.d(TAG, "editCellAt(" + row + "," + column + ") No Editor override provided for "
            + propertyClass.getName());
    return super.editCellAt(row, column, e);
}

From source file:ca.sqlpower.architect.swingui.TestPlayPen.java

/**
 * Checks that the properties of an instance from the copy constructor are equal to the original.
 * In the case of a mutable property, it also checks that they don't share the same instance.
 * /*  w ww  .  j a  va 2  s.  com*/
 * @throws Exception
 */
public void testCopyConstructor() throws Exception {
    List<PropertyDescriptor> settableProperties = Arrays
            .asList(PropertyUtils.getPropertyDescriptors(pp.getClass()));
    Set<String> copyIgnoreProperties = new HashSet<String>();

    copyIgnoreProperties.add("UI");
    copyIgnoreProperties.add("UIClassID");
    copyIgnoreProperties.add("accessibleContext");
    copyIgnoreProperties.add("actionMap");
    copyIgnoreProperties.add("alignmentX");
    copyIgnoreProperties.add("alignmentY");
    copyIgnoreProperties.add("ancestorListeners");
    copyIgnoreProperties.add("autoscrolls");
    copyIgnoreProperties.add("border");
    copyIgnoreProperties.add("class");
    copyIgnoreProperties.add("component");
    copyIgnoreProperties.add("componentPopupMenu");
    copyIgnoreProperties.add("containerListeners");
    copyIgnoreProperties.add("contentPane");
    copyIgnoreProperties.add("cursorManager");
    copyIgnoreProperties.add("debugGraphicsOptions");
    copyIgnoreProperties.add("doubleBuffered");
    copyIgnoreProperties.add("enabled");
    copyIgnoreProperties.add("focusCycleRoot");
    copyIgnoreProperties.add("focusTraversalKeys");
    copyIgnoreProperties.add("focusTraversalPolicy");
    copyIgnoreProperties.add("focusTraversalPolicyProvider");
    copyIgnoreProperties.add("focusTraversalPolicySet");
    copyIgnoreProperties.add("focusable");
    copyIgnoreProperties.add("fontRenderContext");
    copyIgnoreProperties.add("graphics");
    copyIgnoreProperties.add("height");
    copyIgnoreProperties.add("ignoreTreeSelection");
    copyIgnoreProperties.add("inheritsPopupMenu");
    copyIgnoreProperties.add("inputMap");
    copyIgnoreProperties.add("inputVerifier");
    copyIgnoreProperties.add("insets");
    copyIgnoreProperties.add("layout");
    copyIgnoreProperties.add("managingFocus");
    copyIgnoreProperties.add("maximumSize");
    copyIgnoreProperties.add("minimumSize");
    copyIgnoreProperties.add("mouseMode");
    copyIgnoreProperties.add("name");
    copyIgnoreProperties.add("nextFocusableComponent");
    copyIgnoreProperties.add("opaque");
    copyIgnoreProperties.add("optimizedDrawingEnabled");
    copyIgnoreProperties.add("paintingEnabled");
    copyIgnoreProperties.add("paintingTile");
    copyIgnoreProperties.add("panel");
    copyIgnoreProperties.add("playPenContentPane");
    copyIgnoreProperties.add("preferredScrollableViewportSize");
    copyIgnoreProperties.add("preferredSize");
    copyIgnoreProperties.add("registeredKeyStrokes");
    copyIgnoreProperties.add("requestFocusEnabled");
    copyIgnoreProperties.add("rootPane");
    copyIgnoreProperties.add("scrollableTracksViewportHeight");
    copyIgnoreProperties.add("scrollableTracksViewportWidth");
    copyIgnoreProperties.add("selectedItems");
    copyIgnoreProperties.add("selectedRelationShips");
    copyIgnoreProperties.add("selectedTables");
    copyIgnoreProperties.add("session");
    copyIgnoreProperties.add("topLevelAncestor");
    copyIgnoreProperties.add("toolTipText");
    copyIgnoreProperties.add("transferHandler");
    copyIgnoreProperties.add("usedArea");
    copyIgnoreProperties.add("validateRoot");
    copyIgnoreProperties.add("verifyInputWhenFocusTarget");
    copyIgnoreProperties.add("vetoableChangeListeners");
    copyIgnoreProperties.add("viewPosition");
    copyIgnoreProperties.add("viewportSize");
    copyIgnoreProperties.add("visible");
    copyIgnoreProperties.add("visibleRect");
    copyIgnoreProperties.add("width");
    copyIgnoreProperties.add("x");
    copyIgnoreProperties.add("y");

    copyIgnoreProperties.add("draggingTablePanes");
    copyIgnoreProperties.add("rubberBand");

    // These should not be copied because any new PlayPen needs
    // different values or else it will not work on the new
    // PlayPen.
    copyIgnoreProperties.add("mouseZoomInAction");
    copyIgnoreProperties.add("mouseZoomOutAction");
    copyIgnoreProperties.add("scrollPane");

    // we're not sure if zoom should be duplicated...
    // it might mess up printing?!?!?
    copyIgnoreProperties.add("zoom");

    // individual lists (e.g. tables) checked instead
    copyIgnoreProperties.add("components");

    // The copy of the play pen is for things like print preview, so we don't want to
    // duplicate menus and other interactive features. (?)
    copyIgnoreProperties.add("popupFactory");

    //This property is specific to each play pen and it's settings will be re-calculated
    //regularly so it does not need to be copied.
    copyIgnoreProperties.add("criticismBucket");

    // First pass: set all settable properties, because testing the duplication of
    //             an object with all its properties at their defaults is not a
    //             very convincing test of duplication!
    for (PropertyDescriptor property : settableProperties) {
        if (copyIgnoreProperties.contains(property.getName()))
            continue;
        Object oldVal;
        try {
            oldVal = PropertyUtils.getSimpleProperty(pp, property.getName());
            // check for a setter
            if (property.getWriteMethod() != null) {
                Object newVal = getNewDifferentValue(property, oldVal);
                BeanUtils.copyProperty(pp, property.getName(), newVal);
            }
        } catch (NoSuchMethodException e) {
            logger.warn(
                    "Skipping non-settable property " + property.getName() + " on " + pp.getClass().getName());
        }
    }
    // Second pass get a copy make sure all of 
    // the original mutable objects returned from getters are different
    // between the two objects, but have the same values. 
    PlayPen duplicate = new PlayPen(pp.getSession(), pp);
    for (PropertyDescriptor property : settableProperties) {
        logger.info(property.getName() + property.getDisplayName() + property.getShortDescription());
        if (copyIgnoreProperties.contains(property.getName()))
            continue;
        Object oldVal;
        try {
            oldVal = PropertyUtils.getSimpleProperty(pp, property.getName());
            Object copyVal = PropertyUtils.getSimpleProperty(duplicate, property.getName());
            if (oldVal == null) {
                throw new NullPointerException("We forgot to set " + property.getName());
            } else {
                assertEquals("The two values for property " + property.getDisplayName() + " in "
                        + pp.getClass().getName() + " should be equal", oldVal, copyVal);

                if (isPropertyInstanceMutable(property)) {
                    assertNotSame("Copy shares mutable property with original, property name: "
                            + property.getDisplayName(), copyVal, oldVal);
                }
            }
        } catch (NoSuchMethodException e) {
            logger.warn(
                    "Skipping non-settable property " + property.getName() + " on " + pp.getClass().getName());
        }
    }
}

From source file:com.googlecode.wicketwebbeans.model.BeanMetaData.java

private void init() {
    // Check if bean supports PropertyChangeListeners.
    hasAddPropertyChangeListenerMethod = getAddPropertyChangeListenerMethod() != null;
    hasRemovePropertyChangeListenerMethod = getRemovePropertyChangeListenerMethod() != null;

    String baseBeanClassName = getBaseClassName(beanClass);

    // Deduce actions from the component.
    List<Method> actionMethods = getActionMethods(component.getClass());
    for (Method method : actionMethods) {
        String name = method.getName();
        String prefixedName = ACTION_PROPERTY_PREFIX + name;
        String label = getLabelFromLocalizer(baseBeanClassName, prefixedName);
        if (label == null) {
            label = createLabel(name);/*  w ww.  j  a  v  a 2 s.c  o m*/
        }

        ElementMetaData actionMeta = new ElementMetaData(this, prefixedName, label, null);
        actionMeta.setAction(true);
        elements.add(actionMeta);
    }

    // Create defaults based on the bean itself.
    PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(beanClass);
    for (PropertyDescriptor descriptor : descriptors) {
        String name = descriptor.getName();

        // Skip getClass() and methods that are not readable or hidden.
        if (name.equals("class") || descriptor.getReadMethod() == null || descriptor.isHidden()) {
            continue;
        }

        String label = getLabelFromLocalizer(baseBeanClassName, name);
        if (label == null) {
            label = descriptor.getDisplayName();
        }

        if (label.equals(name)) {
            label = createLabel(name);
        }

        ElementMetaData propertyMeta = new ElementMetaData(this, name, label,
                descriptor.getReadMethod().getGenericReturnType());
        propertyMeta.setViewOnly(isViewOnly());
        elements.add(propertyMeta);

        if (descriptor.getWriteMethod() == null) {
            propertyMeta.setViewOnly(true);
        }

        deriveElementFromAnnotations(descriptor, propertyMeta);
    }

    // Collect various sources of metadata for the bean we're interested in. 
    collectAnnotations();
    collectFromBeanProps();
    collectBeansAnnotation(beansMetaData, false);

    // Process action annotations on component.
    for (Method method : getActionMethods(component.getClass())) {
        Action action = method.getAnnotation(Action.class);
        processActionAnnotation(action, method.getName());
    }

    // Determine the hierarchy of Bean contexts. I.e., the default Bean is always processed first, followed by those that
    // extend it, etc. This acts as a stack.
    List<Bean> beansHier = buildContextStack();

    // Apply beans in order from highest to lowest. The default context will always be first.
    boolean foundSpecifiedContext = false;
    for (Bean bean : beansHier) {
        if (context != null && context.equals(bean.context())) {
            foundSpecifiedContext = true;
        }

        processBeanAnnotation(bean);
    }

    // Ensure that if a context was specified, that we found one in the metadata. Otherwise it might have been a typo.
    if (context != null && !foundSpecifiedContext) {
        throw new RuntimeException("Could not find specified context '" + context + "' in metadata.");
    }

    // Post-process Bean-level parameters
    if (!getBooleanParameter(PARAM_DISPLAYED)) {
        elements.clear();
        tabs.clear();
    }

    // Configure tabs
    if (tabs.isEmpty()) {
        // Create single default tab.
        tabs.add(new TabMetaData(this, DEFAULT_TAB_ID, getParameter(PARAM_LABEL)));
    }

    String defaultTabId = tabs.get(0).getId();

    if (!getBooleanParameter(PARAM_EXPLICIT_ONLY) || defaultTabId.equals(DEFAULT_TAB_ID)) {
        // Post-process each property based on bean parameters
        for (ElementMetaData elementMeta : elements) {
            // If element is not on a tab, add it to the first. If it's an
            // action, it must have been assigned an order to
            // appear on a tab. Otherwise it is a global action.
            if (elementMeta.getTabId() == null && (!elementMeta.isAction()
                    || (elementMeta.isAction() && elementMeta.isActionSpecifiedInProps()))) {
                elementMeta.setTabId(defaultTabId);
            }
        }
    }

    // Remove elements not specified in props
    if (getBooleanParameter(PARAM_EXPLICIT_ONLY)) {
        for (Iterator<ElementMetaData> iter = elements.iterator(); iter.hasNext();) {
            ElementMetaData element = iter.next();
            if (!element.isSpecifiedInProps()) {
                iter.remove();
            }
        }
    }

    Collections.sort(elements, new Comparator<ElementMetaData>() {
        public int compare(ElementMetaData o1, ElementMetaData o2) {
            return (o1.getOrder() > o2.getOrder() ? 1 : (o1.getOrder() < o2.getOrder() ? -1 : 0));
        }
    });
}

From source file:ca.sqlpower.architect.swingui.TestPlayPenComponent.java

/**
  * Checks that the properties of an instance from the copy constructor are equal to the original.
  * In the case of a mutable property, it also checks that they don't share the same instance.
  * //w w w  . jav  a2  s . co  m
  * @throws Exception
  */
public void testCopyConstructor() throws Exception {
    PlayPenComponent comp = getTarget();

    List<PropertyDescriptor> settableProperties = Arrays
            .asList(PropertyUtils.getPropertyDescriptors(comp.getClass()));

    copyIgnoreProperties.add("UI");
    copyIgnoreProperties.add("UIClassID");
    copyIgnoreProperties.add("UUID");
    copyIgnoreProperties.add("allowedChildTypes");
    copyIgnoreProperties.add("background");
    copyIgnoreProperties.add("bounds");
    copyIgnoreProperties.add("class");
    copyIgnoreProperties.add("children");
    copyIgnoreProperties.add("fontRenderContext");
    copyIgnoreProperties.add("height");
    copyIgnoreProperties.add("insets");
    copyIgnoreProperties.add("lengths");
    copyIgnoreProperties.add("location");
    copyIgnoreProperties.add("locationOnScreen");
    copyIgnoreProperties.add("magicEnabled");
    copyIgnoreProperties.add("opaque");
    copyIgnoreProperties.add("parent");
    copyIgnoreProperties.add("playPen");
    copyIgnoreProperties.add("popup");
    copyIgnoreProperties.add("preferredLocation");
    copyIgnoreProperties.add("preferredSize");
    copyIgnoreProperties.add("selected");
    copyIgnoreProperties.add("session");
    copyIgnoreProperties.add("workspaceContainer");
    copyIgnoreProperties.add("runnableDispatcher");
    copyIgnoreProperties.add("size");
    copyIgnoreProperties.add("toolTipText");
    copyIgnoreProperties.add("width");
    copyIgnoreProperties.add("x");
    copyIgnoreProperties.add("y");

    // no setters for this and it depends on the playpen's font
    copyIgnoreProperties.add("font");

    // not so sure if this should be duplicated, it's changed as the model properties changes
    copyIgnoreProperties.add("modelName");

    // copy and original should point to same business object
    copySameInstanceIgnoreProperties.add("model");

    // First pass: set all settable properties, because testing the duplication of
    //             an object with all its properties at their defaults is not a
    //             very convincing test of duplication!
    for (PropertyDescriptor property : settableProperties) {
        if (copyIgnoreProperties.contains(property.getName()))
            continue;
        Object oldVal;
        try {
            oldVal = PropertyUtils.getSimpleProperty(comp, property.getName());
            // check for a setter
            if (property.getWriteMethod() != null) {
                Object newVal = getNewDifferentValue(property, oldVal);
                BeanUtils.copyProperty(comp, property.getName(), newVal);
            }
        } catch (NoSuchMethodException e) {
            System.out.println("Skipping non-settable property " + property.getName() + " on "
                    + comp.getClass().getName());
        }
    }
    // Second pass get a copy make sure all of 
    // the origional mutable objects returned from getters are different
    // between the two objects, but have the same values. 
    PlayPenComponent duplicate = getTargetCopy();
    for (PropertyDescriptor property : settableProperties) {
        if (copyIgnoreProperties.contains(property.getName()))
            continue;
        Object oldVal;
        try {
            oldVal = PropertyUtils.getSimpleProperty(comp, property.getName());
            Object copyVal = PropertyUtils.getSimpleProperty(duplicate, property.getName());
            if (oldVal == null) {
                throw new NullPointerException("We forgot to set " + property.getName());
            } else {
                assertEquals("The two values for property " + property.getDisplayName() + " in "
                        + comp.getClass().getName() + " should be equal", oldVal, copyVal);

                if (isPropertyInstanceMutable(property)
                        && !copySameInstanceIgnoreProperties.contains(property.getName())) {
                    assertNotSame("Copy shares mutable property with original, property name: "
                            + property.getDisplayName(), copyVal, oldVal);
                }
            }
        } catch (NoSuchMethodException e) {
            System.out.println("Skipping non-settable property " + property.getName() + " on "
                    + comp.getClass().getName());
        }
    }
}

From source file:com.twinsoft.convertigo.beans.core.DatabaseObject.java

public Element toXml(Document document) throws EngineException {
    Element element = document.createElement(getDatabaseType().toLowerCase());

    element.setAttribute("classname", getClass().getName());
    if (exportOptions.contains(ExportOption.bIncludeVersion)) {
        element.setAttribute("version", com.twinsoft.convertigo.beans.Version.version);
    }/*  w  ww.j av a 2 s.c  o m*/

    // Storing the database object priority
    element.setAttribute("priority", new Long(priority).toString());

    int len;
    PropertyDescriptor[] propertyDescriptors;
    PropertyDescriptor propertyDescriptor;
    Element propertyElement;

    try {
        BeanInfo bi = CachedIntrospector.getBeanInfo(getClass());
        propertyDescriptors = bi.getPropertyDescriptors();
        len = propertyDescriptors.length;
        if (exportOptions.contains(ExportOption.bIncludeDisplayName)) {
            element.setAttribute("displayName", bi.getBeanDescriptor().getDisplayName());
        }
    } catch (IntrospectionException e) {
        throw new EngineException("Couldn't introspect the bean \"" + getName() + "\"", e);
    }

    for (int i = 0; i < len; i++) {
        propertyDescriptor = propertyDescriptors[i];
        String name = propertyDescriptor.getName();
        String displayName = propertyDescriptor.getDisplayName();
        String shortDescription = propertyDescriptor.getShortDescription();

        Method getter = propertyDescriptor.getReadMethod();

        // Only analyze read propertyDescriptors.
        if (getter == null) {
            continue;
        }

        if (checkBlackListParentClass(propertyDescriptor)) {
            continue;
        }

        try {
            // Storing the database object bean properties
            Object uncompiledValue = getCompilablePropertySourceValue(name);
            Object compiledValue = null;
            Object cypheredValue = null;
            Object value = getter.invoke(this);

            if (uncompiledValue != null) {
                compiledValue = value;
                value = uncompiledValue;
            }

            // Only write non-null values
            if (value == null) {
                Engine.logBeans.warn("Attempting to store null property (\"" + name + "\"); skipping...");
                continue;
            }

            propertyElement = document.createElement("property");
            propertyElement.setAttribute("name", name);

            // Encrypts value if needed
            //if (isCipheredProperty(name) && !this.exportOptions.contains(ExportOption.bIncludeDisplayName)) {
            if (isCipheredProperty(name) && (this.exportOptions.contains(ExportOption.bHidePassword)
                    || !this.exportOptions.contains(ExportOption.bIncludeDisplayName))) {
                cypheredValue = encryptPropertyValue(value);
                if (!value.equals(cypheredValue)) {
                    value = cypheredValue;
                    propertyElement.setAttribute("ciphered", "true");
                }
            }

            // Stores the value
            Node node = null;
            if (exportOptions.contains(ExportOption.bIncludeCompiledValue)) {
                node = XMLUtils.writeObjectToXml(document, value, compiledValue);
            } else {
                node = XMLUtils.writeObjectToXml(document, value);
            }
            propertyElement.appendChild(node);

            // Add visibility for logs
            if (!isTraceableProperty(name)) {
                propertyElement.setAttribute("traceable", "false");
            }

            if (exportOptions.contains(ExportOption.bIncludeBlackListedElements)) {
                Object propertyDescriptorBlackListValue = propertyDescriptor
                        .getValue(MySimpleBeanInfo.BLACK_LIST_NAME);
                if (propertyDescriptorBlackListValue != null && (Boolean) propertyDescriptorBlackListValue) {
                    propertyElement.setAttribute("blackListed", "blackListed");
                }
            }
            if (exportOptions.contains(ExportOption.bIncludeDisplayName)) {
                propertyElement.setAttribute("displayName", displayName);
                propertyElement.setAttribute("isHidden", Boolean.toString(propertyDescriptor.isHidden()));
                propertyElement.setAttribute("isMasked",
                        isMaskedProperty(Visibility.Platform, name) ? "true" : "false");
                propertyElement.setAttribute("isExpert", Boolean.toString(propertyDescriptor.isExpert()));
            }
            if (exportOptions.contains(ExportOption.bIncludeShortDescription)) {
                propertyElement.setAttribute("shortDescription", shortDescription);
            }

            if (exportOptions.contains(ExportOption.bIncludeEditorClass)) {
                Class<?> pec = propertyDescriptor.getPropertyEditorClass();
                String message = "";
                if (pec != null) {
                    message = propertyDescriptor.getPropertyEditorClass().toString().replaceFirst("(.)*\\.",
                            "");
                } else {
                    message = "null";
                }
                if (this instanceof ITagsProperty || (pec != null && Enum.class.isAssignableFrom(pec))) {
                    String[] sResults = null;
                    try {
                        if (this instanceof ITagsProperty) {
                            sResults = ((ITagsProperty) this).getTagsForProperty(name);
                        } else {
                            sResults = EnumUtils.toNames(pec);
                        }
                    } catch (Exception ex) {
                        sResults = new String[0];
                    }

                    if (sResults != null) {
                        if (sResults.length > 0) {
                            Element possibleValues = document.createElement("possibleValues");
                            Element possibleValue = null;
                            for (int j = 0; j < sResults.length; j++) {
                                possibleValue = document.createElement("value");
                                possibleValue.setTextContent(sResults[j]);
                                possibleValues.appendChild(possibleValue);
                            }
                            propertyElement.appendChild(possibleValues);
                        }
                    }
                }
                propertyElement.setAttribute("editorClass", message);
            }

            element.appendChild(propertyElement);

            if (Boolean.TRUE.equals(propertyDescriptor.getValue("nillable"))) {
                try {
                    Method method = this.getClass().getMethod("isNullProperty", new Class[] { String.class });
                    Object isNull = method.invoke(this, new Object[] { name });
                    propertyElement.setAttribute("isNull", isNull.toString());
                } catch (Exception ex) {
                    Engine.logBeans.error(
                            "[Serialization] Skipping 'isNull' attribute for property \"" + name + "\".", ex);
                }
            }
        } catch (Exception e) {
            Engine.logBeans.error("[Serialization] Skipping property \"" + name + "\".", e);
        }
    }

    return element;
}