@Override
    public List<T> handle(ResultSet rs) throws SQLException {
      List<T> list = new LinkedList<>();
      while (rs.next()) {
        try {
          T t = this.clz.newInstance();
          BeanInfo beanInfo = Introspector.getBeanInfo(this.clz, Object.class);
          PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();

          Map<String, Object> map = new HashMap<String, Object>();
          for (PropertyDescriptor pd : descriptors) {
            String propertyName = pd.getName();
            Class<?> propertyType = pd.getPropertyType();
            if (propertyType.isAnnotationPresent(Entry.class)) {
              propertyName = propertyName + "_id";
            }
            Object value = rs.getObject(propertyName);
            if (propertyType.isAnnotationPresent(Entry.class)) {
              value = getObject(value, propertyType);
            }
            map.put(pd.getName(), value);
          }
          BeanUtils.copyProperties(t, map);
          list.add(t);

        } catch (InstantiationException
            | IllegalAccessException
            | IntrospectionException
            | InvocationTargetException e) {
          e.printStackTrace();
        }
      }
      return list;
    }
  /**
   * @Description: 将一个 Map 对象转化为一个 JavaBean
   *
   * @param @param obj
   * @param @param map
   * @param @return
   * @param @throws IntrospectionException
   * @param @throws IllegalAccessException
   * @param @throws InstantiationException
   * @param @throws InvocationTargetException
   * @return Model
   */
  @SuppressWarnings("rawtypes")
  public static <Model> Model convertMap(Model obj, Map map)
      throws IntrospectionException, IllegalAccessException, InstantiationException,
          InvocationTargetException {
    BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass()); // 获取类属性
    // Model obj = type.newInstance(); // 创建 JavaBean 对象

    // 给 JavaBean 对象的属性赋值
    PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
    for (int i = 0; i < propertyDescriptors.length; i++) {
      PropertyDescriptor descriptor = propertyDescriptors[i];
      String propertyName = descriptor.getName();

      if (map.containsKey(propertyName)) {
        // 下面一句可以 try 起来,这样当一个属性赋值失败的时候就不会影响其他属性赋值。
        Object value = map.get(propertyName);

        Object[] args = new Object[1];
        args[0] = value;

        descriptor.getWriteMethod().invoke(obj, args);
      }
    }
    return obj;
  }
Exemple #3
0
  /**
   * Returns the bean property descriptor of an attribute
   *
   * @param beanClass the class that holds the attribute
   * @param propertyName the name of the property
   * @return the attribute's property descriptor
   */
  public static PropertyDescriptor getPropertyDescriptor(Class<?> beanClass, String propertyName) {
    if (beanClass == null) throw new IllegalArgumentException("beanClass is null");
    String propertyId = beanClass.getName() + '#' + propertyName;
    PropertyDescriptor result = propertyDescriptors.get(propertyId);
    if (result != null) return result;
    // descriptor is new

    int separatorIndex = propertyName.indexOf('.');
    if (separatorIndex >= 0) {
      String localProperty = propertyName.substring(0, separatorIndex);
      String remoteProperty = propertyName.substring(separatorIndex + 1);
      Class<?> localPropertyType =
          getPropertyDescriptor(beanClass, localProperty).getPropertyType();
      result = getPropertyDescriptor(localPropertyType, remoteProperty);
    } else {
      try {
        BeanInfo beanInfo = Introspector.getBeanInfo(beanClass);
        PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor descriptor : descriptors) {
          String name = descriptor.getName();
          if (name.equals(propertyName)) {
            result = descriptor;
            break;
          }
        }
      } catch (IntrospectionException e) {
        throw ExceptionMapper.configurationException(e, propertyName);
      }
    }
    propertyDescriptors.put(propertyId, result);
    return result;
  }
Exemple #4
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()]));
    }
  public static Object buildBean(Class<?> beanClass, Map<String, String> values) {
    try {
      Object obj = null;

      if (beanClass.isInterface()) {
        @SuppressWarnings("unchecked")
        Class<? extends OpenEngSBModel> model = (Class<? extends OpenEngSBModel>) beanClass;
        obj = ekbService.createEmptyModelObject(model);
      } else {
        obj = beanClass.newInstance();
      }

      BeanInfo beanInfo = Introspector.getBeanInfo(beanClass);
      PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
      for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
        if (propertyDescriptor.getWriteMethod() == null
            || !Modifier.isPublic(propertyDescriptor.getWriteMethod().getModifiers())) {
          continue;
        }
        String value = values.get(propertyDescriptor.getName());
        Object ob = convertToCorrectClass(propertyDescriptor.getPropertyType(), value);
        propertyDescriptor.getWriteMethod().invoke(obj, ob);
      }
      return obj;
    } catch (Exception e) {
      throw new IllegalArgumentException(e);
    }
  }
Exemple #6
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);
   }
 }
  public static void main(String[] args) throws IntrospectionException {
    BeanInfo beanInfo = Introspector.getBeanInfo(User.class);

    System.out.println("==>MethodDescriptor");
    MethodDescriptor[] methodDescs = beanInfo.getMethodDescriptors();
    for (MethodDescriptor method : methodDescs) {
      System.out.println(method.getName());
      System.out.println(method.getDisplayName());
      System.out.println(method.getShortDescription());
      System.out.println(method.getValue("getName"));

      System.out.println("==>MethodDescriptor/ReflectionMethod");
      Method reflectMethod = method.getMethod();
      System.out.println(reflectMethod.getName());

      System.out.println("==>MethodDescriptor/ParameterDescriptor");
      ParameterDescriptor[] paramDescs = method.getParameterDescriptors();
      if (paramDescs != null) {
        for (ParameterDescriptor paramDesc : paramDescs) {
          System.out.println(paramDesc.getName());
          System.out.println(paramDesc.getDisplayName());
          System.out.println(paramDesc.getShortDescription());
          System.out.println(paramDesc.getValue("name"));
        }
      }
    }
  }
  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();
        }
      }
    }
  }
  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;
  }
Exemple #10
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);
    }
  }
Exemple #11
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());
         }
       }
     }
   }
 }
  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);
    }
  }
  @Test
  public void overloadedNonStandardWriteMethodsOnly_orderB()
      throws IntrospectionException, SecurityException, NoSuchMethodException {
    @SuppressWarnings("unused")
    class C {
      public Object setFoo(int p) {
        return new Object();
      }

      public Object setFoo(String p) {
        return new Object();
      }
    }
    BeanInfo bi = Introspector.getBeanInfo(C.class);

    assertThat(hasReadMethodForProperty(bi, "foo"), is(false));
    assertThat(hasWriteMethodForProperty(bi, "foo"), is(false));

    BeanInfo ebi = new ExtendedBeanInfo(bi);

    assertThat(hasReadMethodForProperty(bi, "foo"), is(false));
    assertThat(hasWriteMethodForProperty(bi, "foo"), is(false));

    assertThat(hasReadMethodForProperty(ebi, "foo"), is(false));
    assertThat(hasWriteMethodForProperty(ebi, "foo"), is(true));

    for (PropertyDescriptor pd : ebi.getPropertyDescriptors()) {
      if (pd.getName().equals("foo")) {
        assertThat(pd.getWriteMethod(), is(C.class.getMethod("setFoo", String.class)));
        return;
      }
    }
    fail("never matched write method");
  }
  @Test
  public void propertyCountsMatch() throws IntrospectionException {
    BeanInfo bi = Introspector.getBeanInfo(TestBean.class);
    BeanInfo ebi = new ExtendedBeanInfo(bi);

    assertThat(ebi.getPropertyDescriptors().length, equalTo(bi.getPropertyDescriptors().length));
  }
  @Test
  public void shouldUseExtendedBeanInfoWhenApplicable()
      throws NoSuchMethodException, SecurityException {
    // given a class with a non-void returning setter method
    @SuppressWarnings("unused")
    class C {
      public Object setFoo(String s) {
        return this;
      }

      public String getFoo() {
        return null;
      }
    }

    // CachedIntrospectionResults should delegate to ExtendedBeanInfo
    CachedIntrospectionResults results = CachedIntrospectionResults.forClass(C.class);
    BeanInfo info = results.getBeanInfo();
    PropertyDescriptor pd = null;
    for (PropertyDescriptor candidate : info.getPropertyDescriptors()) {
      if (candidate.getName().equals("foo")) {
        pd = candidate;
      }
    }

    // resulting in a property descriptor including the non-standard setFoo method
    assertThat(pd, notNullValue());
    assertThat(pd.getReadMethod(), equalTo(C.class.getMethod("getFoo")));
    assertThat(
        "No write method found for non-void returning 'setFoo' method. "
            + "Check to see if CachedIntrospectionResults is delegating to "
            + "ExtendedBeanInfo as expected",
        pd.getWriteMethod(),
        equalTo(C.class.getMethod("setFoo", String.class)));
  }
Exemple #16
0
  public Object getPrincipalProperty(String property) {
    Subject subject = SecurityUtils.getSubject();

    if (subject != null) {
      Object principal = subject.getPrincipal();

      try {
        BeanInfo bi = Introspector.getBeanInfo(principal.getClass());

        for (PropertyDescriptor pd : bi.getPropertyDescriptors()) {
          if (pd.getName().equals(property) == true) {
            return pd.getReadMethod().invoke(principal, (Object[]) null);
          }
        }

        logger.trace(
            "Property [{}] not found in principal of type [{}]",
            property,
            principal.getClass().getName());
      } catch (Exception e) {
        logger.trace(
            "Error reading property [{}] from principal of type [{}]",
            property,
            principal.getClass().getName());
      }
    }

    return null;
  }
Exemple #17
0
  /** Return an entry from the property descrpitor cache for a class. */
  private PropertyDescriptorCacheEntry getPropertyDescriptorCacheEntry(Class c) {
    PropertyDescriptorCacheEntry pce =
        (PropertyDescriptorCacheEntry) propertyDescriptorCache.get(c);

    try {
      if (pce == null) {
        BeanInfo beanInfo = Introspector.getBeanInfo(c, stopClass);
        pce = new PropertyDescriptorCacheEntry();
        pce.propertyDescriptors = beanInfo.getPropertyDescriptors();
        pce.propertiesByName = createPropertiesByNameMap(pce.propertyDescriptors, c.getFields());
        if (cachePropertiesDescriptors) {
          synchronized (propertyDescriptorCache) {
            PropertyDescriptorCacheEntry pce2 =
                (PropertyDescriptorCacheEntry) propertyDescriptorCache.get(c);
            if (pce2 == null) propertyDescriptorCache.put(c, pce);
            else pce = pce2;
          }
        }
      }
    } catch (IntrospectionException ex) {
      // Log failed property set errors
      if (Log.isError()) {
        Logger log = Log.getLogger(LOG_CATEGORY);
        log.error(
            "Failed to introspect object of type: " + c + " error: " + ExceptionUtil.toString(ex));
      }

      // Return an empty descriptor rather than crashing
      pce = new PropertyDescriptorCacheEntry();
      pce.propertyDescriptors = new PropertyDescriptor[0];
      pce.propertiesByName = new TreeMap();
    }
    return pce;
  }
Exemple #18
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()]);
 }
Exemple #19
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);
       }
     }
   }
 }
 /**
  * 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;
 }
  /**
   * 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;
  }
 /**
  * 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 static Method getReadMethod(Class<?> beanClass, String prop) throws JasperException {

    Method method = null;
    Class<?> type = null;
    try {
      java.beans.BeanInfo info = java.beans.Introspector.getBeanInfo(beanClass);
      if (info != null) {
        java.beans.PropertyDescriptor pd[] = info.getPropertyDescriptors();
        for (int i = 0; i < pd.length; i++) {
          if (pd[i].getName().equals(prop)) {
            method = pd[i].getReadMethod();
            type = pd[i].getPropertyType();
            break;
          }
        }
      } else {
        // just in case introspection silently fails.
        throw new JasperException(
            Localizer.getMessage("jsp.error.beans.nobeaninfo", beanClass.getName()));
      }
    } catch (Exception ex) {
      throw new JasperException(ex);
    }
    if (method == null) {
      if (type == null) {
        throw new JasperException(
            Localizer.getMessage("jsp.error.beans.noproperty", prop, beanClass.getName()));
      } else {
        throw new JasperException(
            Localizer.getMessage("jsp.error.beans.nomethod", prop, beanClass.getName()));
      }
    }

    return method;
  }
Exemple #24
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
    }
  }
  private JPanel getRemoveOptionsPanel() {

    if (pnlRemoveOptions == null) {
      pnlRemoveOptions = new JPanel(new BorderLayout());
      DefaultBeanInfoResolver resolver = new DefaultBeanInfoResolver();

      BeanInfo beanInfo = resolver.getBeanInfo(options);

      PropertySheetPanel sheet = new PropertySheetPanel();
      sheet.setMode(PropertySheet.VIEW_AS_CATEGORIES);
      sheet.setProperties(beanInfo.getPropertyDescriptors());
      sheet.readFromObject(options);
      sheet.setDescriptionVisible(true);
      sheet.setSortingCategories(true);
      sheet.setSortingProperties(true);
      pnlRemoveOptions.add(sheet, BorderLayout.CENTER);

      // everytime a property change, update the button with it
      PropertyChangeListener listener =
          new PropertyChangeListener() {
            public void propertyChange(PropertyChangeEvent evt) {
              Property prop = (Property) evt.getSource();
              prop.writeToObject(options);
            }
          };
      sheet.addPropertySheetChangeListener(listener);
    }

    return pnlRemoveOptions;
  }
  /**
   * Load bean information into a cache, because this operation will be slow.
   *
   * @param clazz
   * @throws IntrospectionException
   */
  protected PropertyDescriptor[] loadIntrospectionForClass(Class<?> clazz) {
    if (null == clazz) {
      throw new IllegalArgumentException("No bean class specified");
    }

    PropertyDescriptor[] descriptors = null;
    descriptors = introspectionCache.get(clazz);
    if (descriptors != null) {
      return descriptors;
    }

    BeanInfo beanInfo = null;
    try {
      beanInfo = Introspector.getBeanInfo(clazz);

      descriptors = beanInfo.getPropertyDescriptors();
      if (null == descriptors) {
        descriptors = new PropertyDescriptor[0];
      }
    } catch (IntrospectionException e) {
      e.printStackTrace();
      descriptors = new PropertyDescriptor[0];
    }

    introspectionCache.put(clazz, descriptors);
    return descriptors;
  }
 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 {
       }
     }
   }
 }
  @Override
  public PropertyDescriptor[] getPropertyDescriptors(String name, URI uri) {
    // platform:/resource/simple-jdbc-dao/src/main/resources/statements.meta
    if (allLoaders == null) init();
    Class<?> beanClass = loadClass(name, uri);
    if (beanClass == null) return null;

    // Look up any cached descriptors for this bean class
    PropertyDescriptor[] descriptors = null;
    // descriptors = (PropertyDescriptor[]) descriptorsCache.get(beanClass);
    // if (descriptors != null) {
    // return (descriptors);
    // }

    // Introspect the bean and cache the generated descriptors
    BeanInfo beanInfo = null;
    try {
      beanInfo = Introspector.getBeanInfo(beanClass);
    } catch (IntrospectionException e) {
      return (new PropertyDescriptor[0]);
    }
    descriptors = beanInfo.getPropertyDescriptors();
    if (descriptors == null) {
      descriptors = new PropertyDescriptor[0];
    }

    // descriptorsCache.put(beanClass, descriptors);
    return descriptors;
  }
  public PropertySheetApplicationStats() {
    setLayout(LookAndFeelTweaks.createVerticalPercentLayout());

    final Bean data = new Bean();

    TimeSpan timespan = null;

    // counts of objects
    long discCount = HibernateDao.countAll(Disc.class);
    data.setCountArtists(Long.toString(HibernateDao.countAll(Artist.class)));
    data.setCountDiscs(Long.toString(discCount));
    data.setCountTracks(Long.toString(HibernateDao.countAll(Track.class)));

    // time stats
    long totalTime = 0;
    long totalSize = 0;
    long avgTimePerDisc = 0;
    long avgSizePerDisc = 0;
    try {
      totalTime = HibernateDao.sum(Disc.class, Disc.PROPERTYNAME_DURATION);
      totalSize = HibernateDao.sum(Track.class, Track.PROPERTYNAME_TRACK_SIZE);
      avgTimePerDisc = (totalTime / discCount) * 1000;
      avgSizePerDisc = (totalSize / discCount);
    } catch (RuntimeException ex) {
      totalTime = 0;
    }

    // calculate time fields to display properly
    timespan = new TimeSpan(totalTime * 1000);
    data.setTimeTotal(timespan.toString());
    timespan = new TimeSpan(avgTimePerDisc);
    data.setTimeAveragePerDisc(timespan.toString());

    // file stats
    data.setFileTotal(FileUtils.byteCountToDisplaySize(totalSize));
    data.setFileAveragePerDisc(FileUtils.byteCountToDisplaySize(avgSizePerDisc));

    DefaultBeanInfoResolver resolver = new DefaultBeanInfoResolver();
    BeanInfo beanInfo = resolver.getBeanInfo(data);

    PropertySheetPanel sheet = new PropertySheetPanel();
    sheet.setMode(PropertySheet.VIEW_AS_CATEGORIES);
    sheet.setProperties(beanInfo.getPropertyDescriptors());
    sheet.readFromObject(data);
    sheet.setDescriptionVisible(true);
    sheet.setSortingCategories(true);
    sheet.setSortingProperties(true);
    add(sheet, "*");

    // everytime a property change, update the button with it
    PropertyChangeListener listener =
        new PropertyChangeListener() {
          public void propertyChange(PropertyChangeEvent evt) {
            Property prop = (Property) evt.getSource();
            prop.writeToObject(data);
          }
        };
    sheet.addPropertySheetChangeListener(listener);
  }
Exemple #30
0
 public static Method methodFor(String methodName) throws IntrospectionException {
   BeanInfo beanInfo = Introspector.getBeanInfo(SomeSteps.class);
   for (MethodDescriptor md : beanInfo.getMethodDescriptors()) {
     if (md.getMethod().getName().equals(methodName)) {
       return md.getMethod();
     }
   }
   return null;
 }