List of usage examples for java.beans PropertyDescriptor getWriteMethod
public synchronized Method getWriteMethod()
From source file:org.apache.eagle.storage.jdbc.entity.JdbcEntitySerDeserHelper.java
/** * * @param row/* ww w . ja va 2s . co m*/ * @param entityDefinition * @param <E> * @return * @throws IllegalAccessException * @throws InstantiationException * @throws InvocationTargetException * @throws NoSuchMethodException */ public static <E extends TaggedLogAPIEntity> E buildEntity(Map<String, Object> row, JdbcEntityDefinition entityDefinition) throws IOException { EntityDefinition ed = entityDefinition.getInternal(); Class<? extends TaggedLogAPIEntity> clazz = ed.getEntityClass(); if (clazz == null) { throw new NullPointerException("Entity class of service " + ed.getService() + " is null"); } TaggedLogAPIEntity obj = null; try { obj = clazz.newInstance(); } catch (Exception e) { LOG.error(e.getMessage(), e.getCause()); throw new IOException(e); } Map<String, Qualifier> rawmap = ed.getDisplayNameMap(); // rdbms may contains field which is not case insensitive, we need convert all into lower case Map<String, Qualifier> map = new HashMap<>(); for (Map.Entry<String, Qualifier> e : rawmap.entrySet()) { map.put(e.getKey().toLowerCase(), e.getValue()); } for (Map.Entry<String, Object> entry : row.entrySet()) { // timestamp; if (JdbcConstants.TIMESTAMP_COLUMN_NAME.equalsIgnoreCase(entry.getKey())) { obj.setTimestamp((Long) entry.getValue()); continue; } // set metric as prefix for generic metric if (entityDefinition.getInternal().getService().equals(GenericMetricEntity.GENERIC_METRIC_SERVICE) && JdbcConstants.METRIC_NAME_COLUMN_NAME.equalsIgnoreCase(entry.getKey())) { obj.setPrefix((String) entry.getValue()); continue; } // rowkey: uuid if (JdbcConstants.ROW_KEY_COLUMN_NAME.equalsIgnoreCase(entry.getKey())) { obj.setEncodedRowkey((String) entry.getValue()); continue; } Qualifier q = map.get(entry.getKey().toLowerCase()); if (q == null) { // if it's not pre-defined qualifier, it must be tag unless it's a bug if (obj.getTags() == null) { obj.setTags(new HashMap<String, String>()); } // get normalized tag name, not efficient, but we need make it work first String key = null; if (ed.getTags() != null) { for (String tag : ed.getTags()) { if (tag.equalsIgnoreCase(entry.getKey())) { key = tag; break; } } } try { obj.getTags().put(key == null ? entry.getKey() : key, (String) entry.getValue()); } catch (ClassCastException ex) { LOG.error("Tag value {} = {} is not String", key, entry.getValue(), ex); throw ex; } continue; } // parse different types of qualifiers String fieldName = q.getDisplayName(); // PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(obj, fieldName); PropertyDescriptor pd = null; try { pd = getPropertyDescriptor(obj, fieldName); if (entry.getValue() != null) { pd.getWriteMethod().invoke(obj, entry.getValue()); } } catch (Exception ex) { LOG.error("Failed to set value {} = {}", fieldName, entry.getValue(), ex); throw new IOException(String.format("Failed to set value %s = %s", fieldName, entry.getValue()), ex); } } if (!entityDefinition.getInternal().getService().equals(GenericMetricEntity.GENERIC_METRIC_SERVICE)) { obj.setPrefix(entityDefinition.getInternal().getPrefix()); } return (E) obj; }
From source file:org.opoo.util.ClassUtils.java
public static void setProperty(Object target, PropertyDescriptor prop, Object value) throws Exception { Method setter = prop.getWriteMethod(); if (setter == null) { return;// w w w . j ava 2s . c o m } Class[] params = setter.getParameterTypes(); // convert types for some popular ones if (value != null) { if (value instanceof java.util.Date) { if (params[0].getName().equals("java.sql.Date")) { value = new java.sql.Date(((java.util.Date) value).getTime()); } else if (params[0].getName().equals("java.sql.Time")) { value = new java.sql.Time(((java.util.Date) value).getTime()); } else if (params[0].getName().equals("java.sql.Timestamp")) { value = new java.sql.Timestamp(((java.util.Date) value).getTime()); } } } // Don't call setter if the value object isn't the right type if (isCompatibleType(value, params[0])) { setter.invoke(target, new Object[] { value }); } else { throw new Exception("Cannot set " + prop.getName() + ": incompatible types."); } }
From source file:cn.fql.utility.ClassUtility.java
/** * Import value to object according specified <code>org.xml.sax.Attributes</code> * * @param obj specified object instance * @param atts <code>org.xml.sax.Attributes</code> *//*from ww w .j av a 2 s . co m*/ public static void importValueFromAttribute(Object obj, org.xml.sax.Attributes atts) { if (atts != null) { PropertyDescriptor[] pds; try { pds = exportPropertyDesc(obj.getClass()); if (pds != null && pds.length > 0) { for (int i = 0; i < pds.length; i++) { PropertyDescriptor pd = pds[i]; String strValue = atts.getValue(pd.getName()); if (strValue != null) { Method setter = pd.getWriteMethod(); if (setter != null) { Object value = ConvertUtils.convert(strValue, pd.getPropertyType()); Object[] params = { value }; setter.invoke(obj, params); } } } } } catch (Exception e) { System.out.println(e.getMessage()); } } }
From source file:com.swingtech.commons.testing.JavaBeanTester.java
/** * Tests the get/set methods of the specified class. * /*from w ww .j a v a2 s.co m*/ * @param <T> the type parameter associated with the class under test * @param clazz the Class under test * @param skipThese the names of any properties that should not be tested * @throws IntrospectionException thrown if the Introspector.getBeanInfo() method throws this exception * for the class under test */ public static <T> void test(final Class<T> clazz, final String... skipThese) throws IntrospectionException { final PropertyDescriptor[] props = Introspector.getBeanInfo(clazz).getPropertyDescriptors(); nextProp: for (PropertyDescriptor prop : props) { // Check the list of properties that we don't want to test for (String skipThis : skipThese) { if (skipThis.equals(prop.getName())) { continue nextProp; } } final Method getter = prop.getReadMethod(); final Method setter = prop.getWriteMethod(); if (getter != null && setter != null) { // We have both a get and set method for this property final Class<?> returnType = getter.getReturnType(); final Class<?>[] params = setter.getParameterTypes(); if (params.length == 1 && params[0] == returnType) { // The set method has 1 argument, which is of the same type as the return type of the get method, so we can test this property try { // Build a value of the correct type to be passed to the set method Object value = buildValue(returnType); // Build an instance of the bean that we are testing (each property test gets a new instance) T bean = clazz.newInstance(); // Call the set method, then check the same value comes back out of the get method setter.invoke(bean, value); final Object expectedValue = value; final Object actualValue = getter.invoke(bean); assertEquals(String.format("Failed while testing property %s", prop.getName()), expectedValue, actualValue); } catch (Exception ex) { fail(String.format("An exception was thrown while testing the property %s: %s", prop.getName(), ex.toString())); } } } } }
From source file:Main.java
public static <T> T loadBean(Node node, Class<T> beanClass) throws IntrospectionException, InstantiationException, IllegalAccessException, IllegalArgumentException, DOMException, InvocationTargetException { T store = beanClass.newInstance();/*from ww w. jav a 2 s . co m*/ Map<String, PropertyDescriptor> properties = new HashMap<String, PropertyDescriptor>(); BeanInfo beanInfo = Introspector.getBeanInfo(beanClass); for (PropertyDescriptor property : beanInfo.getPropertyDescriptors()) { properties.put(property.getName(), property); } NamedNodeMap attributes = node.getAttributes(); for (int i = 0; i < attributes.getLength(); i++) { Node attribute = attributes.item(i); PropertyDescriptor property = properties.get(attribute.getNodeName()); if (property != null && property.getPropertyType().equals(String.class) && property.getWriteMethod() != null) { property.getWriteMethod().invoke(store, attribute.getNodeValue()); } } NodeList childNodes = node.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { Node child = childNodes.item(i); PropertyDescriptor property = properties.get(child.getNodeName()); if (property != null && property.getPropertyType().equals(String.class) && property.getWriteMethod() != null) { property.getWriteMethod().invoke(store, child.getTextContent()); } } return store; }
From source file:org.codehaus.groovy.grails.commons.GrailsDomainConfigurationUtil.java
/** * Checks whether is property is configurational. * * @param descriptor The descriptor//from ww w . j a v a2s .com * @return true if it is configurational */ public static boolean isNotConfigurational(PropertyDescriptor descriptor) { final String name = descriptor.getName(); Method readMethod = descriptor.getReadMethod(); Method writeMethod = descriptor.getWriteMethod(); if ((readMethod != null && Modifier.isStatic(readMethod.getModifiers()) || (writeMethod != null && Modifier.isStatic(writeMethod.getModifiers())))) { return false; } return !Errors.class.isAssignableFrom(descriptor.getPropertyType()) && isNotConfigurational(name); }
From source file:org.dozer.util.ReflectionUtils.java
/** * There are some nasty bugs for introspection with generics. This method addresses those nasty bugs and tries to find proper methods if available * http://bugs.sun.com/view_bug.do?bug_id=6788525 * http://bugs.sun.com/view_bug.do?bug_id=6528714 * @param descriptor/* w w w.j a v a 2 s. co m*/ * @return */ private static PropertyDescriptor fixGenericDescriptor(Class<?> clazz, PropertyDescriptor descriptor) { Method readMethod = descriptor.getReadMethod(); Method writeMethod = descriptor.getWriteMethod(); if (readMethod != null && (readMethod.isBridge() || readMethod.isSynthetic())) { String propertyName = descriptor.getName(); //capitalize the first letter of the string; String baseName = Character.toUpperCase(propertyName.charAt(0)) + propertyName.substring(1); String setMethodName = "set" + baseName; String getMethodName = "get" + baseName; Method[] methods = clazz.getMethods(); for (Method method : methods) { if (method.getName().equals(getMethodName) && !method.isBridge() && !method.isSynthetic()) { try { descriptor.setReadMethod(method); } catch (IntrospectionException e) { //move on } } if (method.getName().equals(setMethodName) && !method.isBridge() && !method.isSynthetic()) { try { descriptor.setWriteMethod(method); } catch (IntrospectionException e) { //move on } } } } return descriptor; }
From source file:net.zcarioca.zcommons.config.data.BeanPropertySetterFactory.java
private static Collection<Annotation> getPropertyAnnotations(Field field, PropertyDescriptor descriptor) { Map<Class<? extends Annotation>, Annotation> annotations = new HashMap<Class<? extends Annotation>, Annotation>(); if (descriptor != null) { if (descriptor.getWriteMethod() != null) { addAnnotationsToMap(annotations, descriptor.getWriteMethod().getAnnotations()); }/*from ww w.j a v a 2 s .com*/ if (descriptor.getReadMethod() != null) { addAnnotationsToMap(annotations, descriptor.getReadMethod().getAnnotations()); } } if (field != null) { addAnnotationsToMap(annotations, field.getAnnotations()); } return annotations.values(); }
From source file:com.bstek.dorado.idesupport.template.RuleTemplate.java
private static void applyProperties(Object source, Object target) throws Exception { for (PropertyDescriptor propertyDescriptor : PropertyUtils.getPropertyDescriptors(target)) { if (propertyDescriptor.getReadMethod() != null && propertyDescriptor.getWriteMethod() != null) { applyProperty(source, target, propertyDescriptor.getName()); }/*from w w w. j a v a2s . co m*/ } }
From source file:org.hellojavaer.testcase.generator.TestCaseGenerator.java
@SuppressWarnings({ "unchecked", "rawtypes" }) private static <T> T produceBean(Class<T> clazz, ControlParam countrolParam, Stack<Class> parseClassList) { try {//ww w. j a v a 2s . c om T item = clazz.newInstance(); for (PropertyDescriptor pd : BeanUtils.getPropertyDescriptors(clazz)) { Method writeMethod = pd.getWriteMethod(); if (writeMethod == null || pd.getReadMethod() == null || // countrolParam.getExcludeFieldList() != null && countrolParam.getExcludeFieldList().contains(pd.getName())// ) {// continue; } Class fieldClazz = pd.getPropertyType(); Long numIndex = countrolParam.getNumIndex(); // int enumIndex = countrolParam.getEnumIndex(); Random random = countrolParam.getRandom(); long strIndex = countrolParam.getStrIndex(); int charIndex = countrolParam.getCharIndex(); Calendar time = countrolParam.getTime(); if (TypeUtil.isBaseType(fieldClazz)) { if (TypeUtil.isNumberType(fieldClazz)) { if (fieldClazz == Byte.class) { writeMethod.invoke(item, Byte.valueOf((byte) (numIndex & 0x7F))); } else if (fieldClazz == Short.class) { writeMethod.invoke(item, Short.valueOf((short) (numIndex & 0x7FFF))); } else if (fieldClazz == Integer.class) { writeMethod.invoke(item, Integer.valueOf((int) (numIndex & 0x7FFFFFFF))); } else if (fieldClazz == Long.class) { writeMethod.invoke(item, Long.valueOf((long) numIndex)); } else if (fieldClazz == Float.class) { writeMethod.invoke(item, Float.valueOf((float) numIndex)); } else if (fieldClazz == Double.class) { writeMethod.invoke(item, Double.valueOf((double) numIndex)); } else if (fieldClazz == byte.class) {// writeMethod.invoke(item, (byte) (numIndex & 0x7F)); } else if (fieldClazz == short.class) { writeMethod.invoke(item, (short) (numIndex & 0x7FFF)); } else if (fieldClazz == int.class) { writeMethod.invoke(item, (int) (numIndex & 0x7FFFFFFF)); } else if (fieldClazz == long.class) { writeMethod.invoke(item, (long) numIndex); } else if (fieldClazz == float.class) { writeMethod.invoke(item, (float) numIndex); } else if (fieldClazz == double.class) { writeMethod.invoke(item, (double) numIndex); } numIndex++; if (numIndex < 0) { numIndex &= 0x7FFFFFFFFFFFFFFFL; } countrolParam.setNumIndex(numIndex); } else if (fieldClazz == boolean.class) { writeMethod.invoke(item, random.nextBoolean()); } else if (fieldClazz == Boolean.class) { writeMethod.invoke(item, Boolean.valueOf(random.nextBoolean())); } else if (fieldClazz == char.class) { writeMethod.invoke(item, CHAR_RANGE[charIndex]); charIndex++; if (charIndex >= CHAR_RANGE.length) { charIndex = 0; } countrolParam.setCharIndex(charIndex); } else if (fieldClazz == Character.class) { writeMethod.invoke(item, Character.valueOf(CHAR_RANGE[charIndex])); charIndex++; if (charIndex >= CHAR_RANGE.length) { charIndex = 0; } countrolParam.setCharIndex(charIndex); } else if (fieldClazz == String.class) { if (countrolParam.getUniqueFieldList() != null && countrolParam.getUniqueFieldList().contains(pd.getName())) { StringBuilder sb = new StringBuilder(); convertNum(strIndex, STRING_RANGE, countrolParam.getRandom(), sb); writeMethod.invoke(item, sb.toString()); strIndex += countrolParam.getStrStep(); if (strIndex < 0) { strIndex &= 0x7FFFFFFFFFFFFFFFL; } countrolParam.setStrIndex(strIndex); } else { writeMethod.invoke(item, String.valueOf(CHAR_RANGE[charIndex])); charIndex++; if (charIndex >= CHAR_RANGE.length) { charIndex = 0; } countrolParam.setCharIndex(charIndex); } } else if (fieldClazz == Date.class) { writeMethod.invoke(item, time.getTime()); time.add(Calendar.DAY_OF_YEAR, 1); } else if (fieldClazz.isEnum()) { int index = random.nextInt(fieldClazz.getEnumConstants().length); writeMethod.invoke(item, fieldClazz.getEnumConstants()[index]); } else { // throw new RuntimeException("out of countrol Class " + fieldClazz.getName()); } } else { parseClassList.push(fieldClazz); // TODO ? Set<Class> set = new HashSet<Class>(parseClassList); if (parseClassList.size() - set.size() <= countrolParam.getRecursiveCycleLimit()) { Object bean = produceBean(fieldClazz, countrolParam, parseClassList); writeMethod.invoke(item, bean); } parseClassList.pop(); } } return item; } catch (Exception e) { throw new RuntimeException(e); } }