Example usage for java.beans PropertyDescriptor getName

List of usage examples for java.beans PropertyDescriptor getName

Introduction

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

Prototype

public String getName() 

Source Link

Document

Gets the programmatic name of this feature.

Usage

From source file:org.schemaspy.Config.java

/**
 * Get the value of the specified parameter.
 * Used for properties that are common to most db's, but aren't required.
 *
 * @param paramName//ww w .jav a  2 s  . c  o  m
 * @return
 */
public String getParam(String paramName) {
    try {
        BeanInfo beanInfo = Introspector.getBeanInfo(Config.class);
        PropertyDescriptor[] props = beanInfo.getPropertyDescriptors();
        for (int i = 0; i < props.length; ++i) {
            PropertyDescriptor prop = props[i];
            if (prop.getName().equalsIgnoreCase(paramName)) {
                Object result = prop.getReadMethod().invoke(this, (Object[]) null);
                return result == null ? null : result.toString();
            }
        }
    } catch (Exception failed) {
        failed.printStackTrace();
    }

    return null;
}

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);
    }//from  ww w . java2  s.com

    // 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;
}

From source file:ResultSetIterator.java

/**
 * Calls the setter method on the target object for the given property.
 * If no setter method exists for the property, this method does nothing.
 * @param target The object to set the property on.
 * @param prop The property to set.//from   w w  w .ja  v a2  s  .  co m
 * @param value The value to pass into the setter.
 * @throws SQLException if an error occurs setting the property.
 */
private void callSetter(Object target, PropertyDescriptor prop, Object value) throws SQLException {

    Method setter = prop.getWriteMethod();

    if (setter == null) {
        return;
    }

    Class[] params = setter.getParameterTypes();
    try {
        // convert types for some popular ones
        if (value != null) {
            if (value instanceof java.util.Date) {
                if (params[0].getName().equals("java.sql.Date")) {
                    value = new java.sql.Date(((java.util.Date) value).getTime());
                } else if (params[0].getName().equals("java.sql.Time")) {
                    value = new java.sql.Time(((java.util.Date) value).getTime());
                } else if (params[0].getName().equals("java.sql.Timestamp")) {
                    value = new java.sql.Timestamp(((java.util.Date) value).getTime());
                }
            }
        }

        // Don't call setter if the value object isn't the right type 
        if (this.isCompatibleType(value, params[0])) {
            setter.invoke(target, new Object[] { value });
        } else {
            throw new SQLException("Cannot set " + prop.getName() + ": incompatible types.");
        }

    } catch (IllegalArgumentException e) {
        throw new SQLException("Cannot set " + prop.getName() + ": " + e.getMessage());

    } catch (IllegalAccessException e) {
        throw new SQLException("Cannot set " + prop.getName() + ": " + e.getMessage());

    } catch (InvocationTargetException e) {
        throw new SQLException("Cannot set " + prop.getName() + ": " + e.getMessage());
    }
}

From source file:de.tudarmstadt.ukp.clarin.webanno.api.dao.RepositoryServiceDbData.java

@Override
public <T> void saveHelpContents(T aConfigurationObject) throws IOException {
    BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(aConfigurationObject);
    Properties property = new Properties();
    for (PropertyDescriptor value : wrapper.getPropertyDescriptors()) {
        if (wrapper.getPropertyValue(value.getName()) == null) {
            continue;
        }/*from  www . j a  v  a 2  s. co m*/
        property.setProperty(value.getName(), wrapper.getPropertyValue(value.getName()).toString());
    }
    File helpFile = new File(dir.getAbsolutePath() + HELP_FILE);
    if (helpFile.exists()) {
        FileUtils.forceDeleteOnExit(helpFile);
    } else {
        helpFile.createNewFile();
    }
    property.store(new FileOutputStream(helpFile), null);

}

From source file:de.tudarmstadt.ukp.clarin.webanno.api.dao.RepositoryServiceDbData.java

@Override
public <T> void saveUserSettings(String aUsername, Project aProject, Mode aSubject, T aConfigurationObject)
        throws IOException {
    BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(aConfigurationObject);
    Properties property = new Properties();
    for (PropertyDescriptor value : wrapper.getPropertyDescriptors()) {
        if (wrapper.getPropertyValue(value.getName()) == null) {
            continue;
        }/*from  w w  w  . ja va2  s.  c o  m*/
        property.setProperty(aSubject + "." + value.getName(),
                wrapper.getPropertyValue(value.getName()).toString());
    }
    String propertiesPath = dir.getAbsolutePath() + PROJECT + aProject.getId() + SETTINGS + aUsername;
    // append existing preferences for the other mode
    if (new File(propertiesPath, annotationPreferencePropertiesFileName).exists()) {
        // aSubject = aSubject.equals(Mode.ANNOTATION) ? Mode.CURATION :
        // Mode.ANNOTATION;
        for (Entry<Object, Object> entry : loadUserSettings(aUsername, aProject).entrySet()) {
            String key = entry.getKey().toString();
            // Maintain other Modes of annotations confs than this one
            if (!key.substring(0, key.indexOf(".")).equals(aSubject.toString())) {
                property.put(entry.getKey(), entry.getValue());
            }
        }
    }
    FileUtils.forceDeleteOnExit(new File(propertiesPath, annotationPreferencePropertiesFileName));
    FileUtils.forceMkdir(new File(propertiesPath));
    property.store(new FileOutputStream(new File(propertiesPath, annotationPreferencePropertiesFileName)),
            null);

    createLog(aProject).info(" Saved preferences file [" + annotationPreferencePropertiesFileName
            + "] for project [" + aProject.getName() + "] with ID [" + aProject.getId() + "] to location: ["
            + propertiesPath + "]");
    createLog(aProject).removeAllAppenders();

}

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

/**
 * Derive metadata from standard annotations such as JPA and FindBugs.
 * /*from  w w w. j  a  v  a  2 s.  c  o m*/
 * @param descriptor
 * @param elementMetaData
 */
private void deriveElementFromAnnotations(PropertyDescriptor descriptor, ElementMetaData elementMetaData) {
    // NOTE: !!! The annotation classes must be present at runtime, otherwise getAnnotations() doesn't
    // return the annotation.
    Method readMethod = descriptor.getReadMethod();
    if (readMethod != null) {
        processElementAnnotations(elementMetaData, readMethod.getAnnotations());
    }

    Method writeMethod = descriptor.getWriteMethod();
    if (writeMethod != null) {
        processElementAnnotations(elementMetaData, writeMethod.getAnnotations());
    }

    // Collects annotations on fields
    // Patch submitted by Richard O'Sullivan, fixes issue 9
    try {
        java.lang.reflect.Field beanField = beanClass.getDeclaredField(descriptor.getName());
        processElementAnnotations(elementMetaData, beanField.getAnnotations());
    } catch (Exception e) {
        // no foul, no harm.
    }
}

From source file:com.bstek.dorado.idesupport.initializer.CommonRuleTemplateInitializer.java

protected List<AutoChildTemplate> getChildTemplates(RuleTemplate ruleTemplate, TypeInfo typeInfo,
        XmlNodeInfo xmlNodeInfo, InitializerContext initializerContext) throws Exception {
    List<AutoChildTemplate> childTemplates = new ArrayList<AutoChildTemplate>();
    if (xmlNodeInfo != null) {
        for (XmlSubNode xmlSubNode : xmlNodeInfo.getSubNodes()) {
            TypeInfo propertyTypeInfo = TypeInfo.parse(xmlSubNode.propertyType());
            List<AutoChildTemplate> childRulesBySubNode = getChildTemplatesBySubNode(ruleTemplate, typeInfo,
                    xmlSubNode.propertyName(), xmlSubNode, propertyTypeInfo, initializerContext);
            if (childRulesBySubNode != null) {
                childTemplates.addAll(childRulesBySubNode);
            }/*from   ww w . j  a  v  a  2  s .  c  o m*/
        }
    }

    Class<?> type = typeInfo.getType();
    PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(type);
    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
        Method readMethod = propertyDescriptor.getReadMethod();
        if (readMethod != null) {
            if (readMethod.getDeclaringClass() != type) {
                try {
                    readMethod = type.getDeclaredMethod(readMethod.getName(), readMethod.getParameterTypes());
                } catch (NoSuchMethodException e) {
                    continue;
                }
            }

            List<AutoChildTemplate> childTemplatesBySubNode = null;
            XmlSubNode xmlSubNode = readMethod.getAnnotation(XmlSubNode.class);
            if (xmlSubNode != null) {
                TypeInfo propertyTypeInfo;
                Class<?> propertyType = propertyDescriptor.getPropertyType();
                if (Collection.class.isAssignableFrom(propertyType)) {
                    propertyTypeInfo = TypeInfo.parse((ParameterizedType) readMethod.getGenericReturnType(),
                            true);
                    propertyType = propertyTypeInfo.getType();
                } else {
                    propertyTypeInfo = new TypeInfo(propertyType, false);
                }

                childTemplatesBySubNode = getChildTemplatesBySubNode(ruleTemplate, typeInfo,
                        propertyDescriptor.getName(), xmlSubNode, propertyTypeInfo, initializerContext);
            }

            if (childTemplatesBySubNode != null) {
                IdeSubObject ideSubObject = readMethod.getAnnotation(IdeSubObject.class);
                if (ideSubObject != null && !ideSubObject.visible()) {
                    for (AutoChildTemplate childTemplate : childTemplatesBySubNode) {
                        childTemplate.setVisible(false);
                    }
                }
                childTemplates.addAll(childTemplatesBySubNode);
            }
        }
    }
    return childTemplates;
}