Exemplo n.º 1
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"));
  }
Exemplo n.º 2
0
  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 put(String key, Object value) {
   if (beanWrapper.isWritableProperty(key)) {
     beanWrapper.setPropertyValue(key, value);
   } else {
     thisWrapper.setPropertyValue(key, value);
   }
   return null;
 }
Exemplo n.º 4
0
  /**
   * Set annotation preferences of users for a given project such as window size, annotation
   * layers,... reading from the file system.
   *
   * @param aUsername The {@link User} for whom we need to read the preference (preferences are
   *     stored per user)
   * @param aRepositoryService the repository service.
   * @param aAnnotationService the annotation service.
   * @param aBModel The {@link BratAnnotatorModel} that will be populated with preferences from the
   *     file
   * @param aMode the mode.
   * @throws BeansException hum?
   * @throws IOException hum?
   */
  public static void setAnnotationPreference(
      String aUsername,
      RepositoryService aRepositoryService,
      AnnotationService aAnnotationService,
      BratAnnotatorModel aBModel,
      Mode aMode)
      throws BeansException, IOException {
    AnnotationPreference preference = new AnnotationPreference();
    BeanWrapper wrapper = new BeanWrapperImpl(preference);
    // get annotation preference from file system
    try {
      Properties props = aRepositoryService.loadUserSettings(aUsername, aBModel.getProject());
      for (Entry<Object, Object> entry : props.entrySet()) {
        String property = entry.getKey().toString();
        int index = property.lastIndexOf(".");
        String propertyName = property.substring(index + 1);
        String mode = property.substring(0, index);
        if (wrapper.isWritableProperty(propertyName) && mode.equals(aMode.getName())) {
          if (AnnotationPreference.class.getDeclaredField(propertyName).getGenericType()
              instanceof ParameterizedType) {
            List<String> value =
                Arrays.asList(
                    StringUtils.replaceChars(entry.getValue().toString(), "[]", "").split(","));
            if (!value.get(0).equals("")) {
              wrapper.setPropertyValue(propertyName, value);
            }
          } else {
            wrapper.setPropertyValue(propertyName, entry.getValue());
          }
        }
      }
      aBModel.setPreferences(preference);

      // Get tagset using the id, from the properties file
      aBModel.getAnnotationLayers().clear();
      if (preference.getAnnotationLayers() != null) {
        for (Long id : preference.getAnnotationLayers()) {
          aBModel.getAnnotationLayers().add(aAnnotationService.getLayer(id));
        }
      } else {
        // If no layer preferences are defined, then just assume all layers are enabled
        List<AnnotationLayer> layers = aAnnotationService.listAnnotationLayer(aBModel.getProject());
        aBModel.setAnnotationLayers(layers);
      }
    }
    // no preference found
    catch (Exception e) {
      // If no layer preferences are defined, then just assume all layers are enabled
      List<AnnotationLayer> layers = aAnnotationService.listAnnotationLayer(aBModel.getProject());
      aBModel.setAnnotationLayers(layers);
    }
  }
 @Override
 public void addActionParameter(String param, Object value) {
   if (StringUtils.isEmpty(param) || value == null) {
     throw new IllegalArgumentException("Param or Value is null.");
   }
   beanWrapper.setPropertyValue(param, value);
 }
  /**
   * 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 void foundAsset(String name, String value) {
   BeanWrapper w = PropertyAccessorFactory.forBeanPropertyAccess(m_node.getAssetRecord());
   try {
     w.setPropertyValue(name, value);
   } catch (BeansException e) {
     LOG.warn("Could not set property on asset: {}", name, e);
   }
 }
 @SuppressWarnings("rawtypes")
 private static void bindProperties(Object obj, Map entryProperties) {
   BeanWrapper dsBean = new BeanWrapperImpl(obj);
   for (Object o : entryProperties.entrySet()) {
     Map.Entry entry2 = (Map.Entry) o;
     final String propertyName = entry2.getKey().toString();
     if (dsBean.isWritableProperty(propertyName)) {
       dsBean.setPropertyValue(propertyName, entry2.getValue());
     }
   }
 }
Exemplo n.º 9
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 IValidationRule getRule() {
   if (propertyValues.size() > 0 && !rulePropertiesInitialized) {
     BeanWrapper wrapper = new BeanWrapperImpl(rule);
     for (Map.Entry<String, String> entry : propertyValues.entrySet()) {
       try {
         wrapper.setPropertyValue(entry.getKey(), entry.getValue());
       } catch (BeansException e) {
         SpringCore.log(e);
       }
     }
     rulePropertiesInitialized = true;
   }
   return rule;
 }
Exemplo n.º 11
0
  /**
   * Interrogates the specified properties looking for properites that represent associations to
   * other classes (e.g., 'author.id'). If such a property is found, this method attempts to load
   * the specified instance of the association (by ID) and set it on the target object.
   *
   * @param mpvs the <code>MutablePropertyValues</code> object holding the parameters from the
   *     request
   */
  protected void bindAssociations(MutablePropertyValues mpvs) {
    for (PropertyValue pv : mpvs.getPropertyValues()) {
      String propertyName = pv.getName();
      String propertyNameToCheck = propertyName;
      final int i = propertyName.indexOf('.');
      if (i > -1) {
        propertyNameToCheck = propertyName.substring(0, i);
      }

      if (!isAllowed(propertyNameToCheck)) continue;

      if (propertyName.endsWith(IDENTIFIER_SUFFIX)) {
        propertyName = propertyName.substring(0, propertyName.length() - 3);
        if (!isAllowed(propertyName)) continue;
        if (isReadableAndPersistent(propertyName) && bean.isWritableProperty(propertyName)) {
          if (NULL_ASSOCIATION.equals(pv.getValue())) {
            bean.setPropertyValue(propertyName, null);
            mpvs.removePropertyValue(pv);
          } else {
            Class<?> type = getPropertyTypeForPath(propertyName);
            Object persisted = getPersistentInstance(type, pv.getValue());
            if (persisted != null) {
              bean.setPropertyValue(propertyName, persisted);
            }
          }
        }
      } else {
        if (isReadableAndPersistent(propertyName)) {
          Class<?> type = getPropertyTypeForPath(propertyName);
          if (Collection.class.isAssignableFrom(type)) {
            bindCollectionAssociation(mpvs, pv);
          }
        }
      }
    }
  }
 /**
  * setField
  *
  * @param name a {@link java.lang.String} object.
  * @param val a {@link java.lang.String} object.
  */
 public void setField(final String name, final String val) {
   if (name.equals("eventparms")) {
     String[] parts = val.split(";");
     for (String part : parts) {
       String[] pair = part.split("=");
       addParam(pair[0], pair[1].replaceFirst("[(]\\w+,\\w+[)]", ""));
     }
   } else {
     final BeanWrapper w = PropertyAccessorFactory.forBeanPropertyAccess(m_event);
     try {
       w.setPropertyValue(name, val);
     } catch (final BeansException e) {
       LogUtils.warnf(this, e, "Could not set field on event: %s", name);
     }
   }
 }
Exemplo n.º 13
0
 protected Errors validateConstraint(Constraint constraint, Object value, Boolean shouldVeto) {
   BeanWrapper constrainedBean = new BeanWrapperImpl(new TestClass());
   constrainedBean.setPropertyValue(constraint.getPropertyName(), value);
   Errors errors =
       new BindException(
           constrainedBean.getWrappedInstance(), constrainedBean.getWrappedClass().getName());
   if (!(constraint instanceof VetoingConstraint) || shouldVeto == null) {
     constraint.validate(constrainedBean.getWrappedInstance(), value, errors);
   } else {
     boolean vetoed =
         ((VetoingConstraint) constraint)
             .validateWithVetoing(constrainedBean.getWrappedInstance(), value, errors);
     if (shouldVeto.booleanValue() && !vetoed) fail("Constraint should veto");
     else if (!shouldVeto.booleanValue() && vetoed) fail("Constraint shouldn't veto");
   }
   return errors;
 }
  /**
   * Extract the values for all attributes in the struct.
   *
   * <p>Utilizes public setters and result set metadata.
   *
   * @see java.sql.ResultSetMetaData
   */
  public Object fromStruct(STRUCT struct) throws SQLException {
    Assert.state(this.mappedClass != null, "Mapped class was not specified");
    Object mappedObject = BeanUtils.instantiateClass(this.mappedClass);
    BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(mappedObject);
    initBeanWrapper(bw);

    ResultSetMetaData rsmd = struct.getDescriptor().getMetaData();
    Object[] attr = struct.getAttributes();
    int columnCount = rsmd.getColumnCount();
    for (int index = 1; index <= columnCount; index++) {
      String column = JdbcUtils.lookupColumnName(rsmd, index).toLowerCase();
      PropertyDescriptor pd = (PropertyDescriptor) this.mappedFields.get(column);
      if (pd != null) {
        Object value = attr[index - 1];
        if (logger.isDebugEnabled()) {
          logger.debug(
              "Mapping column '"
                  + column
                  + "' to property '"
                  + pd.getName()
                  + "' of type "
                  + pd.getPropertyType());
        }
        if (bw.isWritableProperty(pd.getName())) {
          try {
            bw.setPropertyValue(pd.getName(), value);
          } catch (Exception e) {
            e.printStackTrace();
          }
        } else {
          // Если нету сеттера для проперти не нужно кидать ошибку!
          logger.warn(
              "Unable to access the setter for "
                  + pd.getName()
                  + ".  Check that "
                  + "set"
                  + StringUtils.capitalize(pd.getName())
                  + " is declared and has public access.");
        }
      }
    }

    return mappedObject;
  }
Exemplo n.º 15
0
 protected void overrideBeanProperties(ServletConfig sc) throws ServletException {
   BeanWrapper wrapper = new BeanWrapperImpl(driver);
   Enumeration<String> en = sc.getInitParameterNames();
   while (en.hasMoreElements()) {
     String name = en.nextElement();
     if (name.indexOf(driverBean + '.') == 0 && name.length() > (driverBean.length() + 1)) {
       String propertyName = name.substring(driverBean.length() + 1);
       String value = sc.getInitParameter(name);
       if (value != null) {
         try {
           wrapper.setPropertyValue(propertyName, value);
         } catch (BeansException e) {
           throw new ServletException(
               "Cannot set property " + propertyName + " of bean " + driverBean, e);
         }
       }
     }
   }
 }
Exemplo n.º 16
0
 /**
  * Set the value for this attribute
  *
  * @param value
  */
 public void setValue(Object value) {
   Class claz = sourceObject.getPropertyType(attribute);
   if (claz == null)
     throw new IllegalArgumentException(
         "Atribute "
             + attribute
             + " does not exist in class "
             + sourceObject.getWrappedClass()
             + ". Cannot set value:"
             + value);
   value = ObjectConverter.convert(value, claz);
   sourceObject.setPropertyValue(attribute, value);
   //        if((sourceObject.getWrappedInstance() instanceof BindingComponent) &&
   // !(sourceObject.getWrappedInstance() instanceof BndIJComboBox)){
   //            logger.info("Setting bindingComponent ...");
   //
   //            ((BindingComponent)sourceObject.getWrappedInstance()).setValueToJComponent();
   //        }
 }
 public T mapRow(ResultSet rs, int rowNum) throws SQLException {
   T mappedObject = instantiateMappedClass(mapperConfig.getMappedClass());
   BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(mappedObject);
   //
   ResultSetMetaData rsmd = rs.getMetaData();
   int columnCount = rsmd.getColumnCount();
   //
   for (int index = 1; index <= columnCount; index++) {
     String column = JdbcUtils.lookupColumnName(rsmd, index);
     String property = mapperConfig.getMappedProperty(column);
     if (property != null) {
       PropertyDescriptor pd = bw.getPropertyDescriptor(property);
       if (pd != null) {
         Object value = getColumnValue(rs, index, pd);
         bw.setPropertyValue(pd.getName(), value);
       }
     }
     //
   }
   //
   return mappedObject;
 }
Exemplo n.º 18
0
  /**
   * 将group中的值置入指定对象。
   *
   * <p>对于<code>isValidated()</code>为<code>false</code>的group,该方法无效。
   */
  public void setProperties(Object object) {
    if (!isValidated() || object == null) {
      return;
    }

    if (isValid()) {
      if (log.isDebugEnabled()) {
        log.debug(
            "Set validated properties of group \""
                + getName()
                + "\" to object "
                + ObjectUtil.identityToString(object));
      }

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

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

        if (bean.isWritableProperty(propertyName)) {
          PropertyDescriptor pd = bean.getPropertyDescriptor(propertyName);
          MethodParameter mp = BeanUtils.getWriteMethodParameter(pd);
          Object value = field.getValueOfType(pd.getPropertyType(), mp, null);

          bean.setPropertyValue(propertyName, value);
        } else {
          log.debug(
              "No writable property \"{}\" found in type {}",
              propertyName,
              object.getClass().getName());
        }
      }
    } else {
      throw new InvalidGroupStateException("Attempted to call setProperties from an invalid input");
    }
  }
Exemplo n.º 19
0
 @PUT
 @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
 @Path("{userCriteria}")
 public Response updateUser(
     @PathParam("userCriteria") final String userCriteria, final MultivaluedMapImpl params) {
   OnmsUser user = null;
   writeLock();
   try {
     try {
       user = m_userManager.getOnmsUser(userCriteria);
     } catch (final Throwable t) {
       throw getException(Status.BAD_REQUEST, t);
     }
     if (user == null)
       throw getException(Status.BAD_REQUEST, "updateUser: User does not exist: " + userCriteria);
     log().debug("updateUser: updating user " + user);
     final BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(user);
     for (final String key : params.keySet()) {
       if (wrapper.isWritableProperty(key)) {
         final String stringValue = params.getFirst(key);
         @SuppressWarnings("unchecked")
         final Object value =
             wrapper.convertIfNecessary(stringValue, wrapper.getPropertyType(key));
         wrapper.setPropertyValue(key, value);
       }
     }
     log().debug("updateUser: user " + user + " updated");
     try {
       m_userManager.save(user);
     } catch (final Throwable t) {
       throw getException(Status.INTERNAL_SERVER_ERROR, t);
     }
     return Response.seeOther(getRedirectUri(m_uriInfo)).build();
   } finally {
     writeUnlock();
   }
 }
Exemplo n.º 20
0
  @Override
  public UserProfile getProfileForDisplay(UserProfile userProfile, boolean showPrivateFields) {
    UserProfile display = new UserProfile();
    copyFields(userProfile, display);
    if (!showPrivateFields) {
      log.debug("Removing private fields for display on user: {}", userProfile.getDisplayName());
      display.setOrganizationName(null);
      display.setOrganizationType(null);
      display.setPostalAddress(null);
      display.setPositionType(null);
    }

    // escape html in all string fields
    BeanWrapper wrapper = new BeanWrapperImpl(display);
    for (PropertyDescriptor property : wrapper.getPropertyDescriptors()) {
      if (String.class.isAssignableFrom(property.getPropertyType())) {
        String name = property.getName();
        wrapper.setPropertyValue(
            name, TextUtils.escapeHtml((String) wrapper.getPropertyValue(name)));
      }
    }

    return display;
  }
  /**
   * Extract the values for all columns in the current row.
   *
   * <p>Utilizes public setters and result set metadata.
   *
   * @see java.sql.ResultSetMetaData
   */
  @Override
  public T mapRow(ResultSet rs, int rowNumber) throws SQLException {
    Assert.state(this.mappedClass != null, "Mapped class was not specified");
    T mappedObject = BeanUtils.instantiate(this.mappedClass);
    BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(mappedObject);
    initBeanWrapper(bw);

    ResultSetMetaData rsmd = rs.getMetaData();
    int columnCount = rsmd.getColumnCount();
    Set<String> populatedProperties = (isCheckFullyPopulated() ? new HashSet<String>() : null);

    for (int index = 1; index <= columnCount; index++) {
      String column = JdbcUtils.lookupColumnName(rsmd, index);
      PropertyDescriptor pd = this.mappedFields.get(column.replaceAll(" ", "").toLowerCase());
      if (pd != null) {
        try {
          Object value = getColumnValue(rs, index, pd);
          if (logger.isDebugEnabled() && rowNumber == 0) {
            logger.debug(
                "Mapping column '"
                    + column
                    + "' to property '"
                    + pd.getName()
                    + "' of type "
                    + pd.getPropertyType());
          }
          try {
            bw.setPropertyValue(pd.getName(), value);
          } catch (TypeMismatchException e) {
            if (value == null && primitivesDefaultedForNullValue) {
              logger.debug(
                  "Intercepted TypeMismatchException for row "
                      + rowNumber
                      + " and column '"
                      + column
                      + "' with value "
                      + value
                      + " when setting property '"
                      + pd.getName()
                      + "' of type "
                      + pd.getPropertyType()
                      + " on object: "
                      + mappedObject);
            } else {
              throw e;
            }
          }
          if (populatedProperties != null) {
            populatedProperties.add(pd.getName());
          }
        } catch (NotWritablePropertyException ex) {
          throw new DataRetrievalFailureException(
              "Unable to map column " + column + " to property " + pd.getName(), ex);
        }
      }
    }

    if (populatedProperties != null && !populatedProperties.equals(this.mappedProperties)) {
      throw new InvalidDataAccessApiUsageException(
          "Given ResultSet does not contain all fields "
              + "necessary to populate object of class ["
              + this.mappedClass
              + "]: "
              + this.mappedProperties);
    }

    return mappedObject;
  }
  /**
   * doUpdate
   *
   * @param nodeId a int.
   * @param retry a boolean.
   * @throws org.opennms.netmgt.provision.ProvisioningAdapterException if any.
   */
  @Override
  public void doUpdateNode(final int nodeId) throws ProvisioningAdapterException {
    log().debug("doUpdate: updating nodeid: " + nodeId);

    final OnmsNode node = m_nodeDao.get(nodeId);
    Assert.notNull(node, "doUpdate: failed to return node for given nodeId:" + nodeId);

    final InetAddress ipaddress =
        m_template.execute(
            new TransactionCallback<InetAddress>() {
              public InetAddress doInTransaction(final TransactionStatus arg0) {
                return getIpForNode(node);
              }
            });

    final SnmpAgentConfig agentConfig = m_snmpConfigDao.getAgentConfig(ipaddress);

    final OnmsAssetRecord asset = node.getAssetRecord();
    m_config.getReadLock().lock();
    try {
      for (AssetField field : m_config.getAssetFieldsForAddress(ipaddress, node.getSysObjectId())) {
        try {
          String value =
              fetchSnmpAssetString(agentConfig, field.getMibObjs(), field.getFormatString());
          if (log().isDebugEnabled()) {
            log()
                .debug(
                    "doUpdate: Setting asset field \"" + field.getName() + "\" to value: " + value);
          }
          // Use Spring bean-accessor classes to set the field value
          BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(asset);
          try {
            wrapper.setPropertyValue(field.getName(), value);
          } catch (BeansException e) {
            log()
                .warn(
                    "doUpdate: Could not set property \""
                        + field.getName()
                        + "\" on asset object: "
                        + e.getMessage(),
                    e);
          }
        } catch (MissingFormatArgumentException e) {
          // This exception is thrown if the SNMP operation fails or an incorrect number of
          // parameters is returned by the agent or because of a misconfiguration.
          log()
              .warn(
                  "doUpdate: Could not set value for asset field \""
                      + field.getName()
                      + "\": "
                      + e.getMessage(),
                  e);
        }
      }
    } finally {
      m_config.getReadLock().unlock();
    }
    node.setAssetRecord(asset);
    m_nodeDao.saveOrUpdate(node);
    m_nodeDao.flush();
  }
Exemplo n.º 23
0
  @SuppressWarnings("unchecked")
  private Object autoCreatePropertyIfPossible(
      BeanWrapper wrapper, String propertyName, Object propertyValue) {

    propertyName = PropertyAccessorUtils.canonicalPropertyName(propertyName);
    int currentKeyStart = propertyName.indexOf(PropertyAccessor.PROPERTY_KEY_PREFIX_CHAR);
    int currentKeyEnd = propertyName.indexOf(PropertyAccessor.PROPERTY_KEY_SUFFIX_CHAR);
    String propertyNameWithIndex = propertyName;
    if (currentKeyStart > -1) {
      propertyName = propertyName.substring(0, currentKeyStart);
    }

    Class<?> type = wrapper.getPropertyType(propertyName);
    Object val =
        wrapper.isReadableProperty(propertyName) ? wrapper.getPropertyValue(propertyName) : null;

    LOG.debug(
        "Checking if auto-create is possible for property ["
            + propertyName
            + "] and type ["
            + type
            + "]");
    if (type != null && val == null && (isDomainClass(type) || isEmbedded(wrapper, propertyName))) {
      if (!shouldPropertyValueSkipAutoCreate(propertyValue)
          && isNullAndWritableProperty(wrapper, propertyName)) {
        if (isDomainClass(type)) {
          Object created = autoInstantiateDomainInstance(type);
          if (created != null) {
            val = created;
            wrapper.setPropertyValue(propertyName, created);
          }
        } else if (isEmbedded(wrapper, propertyName)) {
          Object created = autoInstantiateEmbeddedInstance(type);
          if (created != null) {
            val = created;
            wrapper.setPropertyValue(propertyName, created);
          }
        }
      }
    } else {
      final Object beanInstance = wrapper.getWrappedInstance();
      if (type != null && Collection.class.isAssignableFrom(type)) {
        Collection<?> c = null;
        final Class<?> referencedType = getReferencedTypeForCollection(propertyName, beanInstance);

        if (isNullAndWritableProperty(wrapper, propertyName)) {
          c =
              decorateCollectionForDomainAssociation(
                  GrailsClassUtils.createConcreteCollection(type), referencedType);
        } else {
          if (wrapper.isReadableProperty(propertyName)) {
            c =
                decorateCollectionForDomainAssociation(
                    (Collection<?>) wrapper.getPropertyValue(propertyName), referencedType);
          }
        }

        if (wrapper.isWritableProperty(propertyName) && c != null) {
          wrapper.setPropertyValue(propertyName, c);
        }
        val = c;

        if (c != null && currentKeyStart > -1 && currentKeyEnd > -1) {
          String indexString = propertyNameWithIndex.substring(currentKeyStart + 1, currentKeyEnd);
          int index = Integer.parseInt(indexString);

          if (isDomainClass(referencedType)) {
            Object instance = findIndexedValue(c, index);
            if (instance != null) {
              val = instance;
            } else {
              instance = autoInstantiateDomainInstance(referencedType);
              if (instance != null) {
                val = instance;
                if (index == c.size()) {
                  addAssociationToTarget(propertyName, beanInstance, instance);
                } else if (index > c.size()) {
                  while (index > c.size()) {
                    addAssociationToTarget(
                        propertyName, beanInstance, autoInstantiateDomainInstance(referencedType));
                  }

                  addAssociationToTarget(propertyName, beanInstance, instance);
                }
              }
            }
          }
        }
      } else if (type != null && Map.class.isAssignableFrom(type)) {
        Map<String, Object> map;
        if (isNullAndWritableProperty(wrapper, propertyName)) {
          map = new HashMap<String, Object>();
          wrapper.setPropertyValue(propertyName, map);
        } else {
          map = (Map) wrapper.getPropertyValue(propertyName);
        }
        val = map;
        wrapper.setPropertyValue(propertyName, val);

        if (currentKeyStart > -1 && currentKeyEnd > -1) {
          String indexString = propertyNameWithIndex.substring(currentKeyStart + 1, currentKeyEnd);
          Class<?> referencedType = getReferencedTypeForCollection(propertyName, beanInstance);
          if (isDomainClass(referencedType)) {
            final Object domainInstance = autoInstantiateDomainInstance(referencedType);
            val = domainInstance;
            map.put(indexString, domainInstance);
          }
        }
      }
    }

    return val;
  }