public static void add(Composable source, Composable target, double mnoznik) {

    BeanWrapper wrapperSource = new BeanWrapperImpl(source);
    BeanWrapper wrapperTarget = new BeanWrapperImpl(target);

    for (int i = 0; i < wrapperSource.getPropertyDescriptors().length; ++i) {

      String propName = wrapperSource.getPropertyDescriptors()[i].getName();

      if (wrapperSource.isReadableProperty(propName)) {
        Object propValue = wrapperSource.getPropertyValue(propName);

        if (propValue != null) {

          if (propValue instanceof Composable) {
            if ((Composable) wrapperTarget.getPropertyValue(propName) == null)
              System.out.println(propName);
            add(
                (Composable) propValue,
                (Composable) wrapperTarget.getPropertyValue(propName),
                mnoznik);
          } else if (propValue instanceof Double) {
            if (wrapperTarget.getPropertyValue(propName) == null)
              wrapperTarget.setPropertyValue(propName, 0.0);
            wrapperTarget.setPropertyValue(
                propName,
                ((Double) wrapperTarget.getPropertyValue(propName)) + mnoznik * (Double) propValue);
          }
        }
      }
    }
  }
 public Object get(Object key) {
   String objectKey = (String) key;
   if (beanWrapper.isReadableProperty(objectKey)) {
     return beanWrapper.getPropertyValue(objectKey);
   } else {
     return thisWrapper.getPropertyValue(objectKey);
   }
 }
  /**
   * Get the value of the named property, with support for static properties in both Java and Groovy
   * classes (which as of Groovy JSR 1.0 RC 01 only have getters in the metaClass)
   *
   * @param name
   * @param type
   * @return The property value or null
   */
  public Object getPropertyValue(String name, Class type) {

    // Handle standard java beans normal or static properties
    BeanWrapper ref = getReference();
    Object value = null;
    if (ref.isReadableProperty(name)) {
      value = ref.getPropertyValue(name);
    } else {
      // Groovy workaround
      Object inst = ref.getWrappedInstance();
      if (inst instanceof GroovyObject) {
        final Map properties = DefaultGroovyMethods.getProperties(inst);
        if (properties.containsKey(name)) {
          value = properties.get(name);
        }
      }
    }

    if (value != null
        && (type.isAssignableFrom(value.getClass())
            || GrailsClassUtils.isMatchBetweenPrimativeAndWrapperTypes(type, value.getClass()))) {
      return value;
    } else {
      return null;
    }
  }
Exemple #4
0
 /** Return the indexes available for this field (for repeated fields ad List) */
 public List<Integer> indexes() {
   List<Integer> result = new ArrayList<Integer>();
   if (form.value().isDefined()) {
     BeanWrapper beanWrapper = new BeanWrapperImpl(form.value().get());
     beanWrapper.setAutoGrowNestedPaths(true);
     String objectKey = name;
     if (form.name() != null && name.startsWith(form.name() + ".")) {
       objectKey = name.substring(form.name().length() + 1);
     }
     if (beanWrapper.isReadableProperty(objectKey)) {
       Object value = beanWrapper.getPropertyValue(objectKey);
       if (value instanceof Collection) {
         for (int i = 0; i < ((Collection) value).size(); i++) {
           result.add(i);
         }
       }
     }
   } else {
     java.util.regex.Pattern pattern =
         java.util.regex.Pattern.compile(
             "^" + java.util.regex.Pattern.quote(name) + "\\[(\\d+)\\].*$");
     for (String key : form.data().keySet()) {
       java.util.regex.Matcher matcher = pattern.matcher(key);
       if (matcher.matches()) {
         result.add(Integer.parseInt(matcher.group(1)));
       }
     }
   }
   return result;
 }
 @Override
 public Object getActionParameter(String param) {
   if (beanWrapper.isReadableProperty(param)) {
     return beanWrapper.getPropertyValue(param);
   }
   return null;
 }
Exemple #6
0
  /**
   * Converts the entity to a String.
   *
   * @param facesContext current faces context
   * @param component current component
   * @param value current value of the entity
   * @return value converted to string.
   */
  public String getAsString(
      final FacesContext facesContext, final UIComponent component, final Object value) {

    logger.debug(
        String.format(
            "getAsString called value=%s, component=%s, value class=%s",
            value, component.getClientId(facesContext), value.getClass().getName()));
    if (value == null) {
      logger.debug("Value was null, can't convert");
      return "";
    }

    if (value instanceof String) {
      logger.debug("Value was a string");
      return value.toString();
    }

    BeanWrapper bwValue = new BeanWrapperImpl(value);

    try {
      String sValue = bwValue.getPropertyValue(idPropertyName).toString();
      logger.debug(String.format("string value %s", sValue));
      return sValue;
    } catch (Exception ex) {
      logger.debug("Unable to find value returning -1");
      return "-1";
    }
  }
  public static double getMass(Composable source, Composed target) {

    double wynik = 0;

    BeanWrapper wrapper = new BeanWrapperImpl(source);

    for (Substance substance : target) {

      String propName =
          CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, substance.getSubstanceName());

      if (wrapper.isReadableProperty(propName)) {
        Object propValue = wrapper.getPropertyValue(propName);

        if (propValue != null) {

          if (propValue instanceof Composable) {
            wynik += Compositions.getMass((Composable) propValue, (Composed) substance);
          } else if (propValue instanceof Double) {
            wynik += (Double) propValue;
          }
        }
      }
    }

    return wynik;
  }
  /** Copy & Paste, 无修正. */
  private void writeObjectEntry(
      TagWriter tagWriter, String valueProperty, String labelProperty, Object item, int itemIndex)
      throws JspException {

    BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(item);
    Object renderValue;
    if (valueProperty != null) {
      renderValue = wrapper.getPropertyValue(valueProperty);
    } else if (item instanceof Enum) {
      renderValue = ((Enum<?>) item).name();
    } else {
      renderValue = item;
    }
    Object renderLabel = (labelProperty != null ? wrapper.getPropertyValue(labelProperty) : item);
    writeElementTag(tagWriter, item, renderValue, renderLabel, itemIndex);
  }
Exemple #9
0
  public static void main(String[] args) {
    bf = new ClassPathXmlApplicationContext("/Spring-beans.xml");

    System.out.println(bf.getBean("empresa"));

    BeanWrapper company = new BeanWrapperImpl((Empresa) bf.getBean("empresa"));
    company.setPropertyValue("nome", "Target Trust");

    // ou pode ser algo assim
    PropertyValue value = new PropertyValue("nome", "Some Company Inc.");
    company.setPropertyValue(value);

    BeanWrapper carlos = new BeanWrapperImpl((Funcionario) bf.getBean("gestor"));
    carlos.setPropertyValue("nome", "Carlos Santos");

    company.setPropertyValue("gestor", carlos.getWrappedInstance());

    Long sal = (Long) company.getPropertyValue("gestor.salario");
    System.out.println("Salário: " + sal);

    System.out.println(company);
    System.out.println(company.getWrappedInstance());

    //		// verifica o tipo da propriedade salario
    //		System.out.println(((BeanWrapperImpl)
    // company).getPropertyDescriptor("gestor.salarlosrio").getPropertyType());

    //		carlos.setPropertyValue("salario", 200L);
    //		System.out.println(carlos.getPropertyValue("salario"));
  }
 @SuppressWarnings("unchecked")
 private void evaluatePluginInfluencePolicy() {
   if (pluginBean.isReadableProperty(INFLUENCES)) {
     List influencedList = (List) pluginBean.getPropertyValue(INFLUENCES);
     if (influencedList != null) {
       influencedPluginNames =
           (String[]) influencedList.toArray(new String[influencedList.size()]);
     }
   }
 }
 private Object getPropertyValue(String entityIdName) {
   Object propValue;
   try {
     propValue = wrap.getPropertyValue(entityIdName);
   } catch (NullValueInNestedPathException e) {
     if (ignoreNullsNestedPath) propValue = null;
     else throw e;
   }
   return propValue;
 }
 private boolean filterProperty(String name) {
   try {
     BeanWrapper bw = new BeanWrapperImpl(getEntityClass().newInstance());
     bw.getPropertyValue(name);
   } catch (Exception e) {
     log.error("Could not resolve property:" + name, e);
     return false;
   }
   return true;
 }
  /**
   * Read a property value using the property path by invoking a spring {@link BeanWrapper}
   *
   * @param propertyPath
   * @param instance
   * @return the property value found on the property path applied to the provided instance.
   */
  @Override
  public Object doReadPropertyValue(String propertyPath, Object instance) {
    BeanWrapper beanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(instance);

    // check if it's safe to write the property.
    if (!beanWrapper.isReadableProperty(propertyPath)) {
      return null;
    }

    return beanWrapper.getPropertyValue(propertyPath);
  }
  /** Copy & Paste, 无修正. */
  private void writeMapEntry(
      TagWriter tagWriter,
      String valueProperty,
      String labelProperty,
      Map.Entry entry,
      int itemIndex)
      throws JspException {

    Object mapKey = entry.getKey();
    Object mapValue = entry.getValue();
    BeanWrapper mapKeyWrapper = PropertyAccessorFactory.forBeanPropertyAccess(mapKey);
    BeanWrapper mapValueWrapper = PropertyAccessorFactory.forBeanPropertyAccess(mapValue);
    Object renderValue =
        (valueProperty != null ? mapKeyWrapper.getPropertyValue(valueProperty) : mapKey.toString());
    Object renderLabel =
        (labelProperty != null
            ? mapValueWrapper.getPropertyValue(labelProperty)
            : mapValue.toString());
    writeElementTag(tagWriter, mapKey, renderValue, renderLabel, itemIndex);
  }
Exemple #15
0
  /**
   * Find all occurrences of targetClass in targetObject. Be careful. This stuff may be recursive !
   * Should be improved to prevent endless recursive loops.
   *
   * @param
   * @return
   * @param targetObject
   * @param targetClass
   * @param nestedPath
   * @return
   * @throws Exception
   */
  public static Map<String, ?> findNestedPaths(
      Object targetObject,
      Class<?> targetClass,
      String nestedPath,
      List<String> ignoreList,
      Set<Object> visited,
      int maxDepth)
      throws Exception {

    Assert.notNull(targetObject);
    Assert.notNull(targetClass);
    Assert.notNull(ignoreList);
    HashMap<String, Object> nestedPaths = new HashMap<String, Object>();
    if (maxDepth <= 0) {
      return nestedPaths;
    }

    nestedPath = (nestedPath == null ? "" : nestedPath);
    BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(targetObject);
    PropertyDescriptor[] props = bw.getPropertyDescriptors();

    for (PropertyDescriptor pd : props) {
      Class<?> clazz = pd.getPropertyType();
      if (clazz != null
          && !clazz.equals(Class.class)
          && !clazz.isAnnotation()
          && !clazz.isPrimitive()) {
        Object value = null;
        String pathName = pd.getName();
        if (!ignoreList.contains(pathName)) {
          try {
            value = bw.getPropertyValue(pathName);
          } catch (Exception e) {
          } // ignore any exceptions here
          if (StringUtils.hasText(nestedPath)) {
            pathName = nestedPath + PropertyAccessor.NESTED_PROPERTY_SEPARATOR + pathName;
          }
          // TODO break up this stuff into checking and excecution a la ReflectionUtils
          if (targetClass.isAssignableFrom(clazz)) {
            nestedPaths.put(pathName, value);
          }
          // exclude objects already visited from further inspection to prevent circular references
          // unfortunately this stuff isn't fool proof as there are ConcurrentModificationExceptions
          // when adding objects to the visited list
          if (value != null && !isInstanceVisited(visited, value)) {
            nestedPaths.putAll(
                findNestedPaths(value, targetClass, pathName, ignoreList, visited, maxDepth - 1));
          }
        }
      }
    }
    return nestedPaths;
  }
  @Override
  public <T> T getActionParameter(String paramKey, Class<T> t) {
    if (t == null) {
      return null;
    }

    if (beanWrapper.isReadableProperty(paramKey)) {
      Object val = beanWrapper.getPropertyValue(paramKey);
      return (T) val;
    }

    return null;
  }
Exemple #17
0
  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;
      }
      Object srcValue = srcW.getPropertyValue(srcProp.getName());
      if (srcValue != null) {
        dstW.setPropertyValue(srcProp.getName(), srcValue);
      }
    }
  }
 public boolean isValid(final Object value, final ConstraintValidatorContext context) {
   boolean isValid = false;
   BeanWrapper beanWrapper = new BeanWrapperImpl(value);
   final Object field = beanWrapper.getPropertyValue(constraint.field());
   final Object match = beanWrapper.getPropertyValue(constraint.match());
   isValid = field == match || field != null && field.equals(match);
   if (!isValid) {
     context
         .buildConstraintViolationWithTemplate(constraint.message())
         .addNode(constraint.match())
         .addConstraintViolation();
   }
   return isValid;
 }
  private Object getPropertyValueForPath(Object target, String[] propertyNames) {
    BeanWrapper wrapper = new BeanWrapperImpl(target);
    Object obj = target;
    for (int i = 0; i < propertyNames.length - 1; i++) {
      String propertyName = propertyNames[i];
      if (wrapper.isReadableProperty(propertyName)) {
        obj = wrapper.getPropertyValue(propertyName);
        if (obj == null) break;
        wrapper = new BeanWrapperImpl(obj);
      }
    }

    return obj;
  }
  @Override
  public Map<String, Object> getActionParameters() {
    Class<?> wrappedClazz = beanWrapper.getWrappedInstance().getClass();

    Field[] fields = wrappedClazz.getDeclaredFields();
    Map<String, Object> params = new HashMap<String, Object>();
    for (Field field : fields) {
      String fieldProperty = field.getName();
      if (beanWrapper.isReadableProperty(fieldProperty)) {
        params.put(fieldProperty, beanWrapper.getPropertyValue(fieldProperty));
      }
    }
    return params;
  }
 /**
  * Looks for a property of the reference instance with a given name and type.
  *
  * <p>If found its value is returned. We follow the Java bean conventions with augmentation for
  * groovy support and static fields/properties. We will therefore match, in this order:
  *
  * <ol>
  *   <li>Standard public bean property (with getter or just public field, using normal
  *       introspection)
  *   <li>Public static property with getter method
  *   <li>Public static field
  * </ol>
  *
  * @return property value or null if no property or static field was found
  */
 protected Object getPropertyOrStaticPropertyOrFieldValue(String name, Class type) {
   BeanWrapper ref = getReference();
   Object value = null;
   if (ref.isReadableProperty(name)) {
     value = ref.getPropertyValue(name);
   } else if (GrailsClassUtils.isPublicField(ref.getWrappedInstance(), name)) {
     value = GrailsClassUtils.getFieldValue(ref.getWrappedInstance(), name);
   } else {
     value = GrailsClassUtils.getStaticPropertyValue(clazz, name);
   }
   if ((value != null) && GrailsClassUtils.isGroovyAssignableFrom(type, value.getClass())) {
     return value;
   }
   return null;
 }
  @SuppressWarnings("unchecked")
  private void bindCollectionAssociation(MutablePropertyValues mpvs, PropertyValue pv) {
    Object v = pv.getValue();

    Collection collection = (Collection) bean.getPropertyValue(pv.getName());
    collection.clear();
    final Class associatedType = getReferencedTypeForCollection(pv.getName(), getTarget());
    final boolean isArray = v != null && v.getClass().isArray();
    final PropertyEditor propertyEditor = findCustomEditor(collection.getClass(), pv.getName());
    if (propertyEditor == null) {
      if (isDomainAssociation(associatedType)) {
        if (isArray) {
          Object[] identifiers = (Object[]) v;
          for (Object id : identifiers) {
            if (id != null) {
              associateObjectForId(pv, id, associatedType);
            }
          }
          mpvs.removePropertyValue(pv);
        } else if (v != null && (v instanceof String)) {
          associateObjectForId(pv, v, associatedType);
          mpvs.removePropertyValue(pv);
        }
      } else if (GrailsDomainConfigurationUtil.isBasicType(associatedType)) {
        if (isArray) {
          Object[] values = (Object[]) v;
          List list = collection instanceof List ? (List) collection : null;
          for (int i = 0; i < values.length; i++) {
            Object value = values[i];
            try {
              Object newValue = getTypeConverter().convertIfNecessary(value, associatedType);
              if (list != null) {
                if (i > list.size() - 1) {
                  list.add(i, newValue);
                } else {
                  list.set(i, newValue);
                }
              } else {
                collection.add(newValue);
              }
            } catch (TypeMismatchException e) {
              // ignore
            }
          }
        }
      }
    }
  }
 private Class<?> getPropertyTypeForPath(String propertyName) {
   Class<?> type = bean.getPropertyType(propertyName);
   if (type == null) {
     // type not available via BeanWrapper - this happens with e.g. empty list indexes - so
     // find type by examining GrailsDomainClass
     Object target = bean.getWrappedInstance();
     String path = propertyName.replaceAll("\\[.+?\\]", "");
     if (path.indexOf(PATH_SEPARATOR) > -1) {
       // transform x.y.z into value of x.y and path z
       target = bean.getPropertyValue(StringUtils.substringBeforeLast(propertyName, "."));
       path = StringUtils.substringAfterLast(path, ".");
     }
     type = getReferencedTypeForCollection(path, target);
   }
   return type;
 }
 /**
  * Overrides the default behaviour and first checks if a PersistentCollection instance has been
  * initialised using the wasInitialised() method before cascading
  *
  * @param errors The Spring Errors instance
  * @param bean The BeanWrapper for the bean
  * @param persistentProperty The GrailsDomainClassProperty instance
  * @param propertyName The name of the property
  * @see org.hibernate.collection.PersistentCollection#wasInitialized()
  */
 protected void cascadeValidationToMany(
     Errors errors,
     BeanWrapper bean,
     GrailsDomainClassProperty persistentProperty,
     String propertyName) {
   Object collection = bean.getPropertyValue(propertyName);
   if (collection != null) {
     if (collection instanceof PersistentCollection) {
       PersistentCollection persistentCollection = (PersistentCollection) collection;
       if (persistentCollection.wasInitialized()) {
         super.cascadeValidationToMany(errors, bean, persistentProperty, propertyName);
       }
     } else {
       super.cascadeValidationToMany(errors, bean, persistentProperty, propertyName);
     }
   }
 }
  public static Object getPropertyOrStaticPropertyOrFieldValue(
      BeanWrapper ref, Object obj, String name) {
    if (ref.isReadableProperty(name)) {
      return ref.getPropertyValue(name);
    }
    // Look for public fields
    if (isPublicField(obj, name)) {
      return getFieldValue(obj, name);
    }

    // Look for statics
    Class<?> clazz = obj.getClass();
    if (isStaticProperty(clazz, name)) {
      return getStaticPropertyValue(clazz, name);
    }
    return null;
  }
  public Object getObject() throws BeansException {
    BeanWrapper target = this.targetBeanWrapper;
    if (target == null) {
      // fetch prototype target bean
      target = new BeanWrapperImpl(this.beanFactory.getBean(this.targetBeanName));
    }

    Object value = target.getPropertyValue(this.propertyPath);
    if (value == null) {
      throw new FatalBeanException(
          "PropertyPathFactoryBean is not allowed to return null, "
              + "but property value for path '"
              + this.propertyPath
              + "' is null");
    }
    return value;
  }
Exemple #27
0
  /**
   * 将对象中的属性值置入到fields中。
   *
   * <p>对于<code>isValidated()</code>为<code>true</code>的group,该方法无效。
   */
  public void mapTo(Object object) {
    if (isValidated() || object == null) {
      return;
    }

    if (log.isDebugEnabled()) {
      log.debug(
          "Mapping properties to fields: group=\"{}\", object={}",
          getName(),
          ObjectUtil.identityToString(object));
    }

    BeanWrapper bean = new BeanWrapperImpl(object);
    getForm().getFormConfig().getPropertyEditorRegistrar().registerCustomEditors(bean);

    for (Field field : getFields()) {
      String propertyName = field.getFieldConfig().getPropertyName();

      if (bean.isReadableProperty(propertyName)) {
        Object propertyValue = bean.getPropertyValue(propertyName);
        Class<?> propertyType = bean.getPropertyType(propertyName);
        PropertyEditor editor = bean.findCustomEditor(propertyType, propertyName);

        if (editor == null) {
          editor = BeanUtils.findEditorByConvention(propertyType);
        }

        if (editor == null) {
          if (propertyType.isArray()
              || CollectionFactory.isApproximableCollectionType(propertyType)) {
            field.setValues((String[]) bean.convertIfNecessary(propertyValue, String[].class));
          } else {
            field.setValue(bean.convertIfNecessary(propertyValue, String.class));
          }
        } else {
          editor.setValue(propertyValue);
          field.setValue(editor.getAsText());
        }
      } else {
        log.debug(
            "No readable property \"{}\" found in type {}",
            propertyName,
            object.getClass().getName());
      }
    }
  }
  /**
   * Set a property using the property path invoking a spring framework {@link BeanWrapper}.
   *
   * @param propertyPath
   * @param value
   * @param instance
   */
  @Override
  public void doWritePropertyValue(String propertyPath, Object value, Object instance) {
    BeanWrapper beanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(instance);

    // check and make up for missing association parts.
    StringBuilder builder = new StringBuilder();

    String[] subProps = StringUtils.split(propertyPath, '.');

    // go through all the parts but one
    for (int i = 0; i < subProps.length - 1; i++) {
      String prop = subProps[i];

      if (i > 0) {
        builder.append(".");
      }

      builder.append(prop);

      Object partialValue = beanWrapper.getPropertyValue(builder.toString());
      if (partialValue == null) {
        // make up for it
        Class propCls = beanWrapper.getPropertyType(builder.toString());
        Object madeUpValue = BeanClassUtils.createInstance(propCls);
        if (madeUpValue != null) {
          if (beanWrapper.isWritableProperty(builder.toString())) {
            beanWrapper.setPropertyValue(builder.toString(), madeUpValue);
          }
        }
      }
    }

    if (!beanWrapper.isWritableProperty(propertyPath)) {
      logger.info("Cannot write property path " + propertyPath + " of bean", instance);
      return;
    }

    // this can be improved by registering property editors on the bean wrapper
    // at moment this approach is not so simple as the current functionality.
    // nevertheless on the future this situation may change.
    Class expectedType = beanWrapper.getPropertyType(propertyPath);
    value = ValueConversionHelper.applyCompatibilityLogic(expectedType, value);

    beanWrapper.setPropertyValue(propertyPath, value);
  }
  /** {@inheritDoc} */
  @Override
  public Object getValue(String paramName) {
    Object value = null;
    if (privateFields.contains(paramName)) {
      value = beanWrapper.getPropertyValue(paramName);
    } else if (publicFeilds.containsKey(paramName)) {
      Field field = publicFeilds.get(paramName);
      try {
        value = field.get(entity);
      } catch (IllegalAccessException e) {
        throw new IllegalArgumentException(e);
      }
    }

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

    return Jsr310JdbcUtils.convertIfNecessary(value, zoneId);
  }
 private static void copyInternal(Composable source, Composed target, BeanWrapper parent) {
   // copy(source, target);
   if (target instanceof Mixture) {
     Mixture mixture = (Mixture) target;
     String totalPropName =
         CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, mixture.getSubstanceName() + "Total");
     if (parent.isReadableProperty(totalPropName)
         && parent.getPropertyType(totalPropName) == Double.class) {
       Double total = (Double) parent.getPropertyValue(totalPropName);
       if (total != null) {
         if (mixture.isComplete()) {
           double t = mixture.getAmount();
           mixture.setRemains(Math.max(total - t, 0.0));
         } else {
           mixture.setAmount(total);
         }
       }
     }
   }
 }