Example usage for org.springframework.beans BeanWrapper getPropertyDescriptors

List of usage examples for org.springframework.beans BeanWrapper getPropertyDescriptors

Introduction

In this page you can find the example usage for org.springframework.beans BeanWrapper getPropertyDescriptors.

Prototype

PropertyDescriptor[] getPropertyDescriptors();

Source Link

Document

Obtain the PropertyDescriptors for the wrapped object (as determined by standard JavaBeans introspection).

Usage

From source file:com.emc.ecs.sync.service.SyncJobService.java

protected void copyProperties(Object source, Object target, String... ignoredProperties) {
    List<String> ignoredList = Collections.emptyList();
    if (ignoredProperties != null)
        ignoredList = Arrays.asList(ignoredProperties);
    BeanWrapper wSource = new BeanWrapperImpl(source), wTarget = new BeanWrapperImpl(target);
    wSource.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat(ISO_8601_FORMAT), true));
    wTarget.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat(ISO_8601_FORMAT), true));
    for (PropertyDescriptor descriptor : wSource.getPropertyDescriptors()) {
        if (ignoredList.contains(descriptor.getName()))
            continue;
        if (!wSource.isReadableProperty(descriptor.getName()))
            continue;
        if (wTarget.isWritableProperty(descriptor.getName())) {

            // property is readable from source, writeable on target, and not in the list of ignored props
            Object value = wSource.getPropertyValue(descriptor.getName());
            if (value != null)
                wTarget.setPropertyValue(descriptor.getName(), value);
        }//from   w w w. ja va2 s .  c  o m
    }
}

From source file:net.solarnetwork.node.support.XmlServiceSupport.java

/**
 * Turn an object into a simple XML Element, supporting custom property
 * editors./*w  ww  . j  a  v a2s .c o m*/
 * 
 * <p>
 * The returned XML will be a single element with all JavaBean properties
 * turned into attributes. For example:
 * <p>
 * 
 * <pre>
 * &lt;powerDatum
 *   id="123"
 *   pvVolts="123.123"
 *   ... /&gt;
 * </pre>
 * 
 * <p>
 * {@link PropertyEditor} instances can be registered with the supplied
 * {@link BeanWrapper} for custom handling of properties, e.g. dates.
 * </p>
 * 
 * @param bean
 *        the object to turn into XML
 * @param elementName
 *        the name of the XML element
 * @return the element, as an XML DOM Element
 */
protected Element getElement(BeanWrapper bean, String elementName, Document dom) {
    PropertyDescriptor[] props = bean.getPropertyDescriptors();
    Element root = null;
    root = dom.createElement(elementName);
    for (int i = 0; i < props.length; i++) {
        PropertyDescriptor prop = props[i];
        if (prop.getReadMethod() == null) {
            continue;
        }
        String propName = prop.getName();
        if ("class".equals(propName)) {
            continue;
        }
        Object propValue = null;
        PropertyEditor editor = bean.findCustomEditor(prop.getPropertyType(), prop.getName());
        if (editor != null) {
            editor.setValue(bean.getPropertyValue(propName));
            propValue = editor.getAsText();
        } else {
            propValue = bean.getPropertyValue(propName);
        }
        if (propValue == null) {
            continue;
        }
        if (log.isTraceEnabled()) {
            log.trace("attribute name: " + propName + " attribute value: " + propValue);
        }
        root.setAttribute(propName, propValue.toString());
    }
    return root;
}

From source file:net.solarnetwork.node.support.XmlServiceSupport.java

private void writeURLEncodedBeanProperties(BeanWrapper bean, Map<String, ?> attributes, Writer out)
        throws IOException {
    PropertyDescriptor[] props = bean.getPropertyDescriptors();
    boolean propsWritten = false;
    if (attributes != null && attributes.containsKey(ATTR_NODE_ID)) {
        out.write("nodeId=" + attributes.get(ATTR_NODE_ID));
        propsWritten = true;//from ww  w. j  av  a2s.  c om
    }
    for (int i = 0; i < props.length; i++) {
        PropertyDescriptor prop = props[i];
        if (prop.getReadMethod() == null) {
            continue;
        }
        String propName = prop.getName();
        if ("class".equals(propName)) {
            continue;
        }
        Object propValue = null;
        if (attributes != null && attributes.containsKey(propName)) {
            propValue = attributes.get(propName);
        } else {
            PropertyEditor editor = bean.findCustomEditor(prop.getPropertyType(), prop.getName());
            if (editor != null) {
                editor.setValue(bean.getPropertyValue(propName));
                propValue = editor.getAsText();
            } else {
                propValue = bean.getPropertyValue(propName);
            }
        }
        if (propValue == null) {
            continue;
        }
        if (propsWritten) {
            out.write("&");
        }
        out.write(propName);
        out.write("=");
        out.write(URLEncoder.encode(propValue.toString(), "UTF-8"));
        propsWritten = true;
    }
    out.flush();
    out.close();
}

From source file:org.jdal.ui.ViewSupport.java

/**
 * Bind controls following the same name convention or annotated with Property annotation.
 *//*from ww w . j  a  v a2s .  c o  m*/
public void autobind() {
    BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(getModel());
    PropertyAccessor viewPropertyAccessor = new DirectFieldAccessor(this);

    // Parse Property annotations
    List<AnnotatedElement> elements = AnnotatedElementAccessor.findAnnotatedElements(Property.class,
            getClass());

    for (AnnotatedElement ae : elements) {
        Property p = ae.getAnnotation(Property.class);
        InitializationConfig config = getInitializationConfig(ae.getAnnotation(Initializer.class));
        bindAndInitializeControl(p.value(), viewPropertyAccessor.getPropertyValue(((Field) ae).getName()),
                config);
        this.ignoredProperties.add(p.value());
    }

    // Iterate on model properties
    for (PropertyDescriptor pd : bw.getPropertyDescriptors()) {
        String propertyName = pd.getName();
        if (!ignoredProperties.contains(propertyName)
                && viewPropertyAccessor.isReadableProperty(propertyName)) {
            Object control = viewPropertyAccessor.getPropertyValue(propertyName);

            if (control != null) {
                if (log.isDebugEnabled())
                    log.debug("Found control: " + control.getClass().getSimpleName() + " for property: "
                            + propertyName);
                TypeDescriptor descriptor = viewPropertyAccessor.getPropertyTypeDescriptor(propertyName);
                InitializationConfig config = getInitializationConfig(
                        descriptor.getAnnotation(Initializer.class));
                // do bind
                bindAndInitializeControl(propertyName, control, config);
            }
        }
    }
}

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 .j a va 2  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: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 w  w  w  .  j a v a  2s  . c o  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:edu.northwestern.bioinformatics.studycalendar.web.admin.AdministerUserCommand.java

private void copyBoundProperties(User src, User dst) {
    BeanWrapper srcW = new BeanWrapperImpl(src);
    BeanWrapper dstW = new BeanWrapperImpl(dst);

    for (PropertyDescriptor srcProp : srcW.getPropertyDescriptors()) {
        if (srcProp.getReadMethod() == null || srcProp.getWriteMethod() == null) {
            continue;
        }//from  www.  j av  a 2s.  c om
        Object srcValue = srcW.getPropertyValue(srcProp.getName());
        if (srcValue != null) {
            dstW.setPropertyValue(srcProp.getName(), srcValue);
        }
    }
}

From source file:es.pode.soporte.auditoria.registrar.BeanDescripcion.java

/** 
 * Mtodo para recuperar informacin de un objeto a travs de reflexin 
 *   /* ww  w . j a  v  a 2s.  com*/
 * @param objeto Objeto al cual se le realiza la reflexin 
 * @param atributo Valor que se recupera del objeto
 * @return valor Se devuelve el valor del atributo buscado
 */
public static String describe(Object objeto, String atributo) {

    if (objeto == null)
        return null;

    Object valor = null;

    Class clase = objeto.getClass();
    if (clase.isArray() || java.util.Collection.class.isAssignableFrom(clase))
        log.warn("El atributo es un array y debera ser un String");
    else {
        log("Reflexin del objeto: " + objeto);

        BeanWrapper wrapper = new BeanWrapperImpl(objeto);
        PropertyDescriptor descriptors[] = wrapper.getPropertyDescriptors();

        for (int i = 0; i < descriptors.length; i++) {
            PropertyDescriptor pd = descriptors[i];

            if (pd.getReadMethod() != null && pd.getWriteMethod() != null) {
                String name = pd.getName();

                /* Capturamos el valor del atributo que nos interesa */
                if (name.equals(atributo)) {
                    log("Nombre atributo: " + name);
                    valor = wrapper.getPropertyValue(name);

                    /* Si el valor es nulo registramos un "" */
                    if (valor == null) {
                        log("El valor del atributo interceptado es nulo");
                        return null;
                    } else
                        return valor.toString();
                }
            }
        }
    }

    return null;
}

From source file:jp.terasoluna.fw.web.struts.actions.FileDownloadUtil.java

/**
 * uEU_E??[h?B//  ww  w .ja  v  a  2 s .  com
 *
 * @param result _E??[hf?[^?CX^X?B
 * @param request NGXg?B
 * @param response X|X?B
 */
@SuppressWarnings("unchecked")
public static void download(Object result, HttpServletRequest request, HttpServletResponse response) {
    List<AbstractDownloadObject> downloadList = new ArrayList<AbstractDownloadObject>();

    if (result instanceof AbstractDownloadObject) {
        downloadList.add((AbstractDownloadObject) result);
    } else {
        BeanWrapper wrapper = new BeanWrapperImpl(result);
        PropertyDescriptor[] propertyDescriptors = wrapper.getPropertyDescriptors();
        for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
            Method readMethod = propertyDescriptor.getReadMethod();
            if (readMethod == null) {
                continue;
            }
            Class type = readMethod.getReturnType();
            if (AbstractDownloadObject.class.isAssignableFrom(type)) {
                downloadList
                        .add((AbstractDownloadObject) wrapper.getPropertyValue(propertyDescriptor.getName()));
            }
        }
    }

    if (downloadList.isEmpty()) {
        return;
    }
    // _E??[hIuWFNg???O
    if (downloadList.size() != 1) {
        throw new SystemException(new IllegalStateException("Too many AbstractDownloadObject properties."),
                TOO_MANY_DOWNLOAD_ERROR);
    }

    try {
        download(downloadList.get(0), request, response, true);
    } catch (SocketException e) {
        if (log.isDebugEnabled()) {
            log.debug(e.getMessage(), e);
        }
    } catch (IOException e) {
        if (log.isErrorEnabled()) {
            log.error("IOException has occurred while downloading", e);
        }
    }
}