Example #1
0
 /**
  * Wrap the given {@link BeanInfo} instance; copy all its existing property descriptors locally,
  * wrapping each in a custom {@link SimpleIndexedPropertyDescriptor indexed} or {@link
  * SimplePropertyDescriptor non-indexed} {@code PropertyDescriptor} variant that bypasses default
  * JDK weak/soft reference management; then search through its method descriptors to find any
  * non-void returning write methods and update or create the corresponding {@link
  * PropertyDescriptor} for each one found.
  *
  * @param delegate the wrapped {@code BeanInfo}, which is never modified
  * @throws IntrospectionException if any problems occur creating and adding new property
  *     descriptors
  * @see #getPropertyDescriptors()
  */
 public ExtendedBeanInfo(BeanInfo delegate) throws IntrospectionException {
   this.delegate = delegate;
   for (PropertyDescriptor pd : delegate.getPropertyDescriptors()) {
     try {
       this.propertyDescriptors.add(
           pd instanceof IndexedPropertyDescriptor
               ? new SimpleIndexedPropertyDescriptor((IndexedPropertyDescriptor) pd)
               : new SimplePropertyDescriptor(pd));
     } catch (IntrospectionException ex) {
       // Probably simply a method that wasn't meant to follow the JavaBeans pattern...
       if (logger.isDebugEnabled()) {
         logger.debug("Ignoring invalid bean property '" + pd.getName() + "': " + ex.getMessage());
       }
     }
   }
   MethodDescriptor[] methodDescriptors = delegate.getMethodDescriptors();
   if (methodDescriptors != null) {
     for (Method method : findCandidateWriteMethods(methodDescriptors)) {
       try {
         handleCandidateWriteMethod(method);
       } catch (IntrospectionException ex) {
         // We're only trying to find candidates, can easily ignore extra ones here...
         if (logger.isDebugEnabled()) {
           logger.debug("Ignoring candidate write method [" + method + "]: " + ex.getMessage());
         }
       }
     }
   }
 }
Example #2
0
 public ResourceInfo.MethodInfo[] getMethodDescriptors() {
   Set<java.lang.reflect.Method> accessors = new HashSet<java.lang.reflect.Method>();
   for (PropertyDescriptor p : getPropertyDescriptors()) {
     accessors.add(p.getReadMethod());
     accessors.add(p.getWriteMethod());
   }
   for (MethodDescriptor o : getRemoteMethodDescriptors()) {
     accessors.add(o.getMethod());
   }
   TreeSet<MethodDescriptor> methods =
       new TreeSet<MethodDescriptor>(
           new Comparator<MethodDescriptor>() {
             public int compare(MethodDescriptor a, MethodDescriptor b) {
               return a.getName().compareTo(b.getName());
             }
           });
   methods.addAll(Arrays.asList(info.getMethodDescriptors()));
   Iterator<MethodDescriptor> iter = methods.iterator();
   while (iter.hasNext()) {
     MethodDescriptor m = iter.next();
     if (accessors.contains(m.getMethod())) {
       iter.remove();
     }
   }
   return MethodInfo.wrap(methods);
 }
Example #3
0
    private ObjectConverter generateConverter(Class cls) {
      BeanInfo beanInfo = null;

      try {
        beanInfo = Introspector.getBeanInfo(cls);
      } catch (IntrospectionException e) {
        throw new RuntimeException(e);
      }

      PropertyDescriptor[] props = beanInfo.getPropertyDescriptors();
      List<ObjectConverterEntry> list = new ArrayList<ObjectConverterEntry>();

      for (int i = 0, length = props.length; i < length; i++) {
        PropertyDescriptor prop = props[i];
        if ("class".equals(prop.getName())) {
          continue;
        }

        list.add(
            new ObjectConverterEntry(
                prop.getName(), prop.getReadMethod(), getType(prop.getPropertyType())));
      }

      return new ObjectConverter(cls, list.toArray(new ObjectConverterEntry[list.size()]));
    }
Example #4
0
  String getPrincipalProperty(Object principal, String property) throws TemplateModelException {
    try {
      BeanInfo beanInfo = Introspector.getBeanInfo(principal.getClass());

      // Loop through the properties to get the string value of the specified property
      for (PropertyDescriptor propertyDescriptor : beanInfo.getPropertyDescriptors()) {
        if (propertyDescriptor.getName().equals(property)) {
          Object value = propertyDescriptor.getReadMethod().invoke(principal, (Object[]) null);

          return String.valueOf(value);
        }
      }

      // property not found, throw
      throw new TemplateModelException(
          "Property ["
              + property
              + "] not found in principal of type ["
              + principal.getClass().getName()
              + "]");
    } catch (Exception ex) {
      throw new TemplateModelException(
          "Error reading property ["
              + property
              + "] from principal of type ["
              + principal.getClass().getName()
              + "]",
          ex);
    }
  }
Example #5
0
  private List setProperty(
      Object component,
      ComponentDescriptor descriptor,
      ComponentRequirement requirementDescriptor,
      PropertyDescriptor propertyDescriptor,
      PlexusContainer container,
      ClassRealm lookupRealm)
      throws CompositionException {
    Requirement requirement =
        findRequirement(
            component,
            propertyDescriptor.getPropertyType(),
            container,
            requirementDescriptor,
            lookupRealm);

    try {
      Method writeMethod = propertyDescriptor.getWriteMethod();

      Object[] params = new Object[1];

      params[0] = requirement.getAssignment();

      Statement statement = new Statement(component, writeMethod.getName(), params);

      statement.execute();
    } catch (Exception e) {
      reportErrorCannotAssignRequiredComponent(descriptor, requirementDescriptor, e);
    }

    return requirement.getComponentDescriptors();
  }
Example #6
0
 /**
  * bean转化成字符串
  *
  * @param bean
  * @param beanName
  * @return beanStr
  */
 public static String convertBean2Str(Object bean, String beanName) {
   StringBuffer str = new StringBuffer();
   Class<? extends Object> type = bean.getClass();
   try {
     BeanInfo beanInfo = Introspector.getBeanInfo(type);
     PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
     for (int i = 0; i < propertyDescriptors.length; i++) {
       PropertyDescriptor descriptor = propertyDescriptors[i];
       String propertyName = descriptor.getName();
       if (!propertyName.equals("class")) {
         Method readMethod = descriptor.getReadMethod();
         Object result = readMethod.invoke(bean, new Object[0]);
         if (result != null && StringUtils.trim(result.toString()).length() != 0) {
           str.append("&")
               .append(beanName)
               .append(".")
               .append(propertyName)
               .append("=")
               .append(result);
         }
       }
     }
   } catch (Exception e) {
     log.error(e.getMessage(), e);
   }
   return str.indexOf("&") != -1 ? str.substring(1) : str.toString();
 }
Example #7
0
 /**
  * Specifies the name of the property as it shows up in the xml schema. This method just returns
  * <code>propertyDescriptor.getName();</code>
  *
  * @param desc
  * @return
  */
 protected QName createMappedName(PropertyDescriptor desc, boolean qualified) {
   if (qualified) {
     return new QName(getDefaultNamespace(), desc.getName());
   } else {
     return new QName(null, desc.getName());
   }
 }
Example #8
0
 public static void mapping(Object object, Map<String, ? extends Object> parameter)
     throws IllegalAccessException, InvocationTargetException {
   PropertyDescriptor[] pds = getDescriptors(object.getClass());
   for (int i = 0; i < pds.length; i++) {
     PropertyDescriptor pd = pds[i];
     Object obj = parameter.get(pd.getName());
     Object value = obj;
     Class<?> cls = pd.getPropertyType();
     if (obj instanceof String) {
       String string = (String) obj;
       if (!StringUtil.isEmpty(string)) {
         string = ConfigUtil.filter(string);
       }
       if (isPrimitiveType(cls)) {
         value = convert(cls, string);
       }
     } else if (obj instanceof BeanConfig) {
       value = createBean((BeanConfig) obj);
     } else if (obj instanceof BeanConfig[]) {
       List<Object> list = new ArrayList<Object>();
       for (BeanConfig beanconfig : (BeanConfig[]) obj) {
         list.add(createBean(beanconfig));
       }
       value = list.toArray();
     }
     if (cls != null) {
       if (value != null) {
         Method method = pd.getWriteMethod();
         if (method != null) {
           method.invoke(object, new Object[] {value});
         }
       }
     }
   }
 }
Example #9
0
 private Object getEntityId(Object obj, HibernateTemplate ht)
     throws IllegalAccessException, InvocationTargetException {
   ClassMetadata cm = ht.getSessionFactory().getClassMetadata(superClass);
   String idCol = cm.getIdentifierPropertyName();
   PropertyDescriptor idPropDescr = BeanUtils.getPropertyDescriptor(superClass, idCol);
   return idPropDescr.getReadMethod().invoke(obj);
 }
  /**
   * Uses reflection to fill public fields and optionally Bean properties of the target object from
   * the source Map.
   */
  public static Object fill(Object target, Map<String, Object> source, boolean useProperties)
      throws IntrospectionException, IllegalAccessException, InvocationTargetException {
    if (useProperties) {
      BeanInfo info = Introspector.getBeanInfo(target.getClass());

      PropertyDescriptor[] props = info.getPropertyDescriptors();
      for (int i = 0; i < props.length; ++i) {
        PropertyDescriptor prop = props[i];
        String name = prop.getName();
        Method setter = prop.getWriteMethod();
        if (setter != null && !Modifier.isStatic(setter.getModifiers())) {
          // System.out.println(target + " " + name + " <- " + source.get(name));
          setter.invoke(target, new Object[] {source.get(name)});
        }
      }
    }

    Field[] ff = target.getClass().getDeclaredFields();
    for (int i = 0; i < ff.length; ++i) {
      Field field = ff[i];
      int fieldMod = field.getModifiers();
      if (Modifier.isPublic(fieldMod)
          && !(Modifier.isFinal(fieldMod) || Modifier.isStatic(fieldMod))) {
        // System.out.println(target + " " + field.getName() + " := " +
        // source.get(field.getName()));
        try {
          field.set(target, source.get(field.getName()));
        } catch (IllegalArgumentException iae) {
          // no special error processing required
        }
      }
    }

    return target;
  }
  /**
   * 获得源对象中的属性
   *
   * @param propertiesMapping
   * @param targetDescriptor
   * @param sourceDescriptors
   * @return
   */
  private PropertyDescriptor getSourceDescriptor(
      Map<String, String> propertiesMapping,
      PropertyDescriptor targetDescriptor,
      PropertyDescriptor[] sourceDescriptors) {

    String targetPropertyName = targetDescriptor.getName();
    String tempSourcePropertyName = null;

    if (propertiesMapping != null && propertiesMapping.containsKey(targetPropertyName)) {
      tempSourcePropertyName = propertiesMapping.get(targetPropertyName);
    }

    PropertyDescriptor finalPropertyDescriptor = null;
    for (PropertyDescriptor sourceDescriptor : sourceDescriptors) {

      String iterSourcePropertyName = sourceDescriptor.getName();

      if (tempSourcePropertyName != null && tempSourcePropertyName.equals(iterSourcePropertyName)) {
        finalPropertyDescriptor = sourceDescriptor;
        break;
      } else if (targetPropertyName.equals(iterSourcePropertyName)) {
        finalPropertyDescriptor = sourceDescriptor;
        if (tempSourcePropertyName == null) {
          break;
        }
      }
    }

    return finalPropertyDescriptor;
  }
Example #12
0
 ClassDescr(Class<?> clazz) throws IntrospectionException {
   this.clazz = clazz;
   BeanInfo bi = Introspector.getBeanInfo(clazz);
   PropertyDescriptor[] pds = bi.getPropertyDescriptors();
   for (PropertyDescriptor pd : pds) {
     props.put(pd.getName(), pd);
   }
   //        ignoreCase=(clazz.getAnnotation(IgnoreCase.class)!=null);
   /*
   Sequence seq = clazz.getAnnotation(Sequence.class);
   if (seq != null) {
       sequence = seq.value();
       for (int k=0; k<sequence.length; k++) {
           String attrName=sequence[k];
           if (ignoreCase) {
               attrName = attrName.toLowerCase();
           }
           sequence[k]=attrName;
           seqSet.add(attrName);
       }
   }
   */
   if (sequence == null) {
     sequence = seqSet.toArray(new String[seqSet.size()]);
   } else {
     for (String attr : sequence) {
       if (props.get(attr) == null) {
         throw new IntrospectionException("invalid attr:" + clazz.getName() + "." + attr);
       }
     }
   }
 }
  public void makeApiAvailableToScripts(final Binding binding, final Object cla) {
    final Method[] declaredMethods = cla.getClass().getDeclaredMethods();
    for (Method method : declaredMethods) {
      final String name = method.getName();

      final int modifiers = method.getModifiers();
      if (Modifier.isPublic(modifiers) && !Modifier.isStatic(modifiers)) {
        binding.setVariable(name, new MethodClosure(cla, name));
      }
    }

    PropertyDescriptor[] propertyDescriptors;
    try {
      propertyDescriptors = Introspector.getBeanInfo(cla.getClass()).getPropertyDescriptors();
      for (PropertyDescriptor pd : propertyDescriptors) {
        final Method readMethod = pd.getReadMethod();
        if (readMethod != null) {
          if (isDeclared(cla, readMethod)) {
            binding.setVariable(pd.getName(), invokeMethod(readMethod, cla));
          }
        }
      }
    } catch (IntrospectionException e1) {
      // ignore
    }
  }
  /** add by xiongcf 得到指定属性名的类型 * */
  public Class getDestType(Object bean, String name) {

    // Validate method parameters
    if (bean == null) {
      throw new IllegalArgumentException("No bean specified");
    }
    if (name == null) {
      throw new IllegalArgumentException("No name specified");
    }

    // Return the requested result
    if (bean instanceof DynaBean) {
      // All DynaBean properties are writeable
      return null;
    } else {
      try {
        PropertyDescriptor desc = getPropertyDescriptor(bean, name);
        if (desc != null) {
          Class c = desc.getPropertyType();
          return c;
        } else {
          return null;
        }
      } catch (IllegalAccessException e) {
        return null;
      } catch (InvocationTargetException e) {
        return null;
      } catch (NoSuchMethodException e) {
        return null;
      }
    }
  }
 public Object doGetValue() {
   try {
     Method readMethod = propertyDescriptor.getReadMethod();
     if (readMethod == null) {
       throw new BindingException(
           propertyDescriptor.getName() + " property does not have a read method."); // $NON-NLS-1$
     }
     if (!readMethod.isAccessible()) {
       readMethod.setAccessible(true);
     }
     return readMethod.invoke(object, null);
   } catch (InvocationTargetException e) {
     /*
      * InvocationTargetException wraps any exception thrown by the
      * invoked method.
      */
     throw new RuntimeException(e.getCause());
   } catch (Exception e) {
     if (BeansObservables.DEBUG) {
       Policy.getLog()
           .log(
               new Status(
                   IStatus.WARNING,
                   Policy.JFACE_DATABINDING,
                   IStatus.OK,
                   "Could not read value of " + object + "." + propertyDescriptor.getName(),
                   e)); //$NON-NLS-1$ //$NON-NLS-2$
     }
     return null;
   }
 }
Example #16
0
 private static String[] getPropertyNames(Class<?> clazz, boolean only4Copy) {
   List<String> ret_all = new ArrayList<String>();
   List<String> ret = new ArrayList<String>();
   Field[] fields = CE.of(clazz).getFields(Object.class);
   for (Field fld : fields) {
     if (fld.getModifiers() == Modifier.PUBLIC) {
       ret.add(fld.getName());
     }
     ret_all.add(fld.getName());
   }
   BeanInfo info = null;
   try {
     info = Introspector.getBeanInfo(clazz);
   } catch (IntrospectionException e) {
   }
   if (info != null) {
     PropertyDescriptor[] properties = info.getPropertyDescriptors();
     for (int i = 0; i < properties.length; i++) {
       PropertyDescriptor pd = properties[i];
       if (ret_all.contains(pd.getName()) && !ret.contains(pd.getName())) {
         if (!only4Copy || (pd.getReadMethod() != null && pd.getWriteMethod() != null))
           ret.add(properties[i].getName());
       }
     }
   }
   return ret.toArray(new String[ret.size()]);
 }
 public void doSetValue(Object value) {
   updating = true;
   try {
     Object oldValue = doGetValue();
     Method writeMethod = propertyDescriptor.getWriteMethod();
     if (!writeMethod.isAccessible()) {
       writeMethod.setAccessible(true);
     }
     writeMethod.invoke(object, new Object[] {value});
     fireValueChange(Diffs.createValueDiff(oldValue, doGetValue()));
   } catch (InvocationTargetException e) {
     /*
      * InvocationTargetException wraps any exception thrown by the
      * invoked method.
      */
     throw new RuntimeException(e.getCause());
   } catch (Exception e) {
     if (BeansObservables.DEBUG) {
       Policy.getLog()
           .log(
               new Status(
                   IStatus.WARNING,
                   Policy.JFACE_DATABINDING,
                   IStatus.OK,
                   "Could not change value of " + object + "." + propertyDescriptor.getName(),
                   e)); //$NON-NLS-1$ //$NON-NLS-2$
     }
   } finally {
     updating = false;
   }
 }
Example #18
0
 /**
  * Analyzes the bean and returns a map containing the property-values. Works similar to {@link
  * BeanUtils#describe(Object)} but does not convert everything to strings.
  *
  * @throws IllegalArgumentException if the bean cannot be analyzed properly. Probably because some
  *     getter throw an Exception
  */
 public static Map<String, Object> buildObjectAttributeMap(Object bean)
     throws IllegalArgumentException {
   BeanInfo beanInfo;
   try {
     beanInfo = Introspector.getBeanInfo(bean.getClass(), Object.class);
   } catch (IntrospectionException e1) {
     throw new IllegalArgumentException(e1);
   }
   Map<String, Object> result;
   result = Maps.newHashMap();
   for (PropertyDescriptor pDesc : beanInfo.getPropertyDescriptors()) {
     String name = pDesc.getName();
     Object propertyValue;
     try {
       propertyValue = pDesc.getReadMethod().invoke(bean);
     } catch (IllegalAccessException e) {
       // this should never happen since the Introspector only returns accessible read-methods
       LOGGER.error("WTF: got property descriptor with inaccessible read-method");
       throw new IllegalStateException(e);
     } catch (InvocationTargetException e) {
       ReflectionUtils.handleInvocationTargetException(e);
       throw new IllegalStateException("Should never get here");
     }
     if (propertyValue != null) {
       result.put(name, propertyValue);
     }
   }
   return result;
 }
  private List<PropertyDescriptor> getAdapterPropertyDescriptors0(Class<?> type) {
    if (type == null) {
      throw new IllegalArgumentException("Type must be non-null");
    }

    loadProvidersIfNecessary();

    ArrayList<PropertyDescriptor> des = new ArrayList<PropertyDescriptor>();

    for (BeanAdapterProvider provider : providers) {
      Class<?> pdType = provider.getAdapterClass(type);

      if (pdType != null) {
        BeanInfo info = getBeanInfo(pdType);

        if (info != null) {
          PropertyDescriptor[] pds = info.getPropertyDescriptors();

          if (pds != null) {
            for (PropertyDescriptor pd : pds) {
              if (provider.providesAdapter(type, pd.getName())) {
                des.add(pd);
              }
            }
          }
        }
      }
    }

    return des;
  }
  /**
   * 为对象设置属性
   *
   * @param bean 目标对象
   * @param name 属性的名字
   * @param value 将要设置的属性值
   */
  public static void setProperty(Object bean, String name, String value) {
    Class<?> clazz = bean.getClass();
    PropertyDescriptor propertyDescriptor = findPropertyDescriptor(clazz, name);
    if (propertyDescriptor == null) {
      try {
        throw new Exception(
            "propertyDescriptor is null clazz:" + clazz.getName() + " property name:" + name);
      } catch (Exception e) {
        e.printStackTrace();
      }
    }

    Class<?> type = propertyDescriptor.getPropertyType();
    Object newValue = converValue(type, value);
    Method writeMethod = propertyDescriptor.getWriteMethod();
    try {
      writeMethod.invoke(bean, newValue);
    } catch (IllegalArgumentException e) {
      e.printStackTrace();
    } catch (IllegalAccessException e) {
      e.printStackTrace();
    } catch (InvocationTargetException e) {
      e.printStackTrace();
    }
  }
Example #21
0
  private void getInterfacePropertyDescriptors(
      Class<?> clazz, List<PropertyDescriptor> pds, Set<Class<?>> classes) {
    if (classes.contains(clazz)) {
      return;
    }

    classes.add(clazz);

    try {
      Class[] interfaces = clazz.getInterfaces();

      /** add base interface information */
      BeanInfo info = Introspector.getBeanInfo(clazz);
      for (int j = 0; j < info.getPropertyDescriptors().length; j++) {
        PropertyDescriptor pd = info.getPropertyDescriptors()[j];
        if (!containsPropertyName(pds, pd.getName())) {
          pds.add(pd);
        }
      }

      /** add extended interface information */
      for (int i = 0; i < interfaces.length; i++) {
        getInterfacePropertyDescriptors(interfaces[i], pds, classes);
      }
    } catch (IntrospectionException e) {
      // do nothing
    }
  }
Example #22
0
  public static Map<String, Object> copyPropertyValues(
      Object fromObj, Set<String> excludeProperties) {
    excludeProperties = (excludeProperties == null) ? new HashSet<String>() : excludeProperties;
    excludeProperties.add(
        "class"); // be sure we don't include 'class', which appears in every object
    Map<String, Object> retVal = new HashMap<String, Object>();

    Class<?> fromClazz = fromObj.getClass();
    PropertyDescriptor[] propDescs;
    try {
      propDescs = Introspector.getBeanInfo(fromClazz).getPropertyDescriptors();
      for (PropertyDescriptor propDesc : propDescs) {
        String propName = propDesc.getName();
        if (excludeProperties.contains(propName)) continue;
        Method getter = propDesc.getReadMethod();
        try {
          Object val = getter.invoke(fromObj);
          retVal.put(propName, val);
        } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
          //                    log.error("Error reading property " + propName, e);
        }
      }
    } catch (IntrospectionException e) {
      //            log.error("Error copying property values.");
    }

    return retVal;
  }
Example #23
0
  @Override
  public Map<String, String> saveOrUpdataReturnCasecadeID(
      String objectType, HttpServletRequest request) throws Exception {

    Map<String, String> map = QueryUtil.getRequestParameterMapNoAjax(request);
    Object targetObject = Class.forName(objectType).newInstance();
    String jsonString = map.get(this.getType(objectType).getSimpleName());
    String cascadeTypes = map.get("cascadeType");

    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationConfig.Feature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
    mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    Class<?> clazz = this.getType(objectType);
    targetObject = mapper.readValue(jsonString, clazz);
    Serializable id = this.commDao.saveOrUpdata(objectType, targetObject);

    Object target = this.findById(objectType, id.toString());

    Map<String, String> returenIDs = new HashMap<String, String>();
    returenIDs.put("id", id.toString());

    if (cascadeTypes != null) {
      String[] s = cascadeTypes.split(",");
      for (int i = 0; i < s.length; i++) {
        PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(clazz, s[i]);
        Method method = pd.getReadMethod();
        Object childTarget = method.invoke(target);
        PropertyDescriptor pdID = BeanUtils.getPropertyDescriptor(pd.getPropertyType(), "id");
        String childTargetID = pdID.getReadMethod().invoke(childTarget).toString();
        returenIDs.put(s[i], childTargetID);
      }
    }

    return returenIDs;
  }
Example #24
0
  private static void loadPropertyNamesValues(
      Class clazz, Object instance, List names, List values) {
    PropertyDescriptor pd;
    BeanInfo info = null;
    try {
      info = Introspector.getBeanInfo(clazz);
    } catch (IntrospectionException ex) {
      Err.error(ex);
    }

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

      Object value = SelfReferenceUtils.invokeReadProperty(info, pd, instance, pd.getName());
      if (value == null) { // Err.pr( "No property set for " + pd.getName() + " in " + clazz);
      } else {
        names.add(pd.getName());
        values.add(value);
      }
    }
    if (names.isEmpty()) {
      Err.error("Strange that there are no properties with values in " + clazz);
    }
  }
Example #25
0
  public List gleanAutowiringRequirements(
      Map compositionContext, PlexusContainer container, ClassRealm componentRealm) {
    PropertyDescriptor[] propertyDescriptors =
        (PropertyDescriptor[]) compositionContext.get(PROPERTY_DESCRIPTORS);

    List requirements = new ArrayList();

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

      String role = pd.getPropertyType().getName();

      ComponentDescriptor componentDescriptor =
          container.getComponentDescriptor(role, componentRealm);

      if (componentDescriptor != null) {
        ComponentRequirement requirement = new ComponentRequirement();

        requirement.setRole(role);

        requirements.add(requirement);
      }
    }

    return requirements;
  }
Example #26
0
  /**
   * Perform one setter operation with the provided value.
   *
   * @param instance Instance of class under test to operate on.
   * @param property Property being tested
   * @param field Field being tested
   * @param testVal Test value to use.
   * @return Optional that will contain an error message if the test failed, otherwise empty.
   * @throws InvocationTargetException
   * @throws IllegalAccessException
   */
  private Optional<String> testSetterWithVal(
      T instance, PropertyDescriptor property, Field field, Object testVal)
      throws InvocationTargetException, IllegalAccessException {

    Objects.requireNonNull(instance, "Instance of target class required.");
    boolean status = true;
    property.getWriteMethod().invoke(instance, testVal);

    Object expected, actual;
    if (property.getPropertyType().isPrimitive()) {
      expected = String.valueOf(testVal);
      actual = String.valueOf(field.get(instance));
      status = expected.equals(actual);
    } else {

      expected = testVal;
      actual = field.get(instance);

      if (expected == null) {
        status = actual == null;
      } else {
        status = expected.equals(actual);
      }
    }
    if (status == false) {
      return Optional.of(
          String.format(
              "Failed during setter test: %s.  Expected: %s  Actual: %s",
              property.getWriteMethod(), expected, actual));
    }
    return Optional.empty();
  }
 private void fixNullOutputsForSOAP(CrownCounselIndexGetList_Properties fromClient) {
   // Transform null to "null"
   Class c = fromClient.getClass();
   java.beans.BeanInfo beanInfo = null;
   try {
     beanInfo = java.beans.Introspector.getBeanInfo(c);
   } catch (Exception e) {
   }
   java.beans.PropertyDescriptor[] properties = beanInfo.getPropertyDescriptors();
   for (int i = 0; i < properties.length; i++) {
     java.beans.PropertyDescriptor property = properties[i];
     java.lang.reflect.Method readMethod = property.getReadMethod();
     java.lang.reflect.Method writeMethod = property.getWriteMethod();
     if ((readMethod != null) && (writeMethod != null)) {
       String currentvalue = new String("");
       if (readMethod.getReturnType() == currentvalue.getClass()) {
         try {
           currentvalue = (String) (readMethod.invoke(fromClient, null));
         } catch (java.lang.reflect.InvocationTargetException a1) // Null argument
         {
           try {
             Object[] args1 = new Object[1];
             args1[0] = new String("null");
             writeMethod.invoke(fromClient, args1);
           } catch (Exception e2) {
           }
         } catch (Exception e1) {
         }
       } else {
       }
     }
   }
 }
  /**
   * setArgStringValue purpose.
   *
   * <p>Stores a human friendly version.
   *
   * @param name
   * @param value
   * @return
   */
  public boolean addArgStringValue(String name, String value) {
    PropertyDescriptor pd = getPropertyDescriptor(name);

    if (pd == null) {
      return false;
    }

    if ((value == null) || value.equals("")) {
      args.remove(name);

      return false;
    }

    Class cl = pd.getPropertyType();
    ArgumentConfig ac = new ArgumentConfig();
    ac.setName(name);

    try {
      String argType = ArgHelper.getArgumentType(cl);
      ac.setValue(ArgHelper.getArgumentInstance(argType, value));
    } catch (ValidationException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();

      return false;
    }

    args.put(name, ac);

    return true;
  }
  /**
   * Returns a CSV line for the given LoggingObject - containing all properties in the exact same
   * way as in the config file - excluding those which could not be retrieved, i.e. for which no
   * PropertyDescriptor could be created
   *
   * @param loggingObject the LoggingObject for which a CSV line should be created
   * @return the CSV line representing the given LoggingObject
   */
  public String getCSVRow(LoggingObject loggingObject, boolean anonymize, Long resourceableId) {
    List<String> loggingObjectList = new ArrayList<String>();
    for (Iterator<PropertyDescriptor> it = orderedExportedPropertyDescriptors.iterator();
        it.hasNext(); ) {
      PropertyDescriptor pd = it.next();

      String strValue = "";
      try {
        Object value = pd.getReadMethod().invoke(loggingObject, (Object[]) null);
        if (value != null) {
          strValue = String.valueOf(value);
        }
        if (anonymize && anonymizedProperties.contains(pd.getName())) {
          // do anonymization
          strValue = makeAnonymous(String.valueOf(value), resourceableId);
        }
      } catch (IllegalArgumentException e) {
        // nothing to do
      } catch (IllegalAccessException e) {
        // nothing to do
      } catch (InvocationTargetException e) {
        // nothing to do
      }
      loggingObjectList.add(strValue);
    }

    return StringHelper.formatAsCSVString(loggingObjectList);
  }
Example #30
0
 private void handleCandidateWriteMethod(Method method) throws IntrospectionException {
   int nParams = method.getParameterTypes().length;
   String propertyName = propertyNameFor(method);
   Class<?> propertyType = method.getParameterTypes()[nParams - 1];
   PropertyDescriptor existingPd = findExistingPropertyDescriptor(propertyName, propertyType);
   if (nParams == 1) {
     if (existingPd == null) {
       this.propertyDescriptors.add(new SimplePropertyDescriptor(propertyName, null, method));
     } else {
       existingPd.setWriteMethod(method);
     }
   } else if (nParams == 2) {
     if (existingPd == null) {
       this.propertyDescriptors.add(
           new SimpleIndexedPropertyDescriptor(propertyName, null, null, null, method));
     } else if (existingPd instanceof IndexedPropertyDescriptor) {
       ((IndexedPropertyDescriptor) existingPd).setIndexedWriteMethod(method);
     } else {
       this.propertyDescriptors.remove(existingPd);
       this.propertyDescriptors.add(
           new SimpleIndexedPropertyDescriptor(
               propertyName,
               existingPd.getReadMethod(),
               existingPd.getWriteMethod(),
               null,
               method));
     }
   } else {
     throw new IllegalArgumentException(
         "Write method must have exactly 1 or 2 parameters: " + method);
   }
 }