use of java.beans.PropertyDescriptor in project JMRI by JMRI.
the class DefaultJavaBeanConfigXML method store.
@Override
public Element store(Object o) {
Element e = new Element("javabean");
e.setAttribute("class", this.getClass().getName());
e.setAttribute("beanClass", o.getClass().getName());
try {
// reflect through and add parameters
BeanInfo b = Introspector.getBeanInfo(o.getClass());
PropertyDescriptor[] properties = b.getPropertyDescriptors();
for (int i = 0; i < properties.length; i++) {
if (properties[i].getName().equals("class")) {
// we skip this one
continue;
}
if (properties[i].getPropertyType() == null) {
log.warn("skipping property with null type: " + properties[i].getName());
continue;
}
Element p = new Element("property");
Element n = new Element("name");
n.addContent(properties[i].getName());
n.setAttribute("type", properties[i].getPropertyType().toString());
p.addContent(n);
Element v = new Element("value");
if (properties[i].getReadMethod() != null) {
Object value = properties[i].getReadMethod().invoke(o, (Object[]) null);
if (value != null) {
v.addContent(value.toString());
}
}
p.addContent(v);
e.addContent(p);
}
} catch (java.beans.IntrospectionException ex) {
log.error("Partial store due to IntrospectionException: " + ex);
} catch (java.lang.reflect.InvocationTargetException ex) {
log.error("Partial store due to InvocationTargetException: " + ex);
} catch (IllegalAccessException ex) {
log.error("Partial store due to IllegalAccessException: " + ex);
}
return e;
}
use of java.beans.PropertyDescriptor in project Gargoyle by callakrsos.
the class PivotTableViewExam method toMap.
/**
* 빈을 Map으로 변환한다. 기본형 데이터만 Map으로 변환한다.
*
* @작성자 : KYJ
* @작성일 : 2016. 2. 12.
* @param t
* @param isNullBinding
* 값이 빈경우 map에 바인딩할지 유무를 지정.
* @return
* @throws Exception
*/
public static <T> Map<String, Object> toMap(final T t, boolean isNullBinding) {
Map<String, Object> hashMap = new HashMap<String, Object>();
try {
BeanInfo beanInfo = Introspector.getBeanInfo(t.getClass());
// Iterate over all the attributes
for (PropertyDescriptor descriptor : beanInfo.getPropertyDescriptors()) {
// write메소드와 read메소드가 존재할때만.
Method writeMethod = descriptor.getWriteMethod();
Method readMethod = descriptor.getReadMethod();
if (ValueUtil.isEmpty(writeMethod) || ValueUtil.isEmpty(readMethod)) {
continue;
}
// Class<?> returnType = readMethod.getReturnType();
String methodName = ValueUtil.getSimpleMethodName(readMethod.getName());
Object originalValue = readMethod.invoke(t);
// SET문등 수행시 타입 오류 발생
if (ValueUtil.isNotEmpty(originalValue)) {
hashMap.put(methodName, originalValue);
} else {
if (isNullBinding)
hashMap.put(methodName, null);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return hashMap;
}
use of java.beans.PropertyDescriptor in project jdk8u_jdk by JetBrains.
the class Test4682386 method testSwingProperties.
/**
* Should be exectuted with $JAVA_HOME/lib/dt.jar in the classpath
* so that there will be a lot more bound properties.
* <p/>
* This test isn't really appropriate for automated testing.
*/
private static void testSwingProperties() {
long start = System.currentTimeMillis();
for (Class type : TYPES) {
try {
Object bean = Beans.instantiate(type.getClassLoader(), type.getName());
JComponent comp = (JComponent) bean;
for (int k = 0; k < NUM_LISTENERS; k++) {
comp.addPropertyChangeListener(new PropertyListener());
}
for (PropertyDescriptor pd : getPropertyDescriptors(type)) {
if (pd.isBound()) {
if (DEBUG) {
System.out.println("Bound property found: " + pd.getName());
}
Method read = pd.getReadMethod();
Method write = pd.getWriteMethod();
try {
write.invoke(bean, getValue(pd.getPropertyType(), read.invoke(bean)));
} catch (Exception ex) {
// do nothing - just move on.
if (DEBUG) {
System.out.println("Reflective method invocation Exception for " + type + " : " + ex.getMessage());
}
}
}
}
} catch (Exception ex) {
// do nothing - just move on.
if (DEBUG) {
System.out.println("Exception for " + type.getName() + " : " + ex.getMessage());
}
}
}
System.out.println("Exec time (ms): " + (System.currentTimeMillis() - start));
}
use of java.beans.PropertyDescriptor in project jdk8u_jdk by JetBrains.
the class BeanValidator method validate.
public void validate(Object object1, Object object2) {
// compare references
if (object1 == object2) {
return;
}
// check for null
if ((object1 == null) || (object2 == null)) {
throw new IllegalStateException("could not compare object with null");
}
// resolve self references
if (isCyclic(object1, object2)) {
return;
}
// resolve cross references
if (isCyclic(object2, object1)) {
return;
}
Class type = object1.getClass();
if (!type.equals(object2.getClass())) {
// resolve different implementations of the Map.Entry interface
if ((object1 instanceof Map.Entry) && (object2 instanceof Map.Entry)) {
log("!!! special case", "Map.Entry");
Map.Entry entry1 = (Map.Entry) object1;
Map.Entry entry2 = (Map.Entry) object2;
validate(entry1.getKey(), entry2.getKey());
validate(entry1.getValue(), entry2.getValue());
return;
}
throw new IllegalStateException("could not compare objects with different types");
}
// validate elements of arrays
if (type.isArray()) {
int length = Array.getLength(object1);
if (length != Array.getLength(object2)) {
throw new IllegalStateException("could not compare arrays with different lengths");
}
try {
this.cache.put(object1, object2);
for (int i = 0; i < length; i++) {
log("validate array element", Integer.valueOf(i));
validate(Array.get(object1, i), Array.get(object2, i));
}
} finally {
this.cache.remove(object1);
}
return;
}
// special case for collections: do not use equals
boolean ignore = Collection.class.isAssignableFrom(type) || Map.Entry.class.isAssignableFrom(type) || Map.class.isAssignableFrom(type);
// if the class declares such method
if (!ignore && isDefined(type, "equals", Object.class)) {
if (object1.equals(object2)) {
return;
}
throw new IllegalStateException("the first object is not equal to the second one");
}
// if the class declares such method and implements interface Comparable
if (Comparable.class.isAssignableFrom(type) && isDefined(type, "compareTo", Object.class)) {
Comparable cmp = (Comparable) object1;
if (0 == cmp.compareTo(object2)) {
return;
}
throw new IllegalStateException("the first comparable object is not equal to the second one");
}
try {
this.cache.put(object1, object2);
// validate values of public fields
for (Field field : getFields(type)) {
int mod = field.getModifiers();
if (!Modifier.isStatic(mod)) {
log("validate field", field.getName());
validate(object1, object2, field);
}
}
// validate values of properties
for (PropertyDescriptor pd : getDescriptors(type)) {
Method method = pd.getReadMethod();
if (method != null) {
log("validate property", pd.getName());
validate(object1, object2, method);
}
}
// validate contents of maps
if (SortedMap.class.isAssignableFrom(type)) {
validate((Map) object1, (Map) object2, true);
} else if (Map.class.isAssignableFrom(type)) {
validate((Map) object1, (Map) object2, false);
}
// validate contents of collections
if (SortedSet.class.isAssignableFrom(type)) {
validate((Collection) object1, (Collection) object2, true);
} else if (List.class.isAssignableFrom(type)) {
validate((Collection) object1, (Collection) object2, true);
} else if (Queue.class.isAssignableFrom(type)) {
validate((Collection) object1, (Collection) object2, true);
} else if (Collection.class.isAssignableFrom(type)) {
validate((Collection) object1, (Collection) object2, false);
}
} finally {
this.cache.remove(object1);
}
}
use of java.beans.PropertyDescriptor in project opennms by OpenNMS.
the class AbstractXmlCollectionHandler method parseString.
/**
* Parses the string.
*
* <p>Valid placeholders are:</p>
* <ul>
* <li><b>ipAddr|ipAddress</b>, The Node IP Address</li>
* <li><b>step</b>, The Collection Step in seconds</li>
* <li><b>nodeId</b>, The Node ID</li>
* <li><b>nodeLabel</b>, The Node Label</li>
* <li><b>foreignId</b>, The Node Foreign ID</li>
* <li><b>foreignSource</b>, The Node Foreign Source</li>
* <li>Any asset property defined on the node.</li>
* </ul>
*
* @param reference the reference
* @param unformattedString the unformatted string
* @param node the node
* @param ipAddress the IP address
* @param collectionStep the collection step
* @param parameters the service parameters
* @return the string
* @throws IllegalArgumentException the illegal argument exception
*/
protected static String parseString(final String reference, final String unformattedString, final OnmsNode node, final String ipAddress, final Integer collectionStep, final Map<String, String> parameters) throws IllegalArgumentException {
if (unformattedString == null || node == null)
return null;
String formattedString = unformattedString.replaceAll("[{](?i)(ipAddr|ipAddress)[}]", ipAddress);
formattedString = formattedString.replaceAll("[{](?i)step[}]", collectionStep.toString());
formattedString = formattedString.replaceAll("[{](?i)nodeId[}]", node.getNodeId());
if (node.getLabel() != null)
formattedString = formattedString.replaceAll("[{](?i)nodeLabel[}]", node.getLabel());
if (node.getForeignId() != null)
formattedString = formattedString.replaceAll("[{](?i)foreignId[}]", node.getForeignId());
if (node.getForeignSource() != null)
formattedString = formattedString.replaceAll("[{](?i)foreignSource[}]", node.getForeignSource());
for (Map.Entry<String, String> entry : parameters.entrySet()) {
formattedString = formattedString.replaceAll("[{]parameter:" + entry.getKey() + "[}]", entry.getValue());
}
if (node.getAssetRecord() != null) {
BeanWrapper wrapper = new BeanWrapperImpl(node.getAssetRecord());
for (PropertyDescriptor p : wrapper.getPropertyDescriptors()) {
Object obj = wrapper.getPropertyValue(p.getName());
if (obj != null) {
String objStr = obj.toString();
try {
// NMS-7381 - if pulling from asset info you'd expect to not have to encode reserved words yourself.
objStr = URLEncoder.encode(obj.toString(), StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
formattedString = formattedString.replaceAll("[{](?i)" + p.getName() + "[}]", objStr);
}
}
}
if (formattedString.matches(".*[{].+[}].*"))
throw new IllegalArgumentException("The " + reference + " " + formattedString + " contains unknown placeholders.");
return formattedString;
}
Aggregations