Exemplo n.º 1
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;
 }
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);
          }
        }
      }
    }
  }
Exemplo n.º 3
0
  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;
  }
 @Override
 public Object getActionParameter(String param) {
   if (beanWrapper.isReadableProperty(param)) {
     return beanWrapper.getPropertyValue(param);
   }
   return null;
 }
Exemplo n.º 5
0
  /**
   * 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;
    }
  }
Exemplo n.º 6
0
  public void doArtefactConfiguration() {
    if (!pluginBean.isReadableProperty(ARTEFACTS)) {
      return;
    }

    List l = (List) plugin.getProperty(ARTEFACTS);
    for (Object artefact : l) {
      if (artefact instanceof Class) {
        Class artefactClass = (Class) artefact;
        if (ArtefactHandler.class.isAssignableFrom(artefactClass)) {
          try {
            application.registerArtefactHandler((ArtefactHandler) artefactClass.newInstance());
          } catch (InstantiationException e) {
            LOG.error("Cannot instantiate an Artefact Handler:" + e.getMessage(), e);
          } catch (IllegalAccessException e) {
            LOG.error(
                "The constructor of the Artefact Handler is not accessible:" + e.getMessage(), e);
          }
        } else {
          LOG.error("This class is not an ArtefactHandler:" + artefactClass.getName());
        }
      } else {
        if (artefact instanceof ArtefactHandler) {
          application.registerArtefactHandler((ArtefactHandler) artefact);
        } else {
          LOG.error(
              "This object is not an ArtefactHandler:"
                  + artefact
                  + "["
                  + artefact.getClass().getName()
                  + "]");
        }
      }
    }
  }
Exemplo n.º 7
0
 private void evaluatePluginStatus() {
   if (pluginBean.isReadableProperty(STATUS)) {
     Object statusObj = GrailsClassUtils.getPropertyOrStaticPropertyOrFieldValue(plugin, STATUS);
     if (statusObj != null) {
       status = statusObj.toString().toLowerCase();
     }
   }
 }
 public Object get(Object key) {
   String objectKey = (String) key;
   if (beanWrapper.isReadableProperty(objectKey)) {
     return beanWrapper.getPropertyValue(objectKey);
   } else {
     return thisWrapper.getPropertyValue(objectKey);
   }
 }
Exemplo n.º 9
0
 @SuppressWarnings("unchecked")
 private void evaluatePluginDependencies() {
   if (pluginBean.isReadableProperty(DEPENDS_ON)) {
     dependencies =
         (Map) GrailsClassUtils.getPropertyOrStaticPropertyOrFieldValue(plugin, DEPENDS_ON);
     dependencyNames = dependencies.keySet().toArray(new String[dependencies.size()]);
   }
 }
  public void testGenerateController() throws Exception {
    GrailsTemplateGenerator generator;

    GroovyClassLoader gcl = new GroovyClassLoader(Thread.currentThread().getContextClassLoader());

    generator = new DefaultGrailsTemplateGenerator();

    Class dc = gcl.parseClass("class Test { \n Long id;\n  Long version;  }");
    GrailsDomainClass domainClass = new DefaultGrailsDomainClass(dc);

    File generatedFile = new File("test/grails-app/controllers/TestController.groovy");
    if (generatedFile.exists()) {
      generatedFile.delete();
    }

    StringWriter sw = new StringWriter();
    generator.generateController(domainClass, sw);

    String text = sw.toString();

    Class controllerClass = gcl.parseClass(text);
    BeanWrapper bean = new BeanWrapperImpl(controllerClass.newInstance());

    assertEquals("TestController", controllerClass.getName());

    assertTrue(bean.isReadableProperty("list"));
    assertTrue(bean.isReadableProperty("update"));
    assertTrue(bean.isReadableProperty("create"));
    assertTrue(bean.isReadableProperty("list"));
    assertTrue(bean.isReadableProperty("show"));
    assertTrue(bean.isReadableProperty("edit"));
    assertTrue(bean.isReadableProperty("delete"));

    Object propertyValue =
        GrailsClassUtils.getStaticPropertyValue(controllerClass, "allowedMethods");
    assertTrue("allowedMethods property was the wrong type", propertyValue instanceof Map);
    Map map = (Map) propertyValue;
    assertTrue("allowedMethods did not contain the delete action", map.containsKey("delete"));
    assertTrue("allowedMethods did not contain the save action", map.containsKey("save"));
    assertTrue("allowedMethods did not contain the update action", map.containsKey("update"));

    assertEquals("allowedMethods had incorrect value for delete action", "POST", map.get("delete"));
    assertEquals("allowedMethods had incorrect value for save action", "POST", map.get("save"));
    assertEquals("allowedMethods had incorrect value for update action", "POST", map.get("update"));
  }
Exemplo n.º 11
0
 @Override
 public void doWithWebDescriptor(GPathResult webXml) {
   if (pluginBean.isReadableProperty(DO_WITH_WEB_DESCRIPTOR)) {
     Closure c = (Closure) plugin.getProperty(DO_WITH_WEB_DESCRIPTOR);
     c.setResolveStrategy(Closure.DELEGATE_FIRST);
     c.setDelegate(this);
     c.call(webXml);
   }
 }
Exemplo n.º 12
0
 @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()]);
     }
   }
 }
  /**
   * 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);
  }
Exemplo n.º 14
0
  private void evaluatePluginVersion() {
    if (!pluginBean.isReadableProperty(VERSION)) {
      throw new PluginException("Plugin [" + getName() + "] must specify a version!");
    }

    Object vobj = plugin.getProperty(VERSION);
    if (vobj != null) {
      version = vobj.toString();
    } else {
      throw new PluginException(
          "Plugin " + this + " must specify a version. eg: def version = 0.1");
    }
  }
Exemplo n.º 15
0
 private void evaluatePluginEvictionPolicy() {
   if (pluginBean.isReadableProperty(EVICT)) {
     List pluginsToEvict =
         (List) GrailsClassUtils.getPropertyOrStaticPropertyOrFieldValue(plugin, EVICT);
     if (pluginsToEvict != null) {
       evictionList = new String[pluginsToEvict.size()];
       int index = 0;
       for (Object o : pluginsToEvict) {
         evictionList[index++] = o != null ? o.toString() : "";
       }
     }
   }
 }
  @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;
  }
  @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;
  }
Exemplo n.º 18
0
 @SuppressWarnings("unchecked")
 private void evaluatePluginLoadAfters() {
   if (pluginBean.isReadableProperty(PLUGIN_LOAD_AFTER_NAMES)) {
     List loadAfterNamesList =
         (List)
             GrailsClassUtils.getPropertyOrStaticPropertyOrFieldValue(
                 plugin, PLUGIN_LOAD_AFTER_NAMES);
     if (loadAfterNamesList != null) {
       loadAfterNames =
           (String[]) loadAfterNamesList.toArray(new String[loadAfterNamesList.size()]);
     }
   }
   if (pluginBean.isReadableProperty(PLUGIN_LOAD_BEFORE_NAMES)) {
     List loadBeforeNamesList =
         (List)
             GrailsClassUtils.getPropertyOrStaticPropertyOrFieldValue(
                 plugin, PLUGIN_LOAD_BEFORE_NAMES);
     if (loadBeforeNamesList != null) {
       loadBeforeNames =
           (String[]) loadBeforeNamesList.toArray(new String[loadBeforeNamesList.size()]);
     }
   }
 }
Exemplo n.º 19
0
  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;
  }
Exemplo n.º 20
0
 /**
  * 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;
 }
Exemplo n.º 21
0
  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;
  }
Exemplo n.º 22
0
  public void doWithDynamicMethods(ApplicationContext ctx) {
    try {
      if (pluginBean.isReadableProperty(DO_WITH_DYNAMIC_METHODS)) {
        Closure c = (Closure) plugin.getProperty(DO_WITH_DYNAMIC_METHODS);
        if (enableDocumentationGeneration()) {
          DocumentationContext.getInstance().setActive(true);
        }

        c.setDelegate(this);
        c.call(new Object[] {ctx});
      }
    } finally {
      if (enableDocumentationGeneration()) {
        DocumentationContext.getInstance().reset();
      }
    }
  }
Exemplo n.º 23
0
  public void doWithApplicationContext(ApplicationContext ctx) {
    try {
      if (pluginBean.isReadableProperty(DO_WITH_APPLICATION_CONTEXT)) {
        Closure c = (Closure) plugin.getProperty(DO_WITH_APPLICATION_CONTEXT);
        if (enableDocumentationGeneration()) {
          DocumentationContext.getInstance().setActive(true);
        }

        c.setDelegate(this);
        c.call(new Object[] {ctx});
      }
    } finally {
      if (enableDocumentationGeneration()) {
        DocumentationContext.getInstance().reset();
      }
    }
  }
Exemplo n.º 24
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());
      }
    }
  }
Exemplo n.º 25
0
 private void evaluateObservedPlugins() {
   if (pluginBean.isReadableProperty(PLUGIN_OBSERVE)) {
     Object observeProperty =
         GrailsClassUtils.getPropertyOrStaticPropertyOrFieldValue(plugin, PLUGIN_OBSERVE);
     if (observeProperty instanceof Collection) {
       Collection observeList = (Collection) observeProperty;
       observedPlugins = new String[observeList.size()];
       int j = 0;
       for (Object anObserveList : observeList) {
         String pluginName = anObserveList.toString();
         observedPlugins[j++] = pluginName;
       }
     }
   }
   if (observedPlugins == null) {
     observedPlugins = new String[0];
   }
 }
Exemplo n.º 26
0
  protected void init(Object entity) {
    this.entity = entity;

    beanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(entity);
    PropertyDescriptor[] descriptors = beanWrapper.getPropertyDescriptors();
    if (descriptors.length > 1) {
      for (PropertyDescriptor descriptor : descriptors) {
        if (beanWrapper.isReadableProperty(descriptor.getName())) {
          privateFields.add(descriptor.getName());
        }
      }
    }

    Field[] fields = BeanFields.get(entity.getClass());
    if (fields != null) {
      for (Field field : fields) {
        publicFeilds.put(field.getName(), field);
      }
    }
  }
Exemplo n.º 27
0
  public void doWithRuntimeConfiguration(RuntimeSpringConfiguration springConfig) {

    if (pluginBean.isReadableProperty(DO_WITH_SPRING)) {
      if (LOG.isDebugEnabled()) {
        LOG.debug("Plugin " + this + " is participating in Spring configuration...");
      }

      Closure c = (Closure) plugin.getProperty(DO_WITH_SPRING);
      BeanBuilder bb = new BeanBuilder(getParentCtx(), springConfig, application.getClassLoader());
      Binding b = new Binding();
      b.setVariable("application", application);
      b.setVariable("manager", getManager());
      b.setVariable("plugin", this);
      b.setVariable("parentCtx", getParentCtx());
      b.setVariable("resolver", getResolver());
      bb.setBinding(b);
      c.setDelegate(bb);
      bb.invokeMethod("beans", new Object[] {c});
    }
  }
Exemplo n.º 28
0
 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);
         }
       }
     }
   }
 }
Exemplo n.º 29
0
  @Override
  public void doWithWebDescriptor(final Element webXml) {
    if (!pluginBean.isReadableProperty(DO_WITH_WEB_DESCRIPTOR)) {
      return;
    }

    final Closure c = (Closure) plugin.getProperty(DO_WITH_WEB_DESCRIPTOR);
    c.setResolveStrategy(Closure.DELEGATE_FIRST);
    c.setDelegate(this);
    DefaultGroovyMethods.use(
        this,
        DOMCategory.class,
        new Closure<Object>(this) {
          private static final long serialVersionUID = 1;

          @Override
          public Object call(Object... args) {
            return c.call(webXml);
          }
        });
  }
 public STRUCT toStruct(Object object, Connection conn, String typeName) throws SQLException {
   StructDescriptor descriptor = new StructDescriptor(typeName, conn);
   ResultSetMetaData rsmd = descriptor.getMetaData();
   int columns = rsmd.getColumnCount();
   Object[] values = new Object[columns];
   for (int i = 1; i <= columns; i++) {
     String column = JdbcUtils.lookupColumnName(rsmd, i).toLowerCase();
     PropertyDescriptor fieldMeta = (PropertyDescriptor) this.mappedFields.get(column);
     if (fieldMeta != null) {
       BeanWrapper bw = new BeanWrapperImpl(object);
       if (bw.isReadableProperty(fieldMeta.getName())) {
         try {
           if (logger.isDebugEnabled()) {
             logger.debug(
                 "Mapping column named \""
                     + column
                     + "\""
                     + " to property \""
                     + fieldMeta.getName()
                     + "\"");
           }
           values[i - 1] = bw.getPropertyValue(fieldMeta.getName());
         } catch (NotReadablePropertyException ex) {
           throw new DataRetrievalFailureException(
               "Unable to map column " + column + " to property " + fieldMeta.getName(), ex);
         }
       } else {
         logger.warn(
             "Unable to access the getter for "
                 + fieldMeta.getName()
                 + ".  Check that "
                 + "get"
                 + StringUtils.capitalize(fieldMeta.getName())
                 + " is declared and has public access.");
       }
     }
   }
   STRUCT struct = new STRUCT(descriptor, conn, values);
   return struct;
 }