public ComponentDomainClass(Class type) { super(type, ""); PropertyDescriptor[] descriptors; try { descriptors = java.beans.Introspector.getBeanInfo(type).getPropertyDescriptors(); } catch (IntrospectionException e) { throw new GrailsDomainException( "Failed to use class [" + type + "] as a component. Cannot introspect! " + e.getMessage()); } List tmp = (List) getPropertyOrStaticPropertyOrFieldValue( GrailsDomainClassProperty.TRANSIENT, List.class); if (tmp != null) this.transients = tmp; this.properties = createDomainClassProperties(this, descriptors); try { this.constraints = GrailsDomainConfigurationUtil.evaluateConstraints( getReference().getWrappedInstance(), properties); } catch (IntrospectionException e) { LOG.error( "Error reading embedded component [" + getClazz() + "] constraints: " + e.getMessage(), e); } }
/** * 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()); } } } } }
/*lazy PropertyDescriptor*/ private static PropertyDescriptor[] getPdescriptor() { PropertyDescriptor[] properties = new PropertyDescriptor[2]; try { properties[PROPERTY_columnName] = new PropertyDescriptor( "columnName", com.openitech.db.components.JDbStatusBox.class, "getColumnName", "setColumnName"); // NOI18N properties[PROPERTY_columnName].setPreferred(true); properties[PROPERTY_dataSource] = new PropertyDescriptor( "dataSource", com.openitech.db.components.JDbStatusBox.class, "getDataSource", "setDataSource"); // NOI18N properties[PROPERTY_dataSource].setPreferred(true); } catch (IntrospectionException e) { Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.WARNING, e.getMessage(), e); } // GEN-HEADEREND:Properties // Here you can add code for customizing the properties array. return properties; } // GEN-LAST:Properties
@Override public String buildPrimaryConditionSql(Object entity) throws SQLException { AnnotationUtil annotationUtil = AnnotationUtil.getInstance(); Map<String, Object> primary = annotationUtil.getPrimaryValue(entity); String sql = ""; Map<String, PropertyDescriptor> beanMap = null; try { beanMap = annotationUtil.getBeanInfo(entity.getClass()); } catch (IntrospectionException e1) { throw new SQLException("查询失败:" + e1.getMessage()); } Set<String> primaryNames = primary.keySet(); String joinWord = " where "; for (Iterator<String> it = primaryNames.iterator(); it.hasNext(); ) { String primaryName = it.next(); if (primary.get(primaryName) == null) { continue; } if (sql.indexOf("where") != -1) { joinWord = " and "; } // 获取主键的数据类型 String typeName = beanMap.get(primaryName).getPropertyType().getSimpleName().toLowerCase(); // 若为字符类型 sql += joinWord; if (typeName.equals("string")) { sql += primaryName + "='" + primary.get(primaryName) + "'"; } else { sql += primaryName + "=" + primary.get(primaryName); } } return sql; }
/** @see java.beans.BeanInfo#getPropertyDescriptors() */ public PropertyDescriptor[] getPropertyDescriptors() { try { return new PropertyDescriptor[] { describeAttribute("id", BEAN), describeAttribute("schemaLocation", BEAN) }; } catch (IntrospectionException e) { Gloze.logger.error(e.getMessage()); return null; } }
public void refreshConstraints() { try { GrailsDomainClassProperty[] props = getPersistentProperties(); this.constraints = GrailsDomainConfigurationUtil.evaluateConstraints( getReference().getWrappedInstance(), props); } catch (IntrospectionException e) { LOG.error("Error reading class [" + getClazz() + "] constraints: " + e.getMessage(), e); } }
/** * Reads property descriptors of class * * @param clazz Class for which we are getting property descriptors * @return Array of Class PropertyDescriptors */ public static PropertyDescriptor[] propertyDescriptors(Class<?> clazz) { BeanInfo beanInfo = null; try { beanInfo = Introspector.getBeanInfo(clazz); } catch (IntrospectionException ex) { throw new IllegalArgumentException("Bean introspection failed: " + ex.getMessage()); } return beanInfo.getPropertyDescriptors(); }
/** * Returns a PropertyDescriptor[] for the given Class. * * @param c The Class to retrieve PropertyDescriptors for. * @return A PropertyDescriptor[] describing the Class. * @throws SQLException if introspection failed. */ public static PropertyDescriptor[] propertyDescriptors(Class<?> c) throws SQLException { // Introspector caches BeanInfo classes for better performance BeanInfo beanInfo = null; try { beanInfo = Introspector.getBeanInfo(c); } catch (IntrospectionException e) { throw new SQLException("Bean introspection failed: " + e.getMessage()); } return beanInfo.getPropertyDescriptors(); }
public String toString() { try { updateDiffInfo(); Iterator iter = getDifferences().iterator(); StringBuffer sb = new StringBuffer(); while (iter.hasNext()) { DiffEntry de = (DiffEntry) iter.next(); sb.append(de.toString()); } return sb.toString(); } catch (IntrospectionException e) { return e.getMessage(); } }
/** * Deserializes an Object that was serialized with <code>SopremoUtil.serializeObject()</code> from * a given {@link ObjectInputStream} * * @param ois the stream that contains the serialized object * @param clazz the class of the object that is expected * @return the deserialized object * @throws IOException * @throws ClassNotFoundException */ @SuppressWarnings("unchecked") public static <T> T deserializeObject( final ObjectInputStream ois, @SuppressWarnings("unused") final Class<T> clazz) throws IOException, ClassNotFoundException { if (ois.readBoolean()) return (T) ois.readObject(); T object; try { object = (T) Class.forName(ois.readUTF()).newInstance(); } catch (final InstantiationException e) { throw new IOException(e); } catch (final IllegalAccessException e) { throw new IOException(e); } final Map<String, Object> values = (Map<String, Object>) ois.readObject(); BeanInfo beanInfo; try { beanInfo = Introspector.getBeanInfo(object.getClass()); } catch (final IntrospectionException e) { LOG.info( String.format( "Cannot retrieve bean info for type %s: %s", object.getClass(), e.getMessage())); ois.readObject(); return object; } for (final PropertyDescriptor propertyDescriptor : beanInfo.getPropertyDescriptors()) { final String name = propertyDescriptor.getName(); if (values.containsKey(name)) try { propertyDescriptor.getWriteMethod().invoke(object, values.get(name)); } catch (final Exception e) { LOG.debug( String.format( "Cannot deserialize field %s of type %s: %s", propertyDescriptor.getName(), object.getClass(), e.getMessage())); } } return object; }
static { try { PropertyDescriptor pd = null; sProperties = new ArrayList<PropertyDescriptor>(PhysicalObjectBeanInfo.getPropertyList()); /* pd = new PropertyDescriptor("boundingArea",baseClass); pd.setBound(true); sProperties.add(pd); */ pd = new PropertyDescriptor("application", baseClass); pd.setBound(true); sProperties.add(pd); pd = new PropertyDescriptor("dip", baseClass); sProperties.add(pd); pd = new PropertyDescriptor("generatingB", baseClass); pd.setBound(true); sProperties.add(pd); pd = new PropertyDescriptor("globalField", baseClass); pd.setBound(true); sProperties.add(pd); pd = new PropertyDescriptor("numStripes", baseClass); pd.setBound(true); sProperties.add(pd); pd = new PropertyDescriptor("spreadAxis", baseClass); pd.setBound(true); sProperties.add(pd); pd = new PropertyDescriptor("strike", baseClass); pd.setBound(true); sProperties.add(pd); pd = new PropertyDescriptor("stripsDip", baseClass); pd.setBound(true); sProperties.add(pd); TDebug.println(baseClass.getName() + "BeanInfo: array complete"); } catch (IntrospectionException ie) { TDebug.println(ie.getMessage()); } }
/** * Serializes an Object into the given {@link ObjectOutputStream}. The serialized Object can than * be deserialized with <code>SopremoUtil.deserializeObject()</code> * * @param oos the stream that should be used for serialization * @param object the object that should be serialized * @throws IOException */ public static void serializeObject(final ObjectOutputStream oos, final Object object) throws IOException { if (object instanceof Serializable) { oos.writeBoolean(true); oos.writeObject(object); return; } oos.writeBoolean(false); oos.writeUTF(object.getClass().getName()); final Map<String, Object> values = new HashMap<String, Object>(); BeanInfo beanInfo; try { beanInfo = Introspector.getBeanInfo(object.getClass()); } catch (final IntrospectionException e) { LOG.info( String.format( "Cannot retrieve bean info for type %s: %s", object.getClass(), e.getMessage())); oos.writeObject(values); return; } for (final PropertyDescriptor propertyDescriptor : beanInfo.getPropertyDescriptors()) if (Serializable.class.isAssignableFrom(propertyDescriptor.getPropertyType()) && propertyDescriptor.getReadMethod() != null && propertyDescriptor.getWriteMethod() != null) try { values.put( propertyDescriptor.getName(), propertyDescriptor.getReadMethod().invoke(object)); } catch (final Exception e) { LOG.debug( String.format( "Cannot serialize field %s of type %s: %s", propertyDescriptor.getName(), object.getClass(), e.getMessage())); } oos.writeObject(values); }
/** * Create a new Bean instance. * * @param obj The reference object describing the Bean */ @Override public Object getObjectInstance( Object obj, Name name, Context nameCtx, Hashtable<?, ?> environment) throws NamingException { if (obj instanceof ResourceRef) { try { Reference ref = (Reference) obj; String beanClassName = ref.getClassName(); Class<?> beanClass = null; ClassLoader tcl = Thread.currentThread().getContextClassLoader(); if (tcl != null) { try { beanClass = tcl.loadClass(beanClassName); } catch (ClassNotFoundException e) { } } else { try { beanClass = Class.forName(beanClassName); } catch (ClassNotFoundException e) { e.printStackTrace(); } } if (beanClass == null) { throw new NamingException("Class not found: " + beanClassName); } BeanInfo bi = Introspector.getBeanInfo(beanClass); PropertyDescriptor[] pda = bi.getPropertyDescriptors(); Object bean = beanClass.newInstance(); Enumeration<RefAddr> e = ref.getAll(); while (e.hasMoreElements()) { RefAddr ra = e.nextElement(); String propName = ra.getType(); if (propName.equals(Constants.FACTORY) || propName.equals("scope") || propName.equals("auth") || propName.equals("singleton")) { continue; } String value = (String) ra.getContent(); Object[] valueArray = new Object[1]; int i = 0; for (i = 0; i < pda.length; i++) { if (pda[i].getName().equals(propName)) { Class<?> propType = pda[i].getPropertyType(); if (propType.equals(String.class)) { valueArray[0] = value; } else if (propType.equals(Character.class) || propType.equals(char.class)) { valueArray[0] = Character.valueOf(value.charAt(0)); } else if (propType.equals(Byte.class) || propType.equals(byte.class)) { valueArray[0] = new Byte(value); } else if (propType.equals(Short.class) || propType.equals(short.class)) { valueArray[0] = new Short(value); } else if (propType.equals(Integer.class) || propType.equals(int.class)) { valueArray[0] = new Integer(value); } else if (propType.equals(Long.class) || propType.equals(long.class)) { valueArray[0] = new Long(value); } else if (propType.equals(Float.class) || propType.equals(float.class)) { valueArray[0] = new Float(value); } else if (propType.equals(Double.class) || propType.equals(double.class)) { valueArray[0] = new Double(value); } else if (propType.equals(Boolean.class) || propType.equals(boolean.class)) { valueArray[0] = Boolean.valueOf(value); } else { throw new NamingException( "String conversion for property type '" + propType.getName() + "' not available"); } Method setProp = pda[i].getWriteMethod(); if (setProp != null) { setProp.invoke(bean, valueArray); } else { throw new NamingException("Write not allowed for property: " + propName); } break; } } if (i == pda.length) { throw new NamingException("No set method found for property: " + propName); } } return bean; } catch (java.beans.IntrospectionException ie) { NamingException ne = new NamingException(ie.getMessage()); ne.setRootCause(ie); throw ne; } catch (java.lang.IllegalAccessException iae) { NamingException ne = new NamingException(iae.getMessage()); ne.setRootCause(iae); throw ne; } catch (java.lang.InstantiationException ie2) { NamingException ne = new NamingException(ie2.getMessage()); ne.setRootCause(ie2); throw ne; } catch (java.lang.reflect.InvocationTargetException ite) { NamingException ne = new NamingException(ite.getMessage()); ne.setRootCause(ite); throw ne; } } else { return null; } }
/** * Create a new Bean instance. * * @param obj The reference object describing the Bean */ @Override public Object getObjectInstance( Object obj, Name name, Context nameCtx, Hashtable<?, ?> environment) throws NamingException { if (obj instanceof ResourceRef) { try { Reference ref = (Reference) obj; String beanClassName = ref.getClassName(); Class<?> beanClass = null; ClassLoader tcl = Thread.currentThread().getContextClassLoader(); if (tcl != null) { try { beanClass = tcl.loadClass(beanClassName); } catch (ClassNotFoundException e) { } } else { try { beanClass = Class.forName(beanClassName); } catch (ClassNotFoundException e) { e.printStackTrace(); } } if (beanClass == null) { throw new NamingException("Class not found: " + beanClassName); } BeanInfo bi = Introspector.getBeanInfo(beanClass); PropertyDescriptor[] pda = bi.getPropertyDescriptors(); Object bean = beanClass.newInstance(); /* Look for properties with explicitly configured setter */ RefAddr ra = ref.get("forceString"); Map<String, Method> forced = new HashMap<String, Method>(); String value; if (ra != null) { value = (String) ra.getContent(); Class<?> paramTypes[] = new Class[1]; paramTypes[0] = String.class; String setterName; int index; /* Items are given as comma separated list */ for (String param : value.split(",")) { param = param.trim(); /* A single item can either be of the form name=method * or just a property name (and we will use a standard * setter) */ index = param.indexOf('='); if (index >= 0) { setterName = param.substring(index + 1).trim(); param = param.substring(0, index).trim(); } else { setterName = "set" + param.substring(0, 1).toUpperCase(Locale.ENGLISH) + param.substring(1); } try { forced.put(param, beanClass.getMethod(setterName, paramTypes)); } catch (NoSuchMethodException ex) { throw new NamingException( "Forced String setter " + setterName + " not found for property " + param); } catch (SecurityException ex) { throw new NamingException( "Forced String setter " + setterName + " not allowed for property " + param); } } } Enumeration<RefAddr> e = ref.getAll(); while (e.hasMoreElements()) { ra = e.nextElement(); String propName = ra.getType(); if (propName.equals(Constants.FACTORY) || propName.equals("scope") || propName.equals("auth") || propName.equals("forceString") || propName.equals("singleton")) { continue; } value = (String) ra.getContent(); Object[] valueArray = new Object[1]; /* Shortcut for properties with explicitly configured setter */ Method method = forced.get(propName); if (method != null) { valueArray[0] = value; try { method.invoke(bean, valueArray); } catch (IllegalAccessException ex) { throw new NamingException( "Forced String setter " + method.getName() + " threw IllegalAccessException for property " + propName); } catch (IllegalArgumentException ex) { throw new NamingException( "Forced String setter " + method.getName() + " threw IllegalArgumentException for property " + propName); } catch (InvocationTargetException ex) { throw new NamingException( "Forced String setter " + method.getName() + " threw InvocationTargetException for property " + propName); } continue; } int i = 0; for (i = 0; i < pda.length; i++) { if (pda[i].getName().equals(propName)) { Class<?> propType = pda[i].getPropertyType(); if (propType.equals(String.class)) { valueArray[0] = value; } else if (propType.equals(Character.class) || propType.equals(char.class)) { valueArray[0] = Character.valueOf(value.charAt(0)); } else if (propType.equals(Byte.class) || propType.equals(byte.class)) { valueArray[0] = Byte.valueOf(value); } else if (propType.equals(Short.class) || propType.equals(short.class)) { valueArray[0] = Short.valueOf(value); } else if (propType.equals(Integer.class) || propType.equals(int.class)) { valueArray[0] = Integer.valueOf(value); } else if (propType.equals(Long.class) || propType.equals(long.class)) { valueArray[0] = Long.valueOf(value); } else if (propType.equals(Float.class) || propType.equals(float.class)) { valueArray[0] = Float.valueOf(value); } else if (propType.equals(Double.class) || propType.equals(double.class)) { valueArray[0] = Double.valueOf(value); } else if (propType.equals(Boolean.class) || propType.equals(boolean.class)) { valueArray[0] = Boolean.valueOf(value); } else { throw new NamingException( "String conversion for property " + propName + " of type '" + propType.getName() + "' not available"); } Method setProp = pda[i].getWriteMethod(); if (setProp != null) { setProp.invoke(bean, valueArray); } else { throw new NamingException("Write not allowed for property: " + propName); } break; } } if (i == pda.length) { throw new NamingException("No set method found for property: " + propName); } } return bean; } catch (java.beans.IntrospectionException ie) { NamingException ne = new NamingException(ie.getMessage()); ne.setRootCause(ie); throw ne; } catch (java.lang.IllegalAccessException iae) { NamingException ne = new NamingException(iae.getMessage()); ne.setRootCause(iae); throw ne; } catch (java.lang.InstantiationException ie2) { NamingException ne = new NamingException(ie2.getMessage()); ne.setRootCause(ie2); throw ne; } catch (java.lang.reflect.InvocationTargetException ite) { Throwable cause = ite.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } NamingException ne = new NamingException(ite.getMessage()); ne.setRootCause(ite); throw ne; } } else { return null; } }
@Override public String buildConditionSql( Class<?> entityClass, int firstIndex, int maxResult, Map<String, String> OrderBy, String where_sql, String whereValue, boolean flag) throws SQLException { String sql = null; AnnotationUtil annotationUtil = AnnotationUtil.getInstance(); Map<String, PropertyDescriptor> beanMap = null; try { beanMap = annotationUtil.getBeanInfo(entityClass); } catch (IntrospectionException e1) { throw new SQLException("查询失败:" + e1.getMessage()); } // "select * from " + tableName // 拼接查询sql语句 StringBuffer sqlBuffer = new StringBuffer(); // 如果有条件查询 if (where_sql != null) { sqlBuffer.append(" where "); String[] splitWhereSql = where_sql.split(SqlConstant.CONDITION_SPLIT); String[] splitWhereValue = whereValue.split(SqlConstant.CONDITION_SPLIT); // 如果支持模糊查询 if (flag) { for (int i = 0; i < splitWhereSql.length; i++) { // 获取此参数的类型名 String typeName = beanMap.get(splitWhereSql[i]).getPropertyType().getSimpleName().toLowerCase(); if (typeName.equals("string") || typeName.indexOf("date") != -1) { sqlBuffer .append(splitWhereSql[i] + " like '%" + splitWhereValue[i] + "%'") .append(" and "); } else { sqlBuffer.append(splitWhereSql[i] + "=" + splitWhereValue[i]).append(" and "); } } } else { for (int i = 0; i < splitWhereSql.length; i++) { // 获取此参数的类型名 String typeName = beanMap.get(splitWhereSql[i]).getPropertyType().getSimpleName().toLowerCase(); if (typeName.equals("string") || typeName.indexOf("date") != -1) { sqlBuffer.append(splitWhereSql[i] + "='" + splitWhereValue[i] + "'").append(" and "); } else { sqlBuffer.append(splitWhereSql[i] + "=" + splitWhereValue[i]).append(" and "); } } } // 将多余的and删除 sqlBuffer.delete(sqlBuffer.lastIndexOf("and"), sqlBuffer.length()); } // 设置按主键降序排序 // sqlBuffer.append(" order by " + primaryKeyName + " desc "); /* * if (firstIndex == 0 && maxResult == 0) { * sqlBuffer.append(" order by " + primaryKeyName + " desc "); } else { * sqlBuffer.append(" order by " + primaryKeyName + " desc limit " + * firstIndex + "," + maxResult); } */ sql = sqlBuffer.toString(); return sql; }