Esempio n. 1
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;
  }
Esempio n. 2
0
  public static BeanDescription describe(Class beanClass) {
    BeanDescription beanDescription = knownBeanDescriptions.get(beanClass.getName());
    if (beanDescription != null) {
      return beanDescription;
    }

    try {
      beanDescription = new BeanDescription();
      PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(beanClass);

      for (PropertyDescriptor descriptor : descriptors) {
        if (descriptor.getReadMethod() == null || descriptor.getWriteMethod() == null) {
          continue;
        }

        beanDescription.description.put(descriptor.getName(), descriptor);

        beanDescription.readMethodToDescriptor.put(
            descriptor.getReadMethod().getName(), descriptor);

        beanDescription.writeMethodToDescriptor.put(
            descriptor.getWriteMethod().getName(), descriptor);

        beanDescription.readMethodToPropertyName.put(
            descriptor.getReadMethod().getName(), descriptor.getName());

        beanDescription.writeMethodToPropertyName.put(
            descriptor.getWriteMethod().getName(), descriptor.getName());
      }
      knownBeanDescriptions.put(beanClass.getName(), beanDescription);
      return beanDescription;
    } catch (Throwable t) {
      throw new RuntimeException(t);
    }
  }
Esempio n. 3
0
  /**
   * Test setter and getter call and make sure they match.
   *
   * <p>
   *
   * @param property the property to be set
   * @param setValue the value to be set
   * @param qName qualified name for error reporting
   */
  private static void testProperty(
      Object target, PropertyDescriptor property, Object setValue, String qName) {

    // flag indicating whether a comparison should be done at the end
    boolean expectMatch = true;

    // call setter (if exists)
    if (property.getWriteMethod() != null) {
      invokeMethod(target, property.getWriteMethod(), new Object[] {setValue}, qName);
    } else {
      Assert.assertFalse(true, "Property " + qName + " does not have the required setter.");
      expectMatch = false;
    }

    // call getter (if exists)
    Object getValue = null;
    if (property.getReadMethod() != null) {
      getValue = invokeMethod(target, property.getReadMethod(), null, qName);
    } else {
      Assert.assertFalse(true, "Property " + qName + " does not have the required getter.");
      expectMatch = false;
    }

    // if expecting a match, compare
    // if they are not the same instance, assert that they have equality
    if (expectMatch && setValue != getValue)
      Assert.assertEquals(
          getValue, setValue, "Values did not match for getter/setter call on field " + qName);
  }
  private static HashMap<String, Object> inspectObject(Object o) throws IntrospectionException {
    if (inspections.containsKey(o.getClass())) {
      return inspections.get(o.getClass());
    }

    PropertyDescriptor[] pds = Introspector.getBeanInfo(o.getClass()).getPropertyDescriptors();
    HashMap<String, Object> values = new HashMap<String, Object>();

    for (PropertyDescriptor pd : pds) {
      if (pd.getName().equals("class")
          || (pd.getReadMethod() == null)
          || (pd.getWriteMethod() == null)
          || ((pd.getReadMethod().getModifiers() & Modifier.PUBLIC) == 0)
          || ((pd.getWriteMethod().getModifiers() & Modifier.PUBLIC) == 0)) {
        continue;
      }

      values.put(pd.getName(), pd);
    }

    for (Field field : o.getClass().getFields()) {
      if (((field.getModifiers() & Modifier.PUBLIC) != 0)
          && ((field.getModifiers() & Modifier.FINAL) == 0)
          && ((field.getModifiers() & Modifier.STATIC) == 0)
          && (values.get(field.getName()) == null)) {
        values.put(field.getName(), field);
      }
    }

    inspections.put(o.getClass(), values);

    return values;
  }
Esempio n. 5
0
 /**
  * Gets the value of property from the bean object.
  *
  * @param bean the object of bean class whose property is to access.
  * @param property the name of property.
  * @return the value of property.
  * @throws IntrospectionException
  * @throws IllegalArgumentException
  * @throws IllegalAccessException
  * @throws InvocationTargetException
  */
 public static final Object getPropertyValue(Object bean, String property)
     throws IntrospectionException, IllegalArgumentException, IllegalAccessException,
         InvocationTargetException {
   Object propertyValue = null;
   PropertyDescriptor descriptor = getPropertyDescriptor(bean.getClass(), property);
   if (descriptor != null && descriptor.getReadMethod() != null) {
     propertyValue = descriptor.getReadMethod().invoke(bean, null);
   }
   return propertyValue;
 }
Esempio n. 6
0
  @Override
  public boolean matches(Object argument) {
    if (equalTo(object).matches(argument)) {
      // short circuit: equal is always equivalent
      return true;
    }

    if (argument != null && object.getClass() == argument.getClass()) {
      BeanInfo beanInfo = null;

      try {
        beanInfo = Introspector.getBeanInfo(object.getClass());
      } catch (IntrospectionException shouldNeverHappen) {
        throw new Error(shouldNeverHappen);
      }

      for (PropertyDescriptor pd : beanInfo.getPropertyDescriptors()) {
        if (pd.getReadMethod() == null) {
          continue;
        }

        Object value1 = null;

        try {
          value1 = pd.getReadMethod().invoke(object);
        } catch (RuntimeException e) {
          throw e;
        } catch (Exception e) {
          new Error(e);
        }

        Object value2 = null;

        try {
          value2 = pd.getReadMethod().invoke(object);
        } catch (RuntimeException e) {
          // prevent us from wrapping RuntimExceptions unnecessarily
          throw e;
        } catch (Exception shouldNeverHappen) {
          new Error(shouldNeverHappen);
        }

        if (!equalTo(value1).matches(value2)) {
          return false;
        }
      }

      return true;
    }

    return false;
  }
Esempio n. 7
0
  public static Class<?> determineGenericsType(PropertyDescriptor propDescriptor) {
    Class<?> result = null;
    // Try getter and setter to determine the Generics type in case one does not exist
    if (propDescriptor.getWriteMethod() != null) {
      result = determineGenericsType(propDescriptor.getWriteMethod(), false);
    }

    if (result == null && propDescriptor.getReadMethod() != null) {
      result = determineGenericsType(propDescriptor.getReadMethod(), true);
    }

    return result;
  }
Esempio n. 8
0
 public static Map<String, Method> getGetters(Class<?> clazz) {
   BeanInfo beanInfo;
   Map<String, Method> methodMap = new HashMap<String, Method>();
   try {
     beanInfo = Introspector.getBeanInfo(clazz);
     for (PropertyDescriptor prop : beanInfo.getPropertyDescriptors()) {
       if (prop.getReadMethod() != null) {
         methodMap.put(prop.getName(), prop.getReadMethod());
       }
     }
   } catch (IntrospectionException e) {
     methodMap = null;
   }
   return methodMap;
 }
Esempio n. 9
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();
 }
 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;
   }
 }
Esempio n. 11
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;
  }
Esempio n. 12
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;
 }
Esempio n. 13
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()]);
 }
Esempio n. 14
0
 public TypeWrapper(Class c) throws IntrospectionException {
   Map<String, Field> fields = new HashMap();
   loadFields(c, fields);
   BeanInfo bi = Introspector.getBeanInfo(c, Object.class);
   PropertyDescriptor[] props = bi.getPropertyDescriptors();
   for (int i = 0; i < props.length; i++) {
     PropertyDescriptor pd = props[i];
     Annotation[] ann = null;
     Field f = fields.get(pd.getName());
     if (f != null) {
       f.getAnnotations();
     }
     Class type = pd.getPropertyType();
     boolean arrayFlag = type.isArray();
     PropertyInfo pi =
         new PropertyInfo(
             pd.getName(),
             ann,
             (arrayFlag ? type.getComponentType() : type),
             arrayFlag,
             pd.getReadMethod(),
             pd.getWriteMethod());
     this.properties.put(pi.getName(), pi);
   }
 }
  private Object invokeAttribute(PropertyDescriptor pd, MethodInvocation invocation)
      throws JMException, IOException {

    String attributeName = JmxUtils.getAttributeName(pd, this.useStrictCasing);
    MBeanAttributeInfo inf = (MBeanAttributeInfo) this.allowedAttributes.get(attributeName);

    // If no attribute is returned, we know that it is not defined in the
    // management interface.
    if (inf == null) {
      throw new InvalidInvocationException(
          "Attribute '" + pd.getName() + "' is not exposed on the management interface");
    }
    if (invocation.getMethod().equals(pd.getReadMethod())) {
      if (inf.isReadable()) {
        return this.server.getAttribute(this.objectName, attributeName);
      } else {
        throw new InvalidInvocationException("Attribute '" + attributeName + "' is not readable");
      }
    } else if (invocation.getMethod().equals(pd.getWriteMethod())) {
      if (inf.isWritable()) {
        server.setAttribute(
            this.objectName, new Attribute(attributeName, invocation.getArguments()[0]));
        return null;
      } else {
        throw new InvalidInvocationException("Attribute '" + attributeName + "' is not writable");
      }
    } else {
      throw new IllegalStateException(
          "Method [" + invocation.getMethod() + "] is neither a bean property getter nor a setter");
    }
  }
Esempio n. 16
0
  public boolean isMapped(PropertyDescriptor pd) {
    if (pd.getReadMethod() == null) {
      return false;
    }

    return true;
  }
  /**
   * Compares this <code>PropertyDescriptor</code> against the specified object. Returns true if the
   * objects are the same. Two <code>PropertyDescriptor</code>s are the same if the read, write,
   * property types, property editor and flags are equivalent.
   *
   * @since 1.4
   */
  public boolean equals(Object obj) {
    if (this == obj) {
      return true;
    }
    if (obj != null && obj instanceof PropertyDescriptor) {
      PropertyDescriptor other = (PropertyDescriptor) obj;
      Method otherReadMethod = other.getReadMethod();
      Method otherWriteMethod = other.getWriteMethod();

      if (!compareMethods(getReadMethod(), otherReadMethod)) {
        return false;
      }

      if (!compareMethods(getWriteMethod(), otherWriteMethod)) {
        return false;
      }

      if (getPropertyType() == other.getPropertyType()
          && getPropertyEditorClass() == other.getPropertyEditorClass()
          && bound == other.isBound()
          && constrained == other.isConstrained()
          && writeMethodName == other.writeMethodName
          && readMethodName == other.readMethodName) {
        return true;
      }
    }
    return false;
  }
  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
    }
  }
Esempio n. 19
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);
   }
 }
Esempio n. 20
0
 public static Map<String, String> getEntityPropertiesToStringMap(
     Object entity, Map<String, String> fieldClassMapping, String... entityIdentifier) {
   Map<String, String> propertiesMap = new HashMap<String, String>();
   StringBuffer sb = new StringBuffer();
   if (entityIdentifier.length > 0) {
     for (String ei : entityIdentifier) {
       sb.append(ei + ".");
     }
   }
   String prefixStr = sb.toString();
   PropertyDescriptor[] pds = BeanUtils.getPropertyDescriptors(entity.getClass());
   for (PropertyDescriptor pd : pds) {
     Method readMethod = pd.getReadMethod();
     if (null == readMethod) continue;
     Class<?> returnType = readMethod.getReturnType();
     Object returnValue = null;
     try {
       returnValue = readMethod.invoke(entity);
     } catch (IllegalArgumentException e) {
       e.printStackTrace();
     } catch (IllegalAccessException e) {
       e.printStackTrace();
     } catch (InvocationTargetException e) {
       e.printStackTrace();
     }
     if (null != returnValue) {
       String value = "";
       if (returnType.isAssignableFrom(Set.class)) {
         continue;
       } else if (isTenwaEntity(returnType)) {
         String fieldName = null;
         if (null != fieldClassMapping) {
           fieldName = fieldClassMapping.get(returnType.getSimpleName());
         }
         if (StringUtils.isBlank(fieldName)) {
           fieldName = "id";
         }
         Method method = BeanUtils.getPropertyDescriptor(returnType, fieldName).getReadMethod();
         // System.out.println("####:"+method.getName()+","+returnValue);
         try {
           value = StringUtil.nullToString(method.invoke(returnValue));
         } catch (IllegalArgumentException e) {
           e.printStackTrace();
         } catch (IllegalAccessException e) {
           e.printStackTrace();
         } catch (InvocationTargetException e) {
           e.printStackTrace();
         }
       } else {
         if (returnType.getSimpleName().equalsIgnoreCase("double")) {
           value = MathUtil.decimal((Double) returnValue, 8);
         } else {
           value = returnValue.toString();
         }
       }
       propertiesMap.put(prefixStr + pd.getName().toLowerCase(), value);
     }
   }
   return propertiesMap;
 }
Esempio n. 21
0
  public static void copyProperties(Object target, Object source, String[] ignoreProperties) {
    if (target instanceof Map) {
      throw new UnsupportedOperationException("target is Map unsuported");
    }

    PropertyDescriptor[] targetPds = getPropertyDescriptors(target.getClass());
    List ignoreList = (ignoreProperties != null) ? Arrays.asList(ignoreProperties) : null;

    for (int i = 0; i < targetPds.length; i++) {
      PropertyDescriptor targetPd = targetPds[i];
      if (targetPd.getWriteMethod() != null
          && (ignoreProperties == null || (!ignoreList.contains(targetPd.getName())))) {
        try {
          if (source instanceof Map) {
            Map map = (Map) source;
            if (map.containsKey(targetPd.getName())) {
              Object value = map.get(targetPd.getName());
              setProperty(target, targetPd, value);
            }
          } else {
            PropertyDescriptor sourcePd =
                getPropertyDescriptors(source.getClass(), targetPd.getName());
            if (sourcePd != null && sourcePd.getReadMethod() != null) {
              Object value = getProperty(source, sourcePd);
              setProperty(target, targetPd, value);
            }
          }
        } catch (Throwable ex) {
          throw new IllegalArgumentException(
              "Could not copy properties on:" + targetPd.getDisplayName(), ex);
        }
      }
    }
  }
Esempio n. 22
0
 private void refresh() {
   if (this.value == null) {
     this.setEnabled(false);
     return;
   }
   this.setEnabled(true);
   for (final PropertyDescriptor pd : this.beanInfo.getPropertyDescriptors()) {
     final JTextField field = this.fieldMap.get(pd.getName());
     PropertyEditor editor = pd.createPropertyEditor(this.getValue());
     if (editor == null) {
       editor = PropertyEditorManager.findEditor(pd.getPropertyType());
     }
     if (editor == null) {
       continue;
     }
     Object propertyValue = null;
     try {
       propertyValue = pd.getReadMethod().invoke(this.getValue());
     } catch (final Exception e) {
       // Just continue
       continue;
     }
     field.setText(propertyValue != null ? propertyValue.toString() : "null");
   }
 }
Esempio n. 23
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);
    }
  }
Esempio n. 24
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);
 }
Esempio n. 25
0
 public static <T extends Annotation> T getAnnotation(
     PropertyDescriptor pd, Class<T> annotationType) {
   Method readMethod = pd.getReadMethod();
   Preconditions.checkNotNull(readMethod);
   T column = AnnotationUtils.findAnnotation(readMethod, annotationType);
   return column;
 }
Esempio n. 26
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()]));
    }
 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 {
       }
     }
   }
 }
  public void setBeanInfo() {
    BeanInfo info = null;
    try {
      info = Introspector.getBeanInfo(bean.getClass());
    } catch (IntrospectionException ex) {
      ex.printStackTrace();
    }

    for (PropertyDescriptor pd : info.getPropertyDescriptors()) {
      if (!pd.getName().equals("class")) {
        try {
          Object value = null;
          if (properties.get(pd.getName()) != null) {
            value = properties.get(pd.getName());
            if (value.equals("false") || value.equals("true")) {
              pd.getWriteMethod().invoke(bean, new Object[] {Boolean.valueOf((String) value)});
            } else {
              pd.getWriteMethod().invoke(bean, new Object[] {value});
            }
          } else {
            value = pd.getReadMethod().invoke(bean, new Object[] {});
            pd.getWriteMethod().invoke(bean, new Object[] {value});
          }
        } catch (IllegalArgumentException ex) {
          ex.printStackTrace();
        } catch (IllegalAccessException ex) {
          ex.printStackTrace();
        } catch (InvocationTargetException ex) {
          ex.printStackTrace();
        }
      }
    }
  }
  /**
   * 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);
  }
Esempio n. 30
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);
 }