List of usage examples for java.beans PropertyDescriptor getReadMethod
public synchronized Method getReadMethod()
From source file:de.hybris.platform.webservices.AbstractWebServicesTest.java
/** * Checks in loop if the given properties of the object are not null </br> if at least one is null, than * AssertionError is thrown </br>//from w ww .j av a2 s .c o m * * @param objectsList * list of objects to check * @param objectsClass * class of objects in the list * @param properties * properties to check */ protected void assertIsNotNull(final Collection objectsList, final Class objectsClass, final String... properties) { final Map<String, PropertyDescriptor> pdMap = getPropertyDescriptors(objectsClass); for (final Object dto : objectsList) { for (final String property : properties) { final PropertyDescriptor propDesc = pdMap.get(property); if (propDesc == null) { Assert.fail("Property '" + property + "' not available"); } Object actualProp = null; try { actualProp = propDesc.getReadMethod().invoke(dto, (Object[]) null); //NOPMD } catch (final Exception e) { LOG.error(e.getMessage(), e); Assert.fail(); } final String msg = dto.getClass().getSimpleName() + ": value of '" + property + "' is null"; Assert.assertNotNull(msg, actualProp); } } }
From source file:net.yasion.common.core.bean.wrapper.impl.ExtendedBeanWrapperImpl.java
@SuppressWarnings("unchecked") private Object getPropertyValue(PropertyTokenHolder tokens) throws BeansException { String propertyName = tokens.canonicalName; String actualName = tokens.actualName; PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName); if (pd == null || pd.getReadMethod() == null) { throw new NotReadablePropertyException(getRootClass(), this.nestedPath + propertyName); }/*from ww w.j a va2s. com*/ final Method readMethod = pd.getReadMethod(); try { if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers()) && !readMethod.isAccessible()) { if (System.getSecurityManager() != null) { AccessController.doPrivileged(new PrivilegedAction<Object>() { @Override public Object run() { readMethod.setAccessible(true); return null; } }); } else { readMethod.setAccessible(true); } } Object value; if (System.getSecurityManager() != null) { try { value = AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { return readMethod.invoke(object, (Object[]) null); } }, acc); } catch (PrivilegedActionException pae) { throw pae.getException(); } } else { value = readMethod.invoke(object, (Object[]) null); } if (tokens.keys != null) { if (value == null) { if (isAutoGrowNestedPaths()) { value = setDefaultValue(tokens.actualName); } else { throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + propertyName, "Cannot access indexed value of property referenced in indexed " + "property path '" + propertyName + "': returned null"); } } String indexedPropertyName = tokens.actualName; // apply indexes and map keys for (int i = 0; i < tokens.keys.length; i++) { String key = tokens.keys[i]; if (value == null) { throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + propertyName, "Cannot access indexed value of property referenced in indexed " + "property path '" + propertyName + "': returned null"); } else if (value.getClass().isArray()) { int index = Integer.parseInt(key); value = growArrayIfNecessary(value, index, indexedPropertyName); value = Array.get(value, index); } else if (value instanceof List) { int index = Integer.parseInt(key); List<Object> list = (List<Object>) value; growCollectionIfNecessary(list, index, indexedPropertyName, pd, i + 1); value = list.get(index); } else if (value instanceof Set) { // Apply index to Iterator in case of a Set. Set<Object> set = (Set<Object>) value; int index = Integer.parseInt(key); if (index < 0 || index >= set.size()) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Cannot get element with index " + index + " from Set of size " + set.size() + ", accessed using property path '" + propertyName + "'"); } Iterator<Object> it = set.iterator(); for (int j = 0; it.hasNext(); j++) { Object elem = it.next(); if (j == index) { value = elem; break; } } } else if (value instanceof Map) { Map<Object, Object> map = (Map<Object, Object>) value; Class<?> mapKeyType = GenericCollectionTypeResolver.getMapKeyReturnType(pd.getReadMethod(), i + 1); // IMPORTANT: Do not pass full property name in here - property editors // must not kick in for map keys but rather only for map values. TypeDescriptor typeDescriptor = TypeDescriptor.valueOf(mapKeyType); Object convertedMapKey = convertIfNecessary(null, null, key, mapKeyType, typeDescriptor); value = map.get(convertedMapKey); } else { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Property referenced in indexed property path '" + propertyName + "' is neither an array nor a List nor a Set nor a Map; returned value was [" + value + "]"); } indexedPropertyName += PROPERTY_KEY_PREFIX + key + PROPERTY_KEY_SUFFIX; } } return value; } catch (IndexOutOfBoundsException ex) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Index of out of bounds in property path '" + propertyName + "'", ex); } catch (NumberFormatException ex) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Invalid index in property path '" + propertyName + "'", ex); } catch (TypeMismatchException ex) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Invalid index in property path '" + propertyName + "'", ex); } catch (InvocationTargetException ex) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Getter for property '" + actualName + "' threw exception", ex); } catch (Exception ex) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Illegal attempt to get property '" + actualName + "' threw exception", ex); } }
From source file:net.yasion.common.core.bean.wrapper.ExtendedBeanInfo.java
private void handleCandidateWriteMethod(Method method) throws IntrospectionException { int nParams = method.getParameterTypes().length; String propertyName = propertyNameFor(method); Class<?> propertyType = method.getParameterTypes()[nParams - 1]; PropertyDescriptor existingPd = findExistingPropertyDescriptor(propertyName, propertyType); if (nParams == 1) { if (existingPd == null) { this.propertyDescriptors.add(new SimplePropertyDescriptor(propertyName, null, method)); } else {//from ww w.j a va 2 s .c o m existingPd.setWriteMethod(method); } } else if (nParams == 2) { if (existingPd == null) { this.propertyDescriptors .add(new SimpleIndexedPropertyDescriptor(propertyName, null, null, null, method)); } else if (existingPd instanceof IndexedPropertyDescriptor) { ((IndexedPropertyDescriptor) existingPd).setIndexedWriteMethod(method); } else { this.propertyDescriptors.remove(existingPd); this.propertyDescriptors.add(new SimpleIndexedPropertyDescriptor(propertyName, existingPd.getReadMethod(), existingPd.getWriteMethod(), null, method)); } } else { throw new IllegalArgumentException("Write method must have exactly 1 or 2 parameters: " + method); } }
From source file:net.yasion.common.core.bean.wrapper.impl.ExtendedBeanWrapperImpl.java
@Override public TypeDescriptor getPropertyTypeDescriptor(String propertyName) throws BeansException { try {//from w w w . j a va 2s . c om ExtendedBeanWrapperImpl nestedBw = getBeanWrapperForPropertyPath(propertyName); String finalPath = getFinalPath(nestedBw, propertyName); PropertyTokenHolder tokens = getPropertyNameTokens(finalPath); PropertyDescriptor pd = nestedBw.getCachedIntrospectionResults() .getPropertyDescriptor(tokens.actualName); if (pd != null) { if (tokens.keys != null) { if (pd.getReadMethod() != null || pd.getWriteMethod() != null) { return TypeDescriptor.nested(property(pd), tokens.keys.length); } } else { if (pd.getReadMethod() != null || pd.getWriteMethod() != null) { return new TypeDescriptor(property(pd)); } } } } catch (InvalidPropertyException ex) { // Consider as not determinable. } return null; }
From source file:de.hybris.platform.webservices.AbstractWebServicesTest.java
/** * Tests a collection of properties of two objects for equality. * //from w ww . j a v a 2 s . co m * @param expectedDto * expected object (dto) * @param actualDto * actual object (dto) * @param properties * properties to check */ protected void assertEqual(final Object expectedDto, final Object actualDto, final String... properties) { final Map<String, PropertyDescriptor> pdMap = getPropertyDescriptors(expectedDto.getClass()); for (final String property : properties) { final PropertyDescriptor propertyDescriptor = pdMap.get(property); if (propertyDescriptor == null) { Assert.fail("Property '" + property + "' not available"); } Object expectedProp = null; Object actualProp = null; try { expectedProp = propertyDescriptor.getReadMethod().invoke(expectedDto, (Object[]) null); actualProp = propertyDescriptor.getReadMethod().invoke(actualDto, (Object[]) null); } catch (final Exception e) { LOG.error(e.getMessage(), e); Assert.fail(); } final String msg = actualDto.getClass().getSimpleName() + ": value of '" + property + "' does not match expected value (actual: '" + actualProp + "' expected: '" + expectedProp + "')"; Assert.assertEquals(msg, expectedProp, actualProp); } }
From source file:org.gbif.portal.registration.UDDIUtils.java
/** * Updates the resource given, which must have the UUID set or it'll be a create * TODO Fill in the rest of the details/*from w w w . j a v a2 s .c o m*/ * @param resource To update * @param businessKey To update * @throws TransportException On uddi communication error - e.g. server down * @throws UDDIException On uddi communication error - e.g. bad data */ @SuppressWarnings("unchecked") public void updateResource(ResourceDetail resource, String businessKey) throws UDDIException, TransportException { BusinessService bs = new BusinessService(); bs.setBusinessKey(businessKey); bs.setServiceKey(resource.getServiceKey()); bs.setDefaultDescriptionString(resource.getDescription()); bs.setDefaultNameString(resource.getName(), "en"); bs.setDefaultName(new Name(resource.getName())); AuthToken authToken = uddiProxy.get_authToken(getUddiAuthUser(), getUddiAuthPassword()); //create business service vector Vector businessServiceVector = new Vector(); businessServiceVector.add(bs); //add other properties into a category bag CategoryBag cb = new CategoryBag(); try { Map<String, Object> properties = BeanUtils.describe(resource); for (String key : properties.keySet()) { Object property = properties.get(key); PropertyDescriptor pd = org.springframework.beans.BeanUtils .getPropertyDescriptor(ResourceDetail.class, key); Class propertyType = pd.getPropertyType(); if (property != null) { if (property instanceof List) { List propertyList = (List) property; for (Object listItem : propertyList) { if (listItem != null) addToCategoryBagIfNotNull(cb, key, listItem.toString()); } } else if (propertyType.equals(Date.class)) { SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyy"); Method readMethod = pd.getReadMethod(); Date theDate = (Date) readMethod.invoke(resource, (Object[]) null); if (theDate != null) { addToCategoryBagIfNotNull(cb, key, sdf.format(theDate)); } } else { addToCategoryBagIfNotNull(cb, key, property.toString()); } } } } catch (Exception e) { logger.error(e.getMessage(), e); } bs.setCategoryBag(cb); logger.info("About to save..."); ServiceDetail sd = getUddiProxy().save_service(authToken.getAuthInfoString(), businessServiceVector); // set in the resource serviceKey if required Vector<BusinessService> resultVector = sd.getBusinessServiceVector(); AccessPoint ap = null; BindingTemplate bt = null; BindingTemplates bts = null; for (BusinessService rbs : resultVector) { logger.info("Setting the service key (should be once): " + rbs.getServiceKey()); resource.setServiceKey(rbs.getServiceKey()); bts = rbs.getBindingTemplates(); if (bts != null && bts.size() > 0) { bt = rbs.getBindingTemplates().get(0); ap = bt.getAccessPoint(); } break; } //if there are no binding templates, then add them if (bts == null || bts.size() == 0) { // Saving TModel TModelDetail tModelDetail = null; TModelList tModelList = getUddiProxy().find_tModel(resource.getResourceType(), null, null, null, 1); if (tModelList.getTModelInfos().size() == 0) { //save this new tmodel Vector tModels = new Vector(); TModel newTModel = new TModel("", resource.getResourceType()); tModels.add(newTModel); tModelDetail = getUddiProxy().save_tModel(authToken.getAuthInfoString(), tModels); } else { TModelInfo tModelInfo = tModelList.getTModelInfos().get(0); tModelDetail = getUddiProxy().get_tModelDetail(tModelInfo.getTModelKey()); } // Creating TModelInstanceDetails Vector tModelVector = tModelDetail.getTModelVector(); String tModelKey = ((TModel) (tModelVector.elementAt(0))).getTModelKey(); Vector tModelInstanceInfoVector = new Vector(); TModelInstanceInfo tModelInstanceInfo = new TModelInstanceInfo(tModelKey); tModelInstanceInfoVector.add(tModelInstanceInfo); TModelInstanceDetails tModelInstanceDetails = new TModelInstanceDetails(); tModelInstanceDetails.setTModelInstanceInfoVector(tModelInstanceInfoVector); Vector bindingTemplatesVector = new Vector(); // Create a new binding templates using required elements constructor // BindingKey must be "" to save a new binding BindingTemplate bindingTemplate = new BindingTemplate("", tModelInstanceDetails, new AccessPoint(resource.getAccessPoint(), "http")); bindingTemplate.setServiceKey(resource.getServiceKey()); bindingTemplatesVector.addElement(bindingTemplate); // **** Save the Binding Template BindingDetail bindingDetail = getUddiProxy().save_binding(authToken.getAuthInfoString(), bindingTemplatesVector); } logger.info("Save completed for " + resource.getName()); }
From source file:com.twinsoft.convertigo.engine.Context.java
public Object getTransactionProperty(String propertyName) { if (requestedObject == null) { return null; }/* w w w . j a va 2s. c o m*/ BeanInfo bi; try { bi = CachedIntrospector.getBeanInfo(requestedObject.getClass()); } catch (IntrospectionException e) { Engine.logContext .error("getTransactionProperty : Exception while finding the bean info for transaction class '" + requestedObject.getClass() + "'", e); return null; } PropertyDescriptor[] propertyDescriptors = bi.getPropertyDescriptors(); int len2 = propertyDescriptors.length; PropertyDescriptor propertyDescriptor = null; Object propertyValue; int j; String propertyDescriptorName = ""; for (j = 0; j < len2; j++) { propertyDescriptor = propertyDescriptors[j]; propertyDescriptorName = propertyDescriptor.getName(); if (propertyDescriptorName.equals(propertyName)) break; } if (j == len2 && !propertyDescriptorName.equals(propertyName)) { Engine.logContext.debug("getTransactionProperty : no property descriptor found for the property '" + propertyName + "'"); return null; } Method getter = propertyDescriptor.getReadMethod(); Object args[] = {}; try { propertyValue = getter.invoke(requestedObject, args); } catch (Exception e) { Engine.logContext.error("getTransactionProperty : Exception while executing the property getter '" + getter.getName() + "'", e); return null; } return propertyValue; }
From source file:org.codehaus.groovy.grails.commons.DefaultGrailsDomainClassProperty.java
/** * Constructor.//from w w w . j a v a 2s . c o m * @param domainClass * @param descriptor */ @SuppressWarnings("rawtypes") public DefaultGrailsDomainClassProperty(GrailsDomainClass domainClass, PropertyDescriptor descriptor, Map<String, Object> defaultConstraints) { this.domainClass = domainClass; name = descriptor.getName(); naturalName = GrailsNameUtils.getNaturalName(descriptor.getName()); type = descriptor.getPropertyType(); identity = descriptor.getName().equals(IDENTITY); // establish if property is persistant if (domainClass != null) { // figure out if this property is inherited if (!domainClass.isRoot()) { inherited = GrailsClassUtils.isPropertyInherited(domainClass.getClazz(), name); } List transientProps = getTransients(); checkIfTransient(transientProps); establishFetchMode(); } if (descriptor.getReadMethod() == null || descriptor.getWriteMethod() == null) { persistent = false; } if (Errors.class.isAssignableFrom(type)) { persistent = false; } this.defaultConstraints = defaultConstraints; }
From source file:net.yasion.common.core.bean.wrapper.impl.ExtendedBeanWrapperImpl.java
private void growCollectionIfNecessary(Collection<Object> collection, int index, String name, PropertyDescriptor pd, int nestingLevel) { if (!isAutoGrowNestedPaths()) { return;/*from w ww. j a va 2 s.c o m*/ } int size = collection.size(); if (index >= size && index < this.autoGrowCollectionLimit) { Class<?> elementType = GenericCollectionTypeResolver.getCollectionReturnType(pd.getReadMethod(), nestingLevel); if (elementType != null) { for (int i = collection.size(); i < index + 1; i++) { collection.add(newValue(elementType, null, name)); } } } }
From source file:com.googlecode.wicketwebbeans.model.BeanMetaData.java
/** * Derive metadata from standard annotations such as JPA and FindBugs. * /*ww w. j a va 2 s. c o m*/ * @param descriptor * @param elementMetaData */ private void deriveElementFromAnnotations(PropertyDescriptor descriptor, ElementMetaData elementMetaData) { // NOTE: !!! The annotation classes must be present at runtime, otherwise getAnnotations() doesn't // return the annotation. Method readMethod = descriptor.getReadMethod(); if (readMethod != null) { processElementAnnotations(elementMetaData, readMethod.getAnnotations()); } Method writeMethod = descriptor.getWriteMethod(); if (writeMethod != null) { processElementAnnotations(elementMetaData, writeMethod.getAnnotations()); } // Collects annotations on fields // Patch submitted by Richard O'Sullivan, fixes issue 9 try { java.lang.reflect.Field beanField = beanClass.getDeclaredField(descriptor.getName()); processElementAnnotations(elementMetaData, beanField.getAnnotations()); } catch (Exception e) { // no foul, no harm. } }