Example usage for org.springframework.beans BeanWrapperImpl getPropertyValue

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

Introduction

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

Prototype

@Override
    @Nullable
    public Object getPropertyValue(String propertyName) throws BeansException 

Source Link

Usage

From source file:acromusashi.stream.bean.FieldExtractor.java

/**
 * Extract field // ww  w  .j ava  2s.c  o m
 * 
 * @param target is used to get object data.
 * @param key is used to get key value.
 * @param delimeter key delimeter
 * @return is used to return object data.
 */
public static Object extract(Object target, String key, String delimeter) {
    if (target == null) {
        return target;
    }

    String keyHead = extractKeyHead(key, delimeter); // the return value of keyHead 
    String keyTail = extractKeyTail(key, delimeter); // the return value of keyTail 

    Object innerObject = null;

    // checking if the "Object: target" is Map or not
    if (target instanceof Map) {
        Map<?, ?> targetMap = (Map<?, ?>) target;
        innerObject = targetMap.get(keyHead); // get the object inside "keyHead"
    } else {
        BeanWrapperImpl baseWapper = new BeanWrapperImpl(target); // this is the reflection for getting the field value.
        innerObject = baseWapper.getPropertyValue(keyHead); // get the value from the field if the "keyHead" is not Map
    }

    if (innerObject == null) {
        return innerObject;
    }

    if (StringUtils.isEmpty(keyTail) == true) {
        return innerObject;
    } else {
        return extract(innerObject, keyTail, delimeter); // recursive method for calling self function again.
    }
}

From source file:org.springjutsu.validation.util.RequestUtils.java

/**
 * Used by successView and validationFailureView.
 * If the user specifies a path containing RESTful url
 * wildcards, evaluate those wildcard expressions against 
 * the current model map, and plug them into the url.
 * If the wildcard is a multisegmented path, get the top level
 * bean from the model map, and fetch the sub path using 
 * a beanwrapper instance./*w w  w .  j  av a 2 s. c om*/
 * @param viewName The view potentially containing wildcards
 * @param model the model map 
 * @param request the request
 * @return a wildcard-substituted view name
 */
@SuppressWarnings("unchecked")
public static String replaceRestPathVariables(String viewName, Map<String, Object> model,
        HttpServletRequest request) {
    String newViewName = viewName;
    Matcher matcher = Pattern.compile(PATH_VAR_PATTERN).matcher(newViewName);
    while (matcher.find()) {
        String match = matcher.group();
        String varName = match.substring(1, match.length() - 1);
        String baseVarName = null;
        String subPath = null;
        if (varName.contains(".")) {
            baseVarName = varName.substring(0, varName.indexOf("."));
            subPath = varName.substring(varName.indexOf(".") + 1);
        } else {
            baseVarName = varName;
        }
        Map<String, String> uriTemplateVariables = (Map<String, String>) request
                .getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
        if (uriTemplateVariables != null && uriTemplateVariables.containsKey(varName)) {
            newViewName = newViewName.replace(match, String.valueOf(uriTemplateVariables.get(varName)));
        } else {
            Object resolvedObject = model.get(baseVarName);
            if (resolvedObject == null) {
                throw new IllegalArgumentException(varName + " is not present in model.");
            }
            if (subPath != null) {
                BeanWrapperImpl beanWrapper = new BeanWrapperImpl(resolvedObject);
                resolvedObject = beanWrapper.getPropertyValue(subPath);
            }
            if (resolvedObject == null) {
                throw new IllegalArgumentException(varName + " is not present in model.");
            }
            newViewName = newViewName.replace(match, String.valueOf(resolvedObject));
        }
        matcher.reset(newViewName);
    }
    return newViewName;
}

From source file:cn.guoyukun.spring.jpa.entity.search.utils.SearchableConvertUtils.java

private static Object getConvertedValue(final BeanWrapperImpl beanWrapper, final String searchProperty,
        final String entityProperty, final Object value) {

    Object newValue;//from w  w w .  j ava2 s. co m
    try {

        beanWrapper.setPropertyValue(entityProperty, value);
        newValue = beanWrapper.getPropertyValue(entityProperty);
    } catch (InvalidPropertyException e) {
        throw new InvalidSearchPropertyException(searchProperty, entityProperty, e);
    } catch (Exception e) {
        throw new InvalidSearchValueException(searchProperty, entityProperty, value, e);
    }

    return newValue;
}

From source file:org.wallride.web.support.ControllerUtils.java

public static MultiValueMap<String, String> convertBeanForQueryParams(Object target,
        ConversionService conversionService) {
    BeanWrapperImpl beanWrapper = new BeanWrapperImpl(target);
    beanWrapper.setConversionService(conversionService);
    MultiValueMap<String, String> queryParams = new LinkedMultiValueMap();
    for (PropertyDescriptor pd : beanWrapper.getPropertyDescriptors()) {
        if (beanWrapper.isWritableProperty(pd.getName())) {
            Object pv = beanWrapper.getPropertyValue(pd.getName());
            if (pv != null) {
                if (pv instanceof Collection) {
                    if (!CollectionUtils.isEmpty((Collection) pv)) {
                        for (Object element : (Collection) pv) {
                            queryParams.set(pd.getName(), convertPropertyValueForString(target, pd, element));
                        }/*from  ww  w  .j a va 2 s .c  om*/
                    }
                } else {
                    queryParams.set(pd.getName(), convertPropertyValueForString(target, pd, pv));
                }
            }
        }
    }
    return queryParams;
}

From source file:org.zkoss.spring.security.SecurityUtil.java

/**
 * Return the evaluated result per the given property of the current 
 * Authentication object.//from  w w  w  .ja  v a2  s .  c o  m
 * 
 * @param property Property of the Authentication object which would be 
 * evaluated. Supports nested properties. For example if the principal 
 * object is an instance of UserDetails, the property "principal.username" 
 * will return the username. Alternatively, using "name" will call getName 
 * method on the Authentication object directly.
 * 
 * @return the evaluated result of the current Authentication object per the
 * given property.
 */
public static Object getAuthentication(String property) {
    // determine the value by...
    if (property != null) {
        if ((SecurityContextHolder.getContext() == null)
                || !(SecurityContextHolder.getContext() instanceof SecurityContext)
                || (SecurityContextHolder.getContext().getAuthentication() == null)) {
            return null;
        }

        Authentication auth = SecurityContextHolder.getContext().getAuthentication();

        if (auth.getPrincipal() == null) {
            return null;
        }

        try {
            BeanWrapperImpl wrapper = new BeanWrapperImpl(auth);
            return wrapper.getPropertyValue(property);
        } catch (BeansException e) {
            throw new UiException(e);
        }
    }
    return null;
}

From source file:com.predic8.membrane.annot.bean.MCUtil.java

@SuppressWarnings("unchecked")
public static <T> T clone(T object, boolean deep) {
    try {/*from   w w  w.ja  va 2  s . c  o  m*/
        if (object == null)
            throw new InvalidParameterException("'object' must not be null.");

        Class<? extends Object> clazz = object.getClass();

        MCElement e = clazz.getAnnotation(MCElement.class);
        if (e == null)
            throw new IllegalArgumentException("'object' must be @MCElement-annotated.");

        BeanWrapperImpl dst = new BeanWrapperImpl(clazz);
        BeanWrapperImpl src = new BeanWrapperImpl(object);

        for (Method m : clazz.getMethods()) {
            if (!m.getName().startsWith("set"))
                continue;
            String propertyName = AnnotUtils.dejavaify(m.getName().substring(3));
            MCAttribute a = m.getAnnotation(MCAttribute.class);
            if (a != null) {
                dst.setPropertyValue(propertyName, src.getPropertyValue(propertyName));
            }
            MCChildElement c = m.getAnnotation(MCChildElement.class);
            if (c != null) {
                if (deep) {
                    dst.setPropertyValue(propertyName, cloneInternal(src.getPropertyValue(propertyName), deep));
                } else {
                    dst.setPropertyValue(propertyName, src.getPropertyValue(propertyName));
                }
            }
            MCOtherAttributes o = m.getAnnotation(MCOtherAttributes.class);
            if (o != null) {
                dst.setPropertyValue(propertyName, src.getPropertyValue(propertyName));
            }
            MCTextContent t = m.getAnnotation(MCTextContent.class);
            if (t != null) {
                dst.setPropertyValue(propertyName, src.getPropertyValue(propertyName));
            }
        }

        return (T) dst.getRootInstance();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.predic8.membrane.annot.bean.MCUtil.java

private static void addXML(Object object, String id, XMLStreamWriter xew, SerializationContext sc)
        throws XMLStreamException {
    if (object == null)
        throw new InvalidParameterException("'object' must not be null.");

    Class<? extends Object> clazz = object.getClass();

    MCElement e = clazz.getAnnotation(MCElement.class);
    if (e == null)
        throw new IllegalArgumentException("'object' must be @MCElement-annotated.");

    BeanWrapperImpl src = new BeanWrapperImpl(object);

    xew.writeStartElement(e.name());/*from w  w  w.  ja  v  a  2  s  .  c  o  m*/

    if (id != null)
        xew.writeAttribute("id", id);

    HashSet<String> attributes = new HashSet<String>();
    for (Method m : clazz.getMethods()) {
        if (!m.getName().startsWith("set"))
            continue;
        String propertyName = AnnotUtils.dejavaify(m.getName().substring(3));
        MCAttribute a = m.getAnnotation(MCAttribute.class);
        if (a != null) {
            Object value = src.getPropertyValue(propertyName);
            String str;
            if (value == null)
                continue;
            else if (value instanceof String)
                str = (String) value;
            else if (value instanceof Boolean)
                str = ((Boolean) value).toString();
            else if (value instanceof Integer)
                str = ((Integer) value).toString();
            else if (value instanceof Long)
                str = ((Long) value).toString();
            else if (value instanceof Enum<?>)
                str = value.toString();
            else {
                MCElement el = value.getClass().getAnnotation(MCElement.class);
                if (el != null) {
                    str = defineBean(sc, value, null, true);
                } else {
                    str = "?";
                    sc.incomplete = true;
                }
            }

            if (a.attributeName().length() > 0)
                propertyName = a.attributeName();

            attributes.add(propertyName);
            xew.writeAttribute(propertyName, str);
        }
    }
    for (Method m : clazz.getMethods()) {
        if (!m.getName().startsWith("set"))
            continue;
        String propertyName = AnnotUtils.dejavaify(m.getName().substring(3));
        MCOtherAttributes o = m.getAnnotation(MCOtherAttributes.class);
        if (o != null) {
            Object value = src.getPropertyValue(propertyName);
            if (value instanceof Map<?, ?>) {
                Map<?, ?> map = (Map<?, ?>) value;
                for (Map.Entry<?, ?> entry : map.entrySet()) {
                    Object key = entry.getKey();
                    Object val = entry.getValue();
                    if (!(key instanceof String) || !(val instanceof String)) {
                        sc.incomplete = true;
                        key = "incompleteAttributes";
                        val = "?";
                    }
                    if (attributes.contains(key))
                        continue;
                    attributes.add((String) key);
                    xew.writeAttribute((String) key, (String) val);
                }
            } else {
                xew.writeAttribute("incompleteAttributes", "?");
                sc.incomplete = true;
            }
        }
    }

    List<Method> childElements = new ArrayList<Method>();
    for (Method m : clazz.getMethods()) {
        if (!m.getName().startsWith("set"))
            continue;
        String propertyName = AnnotUtils.dejavaify(m.getName().substring(3));

        MCChildElement c = m.getAnnotation(MCChildElement.class);
        if (c != null) {
            childElements.add(m);
        }
        MCTextContent t = m.getAnnotation(MCTextContent.class);
        if (t != null) {
            Object value = src.getPropertyValue(propertyName);
            if (value == null) {
                continue;
            } else if (value instanceof String) {
                xew.writeCharacters((String) value);
            } else {
                xew.writeCharacters("?");
                sc.incomplete = true;
            }
        }
    }

    Collections.sort(childElements, new Comparator<Method>() {

        @Override
        public int compare(Method o1, Method o2) {
            MCChildElement c1 = o1.getAnnotation(MCChildElement.class);
            MCChildElement c2 = o2.getAnnotation(MCChildElement.class);
            return c1.order() - c2.order();
        }
    });

    for (Method m : childElements) {
        String propertyName = AnnotUtils.dejavaify(m.getName().substring(3));

        Object value = src.getPropertyValue(propertyName);
        if (value != null) {
            if (value instanceof Collection<?>) {
                for (Object item : (Collection<?>) value)
                    addXML(item, null, xew, sc);
            } else {
                addXML(value, null, xew, sc);
            }
        }
    }

    xew.writeEndElement();
}

From source file:pl.chilldev.facelets.taglib.spring.security.AuthenticationTag.java

/**
 * {@inheritDoc}/* www.j a v  a2  s.  c o m*/
 *
 * @since 0.0.1
 */
@Override
public void apply(FaceletContext context, UIComponent parent) {
    String property = this.property.getValue(context);
    Object value = null;
    SecurityContext securityContext = SecurityContextHolder.getContext();

    // if there is no authentication object we can't process the property expression
    Authentication auth = securityContext.getAuthentication();
    if (auth != null) {
        try {
            BeanWrapperImpl wrapper = new BeanWrapperImpl(auth);
            value = wrapper.getPropertyValue(property);
        } catch (BeansException error) {
            throw new FacesException(error);
        }
    }

    // just output the text
    if (this.var == null) {
        UIOutput component = new UIOutput();
        component.setValue(value);
        parent.getChildren().add(component);
    } else {
        // assign result to the variable
        context.setAttribute(this.var.getValue(context), value);
    }
}

From source file:com.googlecode.spring.appengine.taglib.UserTag.java

@Override
public int doEndTag() throws JspException {
    Object result = null;//w w w.j a v  a  2s . co  m
    if (property != null) {
        User user = UserServiceFactory.getUserService().getCurrentUser();
        if (user != null) {
            try {
                BeanWrapperImpl wrapper = new BeanWrapperImpl(user);
                result = wrapper.getPropertyValue(property);
            } catch (BeansException e) {
                throw new JspException(e);
            }
        }
    }
    if (var == null) {
        try {
            pageContext.getOut().print(result);
        } catch (IOException e) {
            throw new JspException(e);
        }
    } else {
        pageContext.setAttribute(var, result, scope);
    }
    return Tag.EVAL_PAGE;
}

From source file:kr.okplace.job.launch.DefaultJobLoader.java

public Object getProperty(String path) {
    int index = PropertyAccessorUtils.getFirstNestedPropertySeparatorIndex(path);
    BeanWrapperImpl wrapper = createBeanWrapper(path, index);
    String key = path.substring(index + 1);
    return wrapper.getPropertyValue(key);
}