List of usage examples for org.apache.commons.beanutils PropertyUtils getPropertyDescriptors
public static PropertyDescriptor[] getPropertyDescriptors(Object bean)
Retrieve the property descriptors for the specified bean, introspecting and caching them the first time a particular bean class is encountered.
For more details see PropertyUtilsBean
.
From source file:com.bstek.dorado.config.xml.XmlParserHelper.java
protected void doInitObjectParser(Context context, ObjectParser objectParser, XmlNodeInfo xmlNodeInfo, Class<?> beanType) throws Exception { objectParser.setAnnotationOwnerType(beanType); if (!Modifier.isAbstract(beanType.getModifiers())) { objectParser.setImpl(beanType.getName()); }//ww w . j av a 2s . com if (xmlNodeInfo != null) { if (StringUtils.isNotEmpty(xmlNodeInfo.getDefinitionType())) { objectParser.setDefinitionType(xmlNodeInfo.getDefinitionType()); } Map<String, XmlParser> propertyParsers = objectParser.getPropertyParsers(); Map<String, XmlParser> subParsers = objectParser.getSubParsers(); if (!(objectParser instanceof CompositePropertyParser)) { boolean inheritable = objectParser.isInheritable() || xmlNodeInfo.isInheritable(); objectParser.setInheritable(inheritable); if (inheritable) { if (propertyParsers.get("parent") == null) { objectParser.registerPropertyParser("parent", beanFactory.getBean(IGNORE_PARSER, XmlParser.class)); } } boolean scopable = objectParser.isScopable() || xmlNodeInfo.isScopable(); objectParser.setScopable(scopable); if (scopable) { if (propertyParsers.get("scope") == null) { objectParser.registerPropertyParser("scope", beanFactory.getBean(IGNORE_PARSER, XmlParser.class)); } } for (String fixedProperty : xmlNodeInfo.getFixedProperties().keySet()) { if (propertyParsers.get(fixedProperty) == null) { objectParser.registerPropertyParser(fixedProperty, beanFactory.getBean(IGNORE_PARSER, XmlParser.class)); } } } for (XmlSubNode xmlSubNode : xmlNodeInfo.getSubNodes()) { if (StringUtils.isNotEmpty(xmlSubNode.propertyType())) { List<XmlParserInfo> xmlParserInfos = getSubNodeXmlParserInfos(context, beanType, xmlSubNode.propertyName(), null, xmlSubNode); if (xmlParserInfos != null) { for (XmlParserInfo xmlParserInfo : xmlParserInfos) { objectParser.registerSubParser(xmlParserInfo.getPath(), xmlParserInfo.getParser()); } } } else if (StringUtils.isNotEmpty(xmlSubNode.nodeName()) && StringUtils.isNotEmpty(xmlSubNode.parser())) { BeanWrapper beanWrapper = BeanFactoryUtils.getBean(xmlSubNode.parser(), Scope.instant); objectParser.registerSubParser(xmlSubNode.nodeName(), (XmlParser) beanWrapper.getBean()); } } for (Map.Entry<String, XmlProperty> entry : xmlNodeInfo.getProperties().entrySet()) { XmlProperty xmlProperty = entry.getValue(); XmlParserInfo xmlParserInfo = getPropertyXmlParserInfo(context, beanType, xmlProperty.propertyName(), null, xmlProperty); if (xmlParserInfo != null) { objectParser.registerPropertyParser(xmlParserInfo.getPath(), xmlParserInfo.getParser()); } } if (ClientEventSupported.class.isAssignableFrom(beanType) && subParsers.get("ClientEvent") == null) { objectParser.registerSubParser("ClientEvent", beanFactory.getBean(CLIENT_EVENT_PARSER, XmlParser.class)); } } PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(beanType); for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { String propertyName = propertyDescriptor.getName(); if ("class".equals(propertyName)) { continue; } Method readMethod = propertyDescriptor.getReadMethod(); if (readMethod == null) { continue; } if (readMethod.getDeclaringClass() != beanType) { try { readMethod = beanType.getMethod(readMethod.getName(), readMethod.getParameterTypes()); } catch (NoSuchMethodException e) { // do nothing } } TypeInfo typeInfo; Class<?> propertyType = propertyDescriptor.getPropertyType(); if (Collection.class.isAssignableFrom(propertyType)) { typeInfo = TypeInfo.parse((ParameterizedType) readMethod.getGenericReturnType(), true); propertyType = typeInfo.getType(); } else { typeInfo = new TypeInfo(propertyType, false); } XmlSubNode xmlSubNode = readMethod.getAnnotation(XmlSubNode.class); if (xmlSubNode != null) { if (StringUtils.isNotEmpty(xmlSubNode.propertyName())) { throw new IllegalArgumentException("@XmlSubNode.propertyName should be empty. [" + beanType.getName() + '#' + propertyName + "]"); } List<XmlParserInfo> xmlParserInfos = getSubNodeXmlParserInfos(context, beanType, propertyName, typeInfo, xmlSubNode); if (xmlParserInfos != null) { for (XmlParserInfo xmlParserInfo : xmlParserInfos) { objectParser.registerSubParser(xmlParserInfo.getPath(), xmlParserInfo.getParser()); } } } else { XmlProperty xmlProperty = readMethod.getAnnotation(XmlProperty.class); if (xmlProperty != null && StringUtils.isNotEmpty(xmlProperty.propertyName())) { throw new IllegalArgumentException("@XmlProperty.propertyName should be empty. [" + beanType.getName() + '#' + propertyName + "]"); } XmlParserInfo xmlParserInfo = getPropertyXmlParserInfo(context, beanType, propertyName, typeInfo, xmlProperty); if (xmlParserInfo != null) { XmlParser parser = xmlParserInfo.getParser(); if (parser instanceof TextPropertyParser) { TextPropertyParser textPropertyParser = (TextPropertyParser) parser; if (textPropertyParser.getTextParser() == null) { TextParser textParser = textParserHelper.getTextParser(propertyType); textPropertyParser.setTextParser(textParser); } } objectParser.registerPropertyParser(xmlParserInfo.getPath(), parser); } } } if (objectParser instanceof ObjectParserInitializationAware) { ((ObjectParserInitializationAware) objectParser).postObjectParserInitialized(objectParser); } Map<String, XmlParserHelperListener> listenerMap = ((ListableBeanFactory) beanFactory) .getBeansOfType(XmlParserHelperListener.class); for (XmlParserHelperListener listener : listenerMap.values()) { listener.onInitParser(this, objectParser, beanType); } }
From source file:com.bstek.dorado.idesupport.initializer.CommonRuleTemplateInitializer.java
protected List<AutoChildTemplate> getChildTemplates(RuleTemplate ruleTemplate, TypeInfo typeInfo, XmlNodeInfo xmlNodeInfo, InitializerContext initializerContext) throws Exception { List<AutoChildTemplate> childTemplates = new ArrayList<AutoChildTemplate>(); if (xmlNodeInfo != null) { for (XmlSubNode xmlSubNode : xmlNodeInfo.getSubNodes()) { TypeInfo propertyTypeInfo = TypeInfo.parse(xmlSubNode.propertyType()); List<AutoChildTemplate> childRulesBySubNode = getChildTemplatesBySubNode(ruleTemplate, typeInfo, xmlSubNode.propertyName(), xmlSubNode, propertyTypeInfo, initializerContext); if (childRulesBySubNode != null) { childTemplates.addAll(childRulesBySubNode); }/*from w ww. j a v a2 s .co m*/ } } Class<?> type = typeInfo.getType(); PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(type); for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { Method readMethod = propertyDescriptor.getReadMethod(); if (readMethod != null) { if (readMethod.getDeclaringClass() != type) { try { readMethod = type.getDeclaredMethod(readMethod.getName(), readMethod.getParameterTypes()); } catch (NoSuchMethodException e) { continue; } } List<AutoChildTemplate> childTemplatesBySubNode = null; XmlSubNode xmlSubNode = readMethod.getAnnotation(XmlSubNode.class); if (xmlSubNode != null) { TypeInfo propertyTypeInfo; Class<?> propertyType = propertyDescriptor.getPropertyType(); if (Collection.class.isAssignableFrom(propertyType)) { propertyTypeInfo = TypeInfo.parse((ParameterizedType) readMethod.getGenericReturnType(), true); propertyType = propertyTypeInfo.getType(); } else { propertyTypeInfo = new TypeInfo(propertyType, false); } childTemplatesBySubNode = getChildTemplatesBySubNode(ruleTemplate, typeInfo, propertyDescriptor.getName(), xmlSubNode, propertyTypeInfo, initializerContext); } if (childTemplatesBySubNode != null) { IdeSubObject ideSubObject = readMethod.getAnnotation(IdeSubObject.class); if (ideSubObject != null && !ideSubObject.visible()) { for (AutoChildTemplate childTemplate : childTemplatesBySubNode) { childTemplate.setVisible(false); } } childTemplates.addAll(childTemplatesBySubNode); } } } return childTemplates; }
From source file:ca.sqlpower.wabit.AbstractWabitObjectTest.java
/** * Reflective test that the wabit object can be persisted as an object and all of * its properties are persisted with it. *//* w ww. j a v a2 s.c o m*/ public void testPersistsObjectAsChild() throws Exception { //This may need to actually have the wabit object as a child to itself. WabitObject parent = new StubWabitObject(); CountingWabitPersister persister = new CountingWabitPersister(); WorkspacePersisterListener listener = new WorkspacePersisterListener( new StubWabitSession(new StubWabitSessionContext()), persister, true); SPObject wo = getObjectUnderTest(); if (wo.getParent() == null) { wo.setParent(parent); } listener.childAdded(new SPChildEvent(parent, wo.getClass(), wo, 0, EventType.ADDED)); assertTrue(persister.getPersistObjectCount() > 0); PersistedSPObject persistedWabitObject = persister.getAllPersistedObjects().get(0); assertEquals(wo.getClass().getSimpleName(), persistedWabitObject.getType()); assertEquals(wo.getUUID(), persistedWabitObject.getUUID()); //confirm we get one persist property for each getter/setter pair //confirm we get one persist property for each value in one of the constructors in the object. List<PropertyDescriptor> settableProperties = new ArrayList<PropertyDescriptor>( Arrays.asList(PropertyUtils.getPropertyDescriptors(wo.getClass()))); List<PersistedSPOProperty> allPropertyChanges = persister.getAllPropertyChanges(); Set<String> ignorableProperties = getPropertiesToNotPersistOnObjectPersist(); ignorableProperties.addAll(getPropertiesToIgnoreForEvents()); List<PersistedSPOProperty> changesOnObject = new ArrayList<PersistedSPOProperty>(); logger.debug("Looking through properties registered to persist..."); for (int i = allPropertyChanges.size() - 1; i >= 0; i--) { if (allPropertyChanges.get(i).getUUID().equals(wo.getUUID())) { changesOnObject.add(allPropertyChanges.get(i)); logger.debug( "The property " + allPropertyChanges.get(i).getPropertyName() + " is ready to persist!"); } else { logger.debug("The property " + allPropertyChanges.get(i).getPropertyName() + " has not been set in WabitSessionPersister and" + " WorkspacePersisterListener to persist properly!"); } } List<String> settablePropertyNames = new ArrayList<String>(); for (PropertyDescriptor pd : settableProperties) { settablePropertyNames.add(pd.getName()); } settablePropertyNames.removeAll(ignorableProperties); if (settablePropertyNames.size() != changesOnObject.size()) { for (String descriptor : settablePropertyNames) { PersistedSPOProperty foundChange = null; for (PersistedSPOProperty propertyChange : changesOnObject) { if (propertyChange.getPropertyName().equals(descriptor)) { foundChange = propertyChange; break; } } assertNotNull("The property " + descriptor + " was not persisted", foundChange); } } logger.debug("Property names" + settablePropertyNames); assertTrue(settablePropertyNames.size() <= changesOnObject.size()); WabitSessionPersisterSuperConverter factory = new WabitSessionPersisterSuperConverter( new StubWabitSession(new StubWabitSessionContext()), new WabitWorkspace(), true); for (String descriptor : settablePropertyNames) { PersistedSPOProperty foundChange = null; for (PersistedSPOProperty propertyChange : changesOnObject) { if (propertyChange.getPropertyName().equals(descriptor)) { foundChange = propertyChange; break; } } assertNotNull("The property " + descriptor + " was not persisted", foundChange); assertTrue(foundChange.isUnconditional()); assertEquals(wo.getUUID(), foundChange.getUUID()); Object value = PropertyUtils.getSimpleProperty(wo, descriptor); //XXX will replace this later List<Object> additionalVals = new ArrayList<Object>(); if (wo instanceof OlapQuery && descriptor.equals("currentCube")) { additionalVals.add(((OlapQuery) wo).getOlapDataSource()); } Object valueConvertedToBasic = factory.convertToBasicType(value, additionalVals.toArray()); logger.debug("Property \"" + descriptor + "\": expected \"" + valueConvertedToBasic + "\" but was \"" + foundChange.getNewValue() + "\" of type " + foundChange.getDataType()); assertEquals(valueConvertedToBasic, foundChange.getNewValue()); } }
From source file:catalina.core.StandardServer.java
/** * Store the relevant attributes of the specified JavaBean. * * @param writer PrintWriter to which we are storing * @param include Should we include a <code>className</code> attribute? * @param bean Bean whose properties are to be rendered as attributes, * * @exception Exception if an exception occurs while storing *///from w ww. j a v a 2 s . c om private void storeAttributes(PrintWriter writer, boolean include, Object bean) throws Exception { // Render a className attribute if requested if (include) { writer.print(" className=\""); writer.print(bean.getClass().getName()); writer.print("\""); } // Acquire the list of properties for this bean PropertyDescriptor descriptors[] = PropertyUtils.getPropertyDescriptors(bean); if (descriptors == null) { descriptors = new PropertyDescriptor[0]; } // Render the relevant properties of this bean String className = bean.getClass().getName(); for (int i = 0; i < descriptors.length; i++) { if (descriptors[i] instanceof IndexedPropertyDescriptor) { continue; // Indexed properties are not persisted } if (!isPersistable(descriptors[i].getPropertyType()) || (descriptors[i].getReadMethod() == null) || (descriptors[i].getWriteMethod() == null)) { continue; // Must be a read-write primitive or String } Object value = PropertyUtils.getSimpleProperty(bean, descriptors[i].getName()); if (value == null) { continue; // Null values are not persisted } if (isException(className, descriptors[i].getName())) { continue; // Skip the specified exceptions } if (!(value instanceof String)) { value = value.toString(); } writer.print(' '); writer.print(descriptors[i].getName()); writer.print("=\""); String strValue = convertStr((String) value); writer.print(strValue); writer.print("\""); } }
From source file:ca.sqlpower.object.PersistedSPObjectTest.java
/** * This test will make changes to the {@link SPObject} under test and then * cause an exception forcing the persister to roll back the changes in the * object.//w ww .ja va 2 s. co m * <p> * Both the changes have to come through the persister initially before the * exception and they have to be reset after the exception. */ public void testSessionPersisterRollsBackProperties() throws Exception { SPObject objectUnderTest = getSPObjectUnderTest(); final Map<PropertyDescriptor, Object> initialProperties = new HashMap<PropertyDescriptor, Object>(); final Map<PropertyDescriptor, Object> newProperties = new HashMap<PropertyDescriptor, Object>(); List<PropertyDescriptor> settableProperties = Arrays .asList(PropertyUtils.getPropertyDescriptors(objectUnderTest.getClass())); Set<String> propertiesToPersist = findPersistableBeanProperties(false, false); Set<String> ignorePropertySet = getRollbackTestIgnorePropertySet(); NewValueMaker valueMaker = createNewValueMaker(getRootObject(), getPLIni()); SPSessionPersister persister = new TestingSessionPersister("tester", getRootObject(), getConverter()); persister.setWorkspaceContainer(getRootObject().getWorkspaceContainer()); failureReason = null; SPPersisterListener listener = new SPPersisterListener(new CountingSPPersister(), converter) { private boolean transactionAlreadyFinished = false; @Override public void transactionEnded(TransactionEvent e) { if (transactionAlreadyFinished) return; transactionAlreadyFinished = true; try { for (Map.Entry<PropertyDescriptor, Object> newProperty : newProperties.entrySet()) { Object objectUnderTest = getSPObjectUnderTest(); Object newVal = newProperty.getValue(); Object basicNewValue = converter.convertToBasicType(newVal); Object newValAfterSet = PropertyUtils.getSimpleProperty(objectUnderTest, newProperty.getKey().getName()); Object basicExpectedValue = converter.convertToBasicType(newValAfterSet); logger.debug("Testing property " + newProperty.getKey().getName()); assertPersistedValuesAreEqual(newVal, newValAfterSet, basicNewValue, basicExpectedValue, newProperty.getKey().getPropertyType()); } } catch (Throwable ex) { failureReason = ex; throw new RuntimeException(ex); } throw new RuntimeException("Forcing rollback."); } }; //Transactions begin and commits are currently sent on the workspace. getRootObject().getParent().addSPListener(listener); persister.begin(); for (PropertyDescriptor property : settableProperties) { Object oldVal; //Changing the UUID of the object makes it referenced as a different object //and would make the check later in this test fail. if (property.getName().equals("UUID")) continue; if (!propertiesToPersist.contains(property.getName())) continue; if (ignorePropertySet.contains(property.getName())) continue; try { oldVal = PropertyUtils.getSimpleProperty(objectUnderTest, property.getName()); // check for a setter if (property.getWriteMethod() == null) continue; } catch (NoSuchMethodException e) { logger.debug("Skipping non-settable property " + property.getName() + " on " + objectUnderTest.getClass().getName()); continue; } initialProperties.put(property, oldVal); //special case for parent types. If a specific wabit object has a tighter parent then //WabitObject the getParentClass should return the parent type. Class<?> propertyType = property.getPropertyType(); if (property.getName().equals("parent")) { propertyType = getSPObjectUnderTest().getClass().getMethod("getParent").getReturnType(); logger.debug("Persisting parent, type is " + propertyType); } Object newVal = valueMaker.makeNewValue(propertyType, oldVal, property.getName()); DataType type = PersisterUtils.getDataType(property.getPropertyType()); Object basicNewValue = converter.convertToBasicType(newVal); persister.begin(); persister.persistProperty(objectUnderTest.getUUID(), property.getName(), type, converter.convertToBasicType(oldVal), basicNewValue); persister.commit(); newProperties.put(property, newVal); } try { persister.commit(); fail("An exception should make the persister hit the exception block."); } catch (Exception e) { //continue, exception expected. } if (failureReason != null) { throw new RuntimeException("Failed when asserting properties were " + "fully persisted.", failureReason); } for (Map.Entry<PropertyDescriptor, Object> entry : initialProperties.entrySet()) { assertEquals("Property " + entry.getKey().getName() + " did not match after rollback.", entry.getValue(), PropertyUtils.getSimpleProperty(objectUnderTest, entry.getKey().getName())); } }
From source file:ca.sqlpower.wabit.AbstractWabitObjectTest.java
/** * This test will set all of the properties in a WabitObject in one transaction then * after committing the next persister after it will throw an exception causing the * persister to undo all of the changes it just made. *//*from w w w .j av a2 s. c om*/ public void testPersisterCommitCanRollbackProperties() throws Exception { SPObject wo = getObjectUnderTest(); WabitSessionPersister persister = new WabitSessionPersister("test persister", session, getWorkspace(), true); CountingWabitListener countingListener = new CountingWabitListener(); ErrorWabitPersister errorPersister = new ErrorWabitPersister(); WorkspacePersisterListener listener = new WorkspacePersisterListener(session, errorPersister, true); SQLPowerUtils.listenToHierarchy(getWorkspace(), listener); wo.addSPListener(countingListener); List<PropertyDescriptor> settableProperties; settableProperties = Arrays.asList(PropertyUtils.getPropertyDescriptors(wo.getClass())); Set<String> propertiesToIgnore = new HashSet<String>(getPropertiesToIgnoreForEvents()); propertiesToIgnore.addAll(getPropertiesToIgnoreForPersisting()); //Track old and new property values to test they are set properly Map<String, Object> propertyNameToOldVal = new HashMap<String, Object>(); //Set all of the properties of the object under test in one transaction. persister.begin(); int propertyChangeCount = 0; for (PropertyDescriptor property : settableProperties) { Object oldVal; if (propertiesToIgnore.contains(property.getName())) continue; try { oldVal = PropertyUtils.getSimpleProperty(wo, property.getName()); // check for a setter if (property.getWriteMethod() == null) continue; } catch (NoSuchMethodException e) { logger.debug( "Skipping non-settable property " + property.getName() + " on " + wo.getClass().getName()); continue; } propertyNameToOldVal.put(property.getName(), oldVal); //special case for parent types. If a specific wabit object has a tighter parent then //WabitObject the getParentClass should return the parent type. Class<?> propertyType = property.getPropertyType(); if (property.getName().equals("parent")) { propertyType = getParentClass(); } Object newVal = valueMaker.makeNewValue(propertyType, oldVal, property.getName()); logger.debug("Persisting property \"" + property.getName() + "\" from oldVal \"" + oldVal + "\" to newVal \"" + newVal + "\""); //XXX will replace this later List<Object> additionalVals = new ArrayList<Object>(); if (wo instanceof OlapQuery && property.getName().equals("currentCube")) { additionalVals.add(((OlapQuery) wo).getOlapDataSource()); } DataType type = PersisterUtils.getDataType(property.getPropertyType()); Object basicNewValue = converterFactory.convertToBasicType(newVal, additionalVals.toArray()); persister.persistProperty(wo.getUUID(), property.getName(), type, converterFactory.convertToBasicType(oldVal, additionalVals.toArray()), basicNewValue); propertyChangeCount++; } //Commit the transaction causing the rollback to occur errorPersister.setThrowError(true); try { persister.commit(); fail("The commit method should have an error sent to it and it should rethrow the exception."); } catch (SPPersistenceException t) { //continue } for (PropertyDescriptor property : settableProperties) { Object currentVal; if (propertiesToIgnore.contains(property.getName())) continue; try { currentVal = PropertyUtils.getSimpleProperty(wo, property.getName()); // check for a setter if (property.getWriteMethod() == null) continue; } catch (NoSuchMethodException e) { logger.debug( "Skipping non-settable property " + property.getName() + " on " + wo.getClass().getName()); continue; } Object oldVal = propertyNameToOldVal.get(property.getName()); //XXX will replace this later List<Object> additionalVals = new ArrayList<Object>(); if (wo instanceof OlapQuery && property.getName().equals("currentCube")) { additionalVals.add(((OlapQuery) wo).getOlapDataSource()); } logger.debug("Checking property " + property.getName() + " was set to " + oldVal + ", actual value is " + currentVal); assertEquals(converterFactory.convertToBasicType(oldVal, additionalVals.toArray()), converterFactory.convertToBasicType(currentVal, additionalVals.toArray())); } logger.debug("Received " + countingListener.getPropertyChangeCount() + " change events."); assertTrue(propertyChangeCount * 2 <= countingListener.getPropertyChangeCount()); }
From source file:com.xwtec.xwserver.util.json.JSONObject.java
/** * Creates a JSONObject from a POJO.<br> * Supports nested maps, POJOs, and arrays/collections. * * @param bean An object with POJO conventions * @throws JSONException if the bean can not be converted to a proper * JSONObject./* w ww .ja va 2 s .com*/ */ private static JSONObject _fromBean(Object bean, JsonConfig jsonConfig) { if (!addInstance(bean)) { try { return jsonConfig.getCycleDetectionStrategy().handleRepeatedReferenceAsObject(bean); } catch (JSONException jsone) { removeInstance(bean); fireErrorEvent(jsone, jsonConfig); throw jsone; } catch (RuntimeException e) { removeInstance(bean); JSONException jsone = new JSONException(e); fireErrorEvent(jsone, jsonConfig); throw jsone; } } fireObjectStartEvent(jsonConfig); JsonBeanProcessor processor = jsonConfig.findJsonBeanProcessor(bean.getClass()); if (processor != null) { JSONObject json = null; try { json = processor.processBean(bean, jsonConfig); if (json == null) { json = (JSONObject) jsonConfig.findDefaultValueProcessor(bean.getClass()) .getDefaultValue(bean.getClass()); if (json == null) { json = new JSONObject(true); } } removeInstance(bean); fireObjectEndEvent(jsonConfig); } catch (JSONException jsone) { removeInstance(bean); fireErrorEvent(jsone, jsonConfig); throw jsone; } catch (RuntimeException e) { removeInstance(bean); JSONException jsone = new JSONException(e); fireErrorEvent(jsone, jsonConfig); throw jsone; } return json; } Class beanClass = bean.getClass(); PropertyNameProcessor propertyNameProcessor = jsonConfig.findJsonPropertyNameProcessor(beanClass); Collection exclusions = jsonConfig.getMergedExcludes(beanClass); JSONObject jsonObject = new JSONObject(); try { PropertyDescriptor[] pds = PropertyUtils.getPropertyDescriptors(bean); PropertyFilter jsonPropertyFilter = jsonConfig.getJsonPropertyFilter(); for (int i = 0; i < pds.length; i++) { boolean bypass = false; String key = pds[i].getName(); if (exclusions.contains(key)) { continue; } if (jsonConfig.isIgnoreTransientFields() && isTransientField(key, beanClass)) { continue; } Class type = pds[i].getPropertyType(); try { pds[i].getReadMethod(); } catch (Exception e) { // bug 2565295 String warning = "Property '" + key + "' of " + beanClass + " has no read method. SKIPPED"; fireWarnEvent(warning, jsonConfig); log.info(warning); continue; } if (pds[i].getReadMethod() != null) { Object value = PropertyUtils.getProperty(bean, key); if (jsonPropertyFilter != null && jsonPropertyFilter.apply(bean, key, value)) { continue; } JsonValueProcessor jsonValueProcessor = jsonConfig.findJsonValueProcessor(beanClass, type, key); if (jsonValueProcessor != null) { value = jsonValueProcessor.processObjectValue(key, value, jsonConfig); bypass = true; if (!JsonVerifier.isValidJsonValue(value)) { throw new JSONException("Value is not a valid JSON value. " + value); } } if (propertyNameProcessor != null) { key = propertyNameProcessor.processPropertyName(beanClass, key); } setValue(jsonObject, key, value, type, jsonConfig, bypass); } else { String warning = "Property '" + key + "' of " + beanClass + " has no read method. SKIPPED"; fireWarnEvent(warning, jsonConfig); log.info(warning); } } // inspect public fields, this operation may fail under // a SecurityManager so we will eat all exceptions try { if (!jsonConfig.isIgnorePublicFields()) { Field[] fields = beanClass.getFields(); for (int i = 0; i < fields.length; i++) { boolean bypass = false; Field field = fields[i]; String key = field.getName(); if (exclusions.contains(key)) { continue; } if (jsonConfig.isIgnoreTransientFields() && isTransientField(field)) { continue; } Class type = field.getType(); Object value = field.get(bean); if (jsonPropertyFilter != null && jsonPropertyFilter.apply(bean, key, value)) { continue; } JsonValueProcessor jsonValueProcessor = jsonConfig.findJsonValueProcessor(beanClass, type, key); if (jsonValueProcessor != null) { value = jsonValueProcessor.processObjectValue(key, value, jsonConfig); bypass = true; if (!JsonVerifier.isValidJsonValue(value)) { throw new JSONException("Value is not a valid JSON value. " + value); } } if (propertyNameProcessor != null) { key = propertyNameProcessor.processPropertyName(beanClass, key); } setValue(jsonObject, key, value, type, jsonConfig, bypass); } } } catch (Exception e) { log.trace("Couldn't read public fields.", e); } } catch (JSONException jsone) { removeInstance(bean); fireErrorEvent(jsone, jsonConfig); throw jsone; } catch (Exception e) { removeInstance(bean); JSONException jsone = new JSONException(e); fireErrorEvent(jsone, jsonConfig); throw jsone; } removeInstance(bean); fireObjectEndEvent(jsonConfig); return jsonObject; }
From source file:net.sf.json.JSONObject.java
private static JSONObject defaultBeanProcessing(Object bean, JsonConfig jsonConfig) { Class beanClass = bean.getClass(); PropertyNameProcessor propertyNameProcessor = jsonConfig.findJsonPropertyNameProcessor(beanClass); Collection exclusions = jsonConfig.getMergedExcludes(beanClass); JSONObject jsonObject = new JSONObject(); try {/*w ww.j a v a 2s .c o m*/ PropertyDescriptor[] pds = PropertyUtils.getPropertyDescriptors(bean); PropertyFilter jsonPropertyFilter = jsonConfig.getJsonPropertyFilter(); for (int i = 0; i < pds.length; i++) { boolean bypass = false; String key = pds[i].getName(); if (exclusions.contains(key)) { continue; } if (jsonConfig.isIgnoreTransientFields() && isTransientField(key, beanClass, jsonConfig)) { continue; } Class type = pds[i].getPropertyType(); try { pds[i].getReadMethod(); } catch (Exception e) { // bug 2565295 String warning = "Property '" + key + "' of " + beanClass + " has no read method. SKIPPED"; fireWarnEvent(warning, jsonConfig); log.info(warning); continue; } if (pds[i].getReadMethod() != null) { /* if( jsonConfig.isIgnoreJPATransient() ){ try{ Class transientClass = Class.forName( "javax.persistence.Transient" ); if( pds[i].getReadMethod() .getAnnotation( transientClass ) != null ){ continue; } }catch( ClassNotFoundException cnfe ){ // ignore } } */ if (isTransient(pds[i].getReadMethod(), jsonConfig)) continue; Object value = PropertyUtils.getProperty(bean, key); if (jsonPropertyFilter != null && jsonPropertyFilter.apply(bean, key, value)) { continue; } JsonValueProcessor jsonValueProcessor = jsonConfig.findJsonValueProcessor(beanClass, type, key); if (jsonValueProcessor != null) { value = jsonValueProcessor.processObjectValue(key, value, jsonConfig); bypass = true; if (!JsonVerifier.isValidJsonValue(value)) { throw new JSONException("Value is not a valid JSON value. " + value); } } if (propertyNameProcessor != null) { key = propertyNameProcessor.processPropertyName(beanClass, key); } setValue(jsonObject, key, value, type, jsonConfig, bypass); } else { String warning = "Property '" + key + "' of " + beanClass + " has no read method. SKIPPED"; fireWarnEvent(warning, jsonConfig); log.info(warning); } } // inspect public fields, this operation may fail under // a SecurityManager so we will eat all exceptions try { if (!jsonConfig.isIgnorePublicFields()) { Field[] fields = beanClass.getFields(); for (int i = 0; i < fields.length; i++) { boolean bypass = false; Field field = fields[i]; String key = field.getName(); if (exclusions.contains(key)) { continue; } if (jsonConfig.isIgnoreTransientFields() && isTransient(field, jsonConfig)) { continue; } Class type = field.getType(); Object value = field.get(bean); if (jsonPropertyFilter != null && jsonPropertyFilter.apply(bean, key, value)) { continue; } JsonValueProcessor jsonValueProcessor = jsonConfig.findJsonValueProcessor(beanClass, type, key); if (jsonValueProcessor != null) { value = jsonValueProcessor.processObjectValue(key, value, jsonConfig); bypass = true; if (!JsonVerifier.isValidJsonValue(value)) { throw new JSONException("Value is not a valid JSON value. " + value); } } if (propertyNameProcessor != null) { key = propertyNameProcessor.processPropertyName(beanClass, key); } setValue(jsonObject, key, value, type, jsonConfig, bypass); } } } catch (Exception e) { log.trace("Couldn't read public fields.", e); } } catch (JSONException jsone) { removeInstance(bean); fireErrorEvent(jsone, jsonConfig); throw jsone; } catch (Exception e) { removeInstance(bean); JSONException jsone = new JSONException(e); fireErrorEvent(jsone, jsonConfig); throw jsone; } return jsonObject; }
From source file:com.krawler.workflow.module.dao.ModuleBuilderDaoImpl.java
public String getModuleRecords(Object moduleObj, DateFormat formatter) throws ServiceException { List objectList;//from w w w . j a v a2 s .co m if (moduleObj instanceof String) objectList = dataObjectOperationObj.getAllDataObjects((String) moduleObj, formatter); else objectList = dataObjectOperationObj.getAllDataObjects(moduleObj.getClass().getSimpleName(), moduleObj.getClass()); PropertyDescriptor[] pdesc = PropertyUtils.getPropertyDescriptors(moduleObj); JSONObject dataObj = new JSONObject(); try { dataObj.put("data", new JSONArray()); for (Object modObj : objectList) { JSONObject jobj; if (moduleObj instanceof String) jobj = new JSONObject((Map) modObj); else jobj = new JSONObject(modObj); dataObj.append("data", jobj); } } catch (JSONException ex) { logger.warn(ex.getMessage(), ex); } return dataObj.toString(); }
From source file:net.sourceforge.pmd.util.fxdesigner.util.beans.RestorePropertyVisitor.java
@Override public void visit(SimpleBeanModelNode model, SettingsOwner target) { if (model == null) { return; // possibly it wasn't saved during the previous save cycle }//from w w w . j av a 2s . co m if (target == null) { throw new IllegalArgumentException(); } if (target.getClass() != model.getNodeType()) { throw new IllegalArgumentException("Incorrect settings restoration target, expected " + model.getNodeType() + ", actual " + target.getClass()); } Map<String, PropertyDescriptor> descriptors = Arrays.stream(PropertyUtils.getPropertyDescriptors(target)) .filter(d -> d.getReadMethod() != null && d.getReadMethod().isAnnotationPresent(PersistentProperty.class)) .collect(Collectors.toMap(PropertyDescriptor::getName, d -> d)); for (Entry<String, Object> saved : model.getSettingsValues().entrySet()) { if (descriptors.containsKey(saved.getKey())) { try { PropertyUtils.setProperty(target, saved.getKey(), saved.getValue()); } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } } } for (BeanModelNodeSeq<?> seq : model.getSequenceProperties()) { this.visit(seq, target); } for (SettingsOwner child : target.getChildrenSettingsNodes()) { model.getChildrenByType().get(child.getClass()).accept(this, child); } }