List of usage examples for org.apache.commons.beanutils PropertyUtils setProperty
public static void setProperty(Object bean, String name, Object value) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException
Set the value of the specified property of the specified bean, no matter which property reference format is used, with no type conversions.
For more details see PropertyUtilsBean
.
From source file:nz.co.senanque.messaging.OrderReplyEndpoint.java
public void issueResponseFor(Message<org.w3c.dom.Document> orderResponse) { log.debug("processed orderResponse: correlationId {}", orderResponse.getHeaders().get(IntegrationMessageHeaderAccessor.CORRELATION_ID, Long.class)); org.w3c.dom.Document doc = orderResponse.getPayload(); Document document = new DOMBuilder().build(doc); Element root = document.getRootElement(); Order context = new Order(); @SuppressWarnings("unchecked") Iterator<Text> itr = (Iterator<Text>) root .getDescendants(new ContentFilter(ContentFilter.TEXT | ContentFilter.CDATA)); while (itr.hasNext()) { Text text = itr.next();//from w w w .j ava2 s.co m log.debug("name {} value {}", text.getParentElement().getName(), text.getValue()); String name = getName(text); try { Class<?> targetType = PropertyUtils.getPropertyType(context, name); Object value = ConvertUtils.convert(text.getValue(), targetType); PropertyUtils.setProperty(context, name, value); } catch (IllegalAccessException e) { // Ignore these and move on log.debug("{} {}", name, e.getMessage()); } catch (InvocationTargetException e) { // Ignore these and move on log.debug("{} {}", name, e.getMessage()); } catch (NoSuchMethodException e) { // Ignore these and move on log.debug("{} {}", name, e.getMessage()); } } }
From source file:omero.cmd.graphs.DuplicateI.java
/** * Duplicate model object properties, linking them as appropriate with each other and with other model objects. * @throws GraphException if duplication failed *//*from w ww .j a v a 2 s. c om*/ private void setDuplicatePropertyValues() throws GraphException { /* organize duplicate index by class name and ID */ final Map<Entry<String, Long>, IObject> duplicatesByOriginalClassAndId = new HashMap<Entry<String, Long>, IObject>(); for (final Entry<IObject, IObject> originalAndDuplicate : originalsToDuplicates.entrySet()) { final IObject original = originalAndDuplicate.getKey(); final String originalClass = Hibernate.getClass(original).getName(); final Long originalId = original.getId(); final IObject duplicate = originalAndDuplicate.getValue(); duplicatesByOriginalClassAndId.put(Maps.immutableEntry(originalClass, originalId), duplicate); } /* allow lookup regardless of if original is actually a Hibernate proxy object */ final Function<Object, Object> duplicateLookup = new Function<Object, Object>() { @Override public Object apply(Object original) { if (original instanceof IObject) { final String originalClass; if (original instanceof HibernateProxy) { originalClass = Hibernate.getClass(original).getName(); } else { originalClass = original.getClass().getName(); } final Long originalId = ((IObject) original).getId(); return duplicatesByOriginalClassAndId.get(Maps.immutableEntry(originalClass, originalId)); } else { return null; } } }; /* copy property values into duplicates and link with other model objects */ final Session session = helper.getSession(); for (final Entry<IObject, IObject> originalAndDuplicate : originalsToDuplicates.entrySet()) { final IObject original = originalAndDuplicate.getKey(); final IObject duplicate = originalAndDuplicate.getValue(); final String originalClass = Hibernate.getClass(original).getName(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("copying properties from " + originalClass + ":" + original.getId()); } try { /* process property values for a given object that is duplicated */ for (final String superclassName : graphPathBean.getSuperclassesOfReflexive(originalClass)) { /* process property values that link from the duplicate to other model objects */ for (final Entry<String, String> forwardLink : graphPathBean.getLinkedTo(superclassName)) { /* next forward link */ final String linkedClassName = forwardLink.getKey(); final String property = forwardLink.getValue(); /* ignore details for now, duplicates never preserve original ownership */ if (property.startsWith("details.")) { continue; } /* note which of the objects to which the original links should be ignored */ final Set<Long> linkedToIdsToIgnore = new HashSet<Long>(); for (final Entry<String, Collection<Long>> linkedToClassIds : graphTraversal .getLinkeds(superclassName, property, original.getId()).asMap().entrySet()) { final String linkedToClass = linkedToClassIds.getKey(); final Collection<Long> linkedToIds = linkedToClassIds.getValue(); if (classifier.getClass( Class.forName(linkedToClass).asSubclass(IObject.class)) == Inclusion.IGNORE) { linkedToIdsToIgnore.addAll(linkedToIds); } } /* check for another accessor for inaccessible properties */ if (graphPathBean.isPropertyAccessible(superclassName, property)) { /* copy the linking from the original's property over to the duplicate's */ Object value; try { value = PropertyUtils.getNestedProperty(original, property); } catch (NestedNullException e) { continue; } if (value instanceof Collection) { /* if a collection property, include only the objects that aren't to be ignored */ final Collection<IObject> valueCollection = (Collection<IObject>) value; final Collection<IObject> valueToCopy; if (value instanceof List) { valueToCopy = new ArrayList<IObject>(); } else if (value instanceof Set) { valueToCopy = new HashSet<IObject>(); } else { throw new GraphException("unexpected collection type: " + value.getClass()); } for (final IObject linkedTo : valueCollection) { if (!linkedToIdsToIgnore.contains(linkedTo.getId())) { valueToCopy.add(linkedTo); } } value = valueToCopy; } else if (value instanceof IObject) { /* if the property value is to be ignored then null it */ if (linkedToIdsToIgnore.contains(((IObject) value).getId())) { value = null; } } /* copy the property value, replacing originals with corresponding duplicates */ final Object duplicateValue = GraphUtil.copyComplexValue(duplicateLookup, value); try { PropertyUtils.setNestedProperty(duplicate, property, duplicateValue); } catch (NestedNullException e) { throw new GraphException( "cannot set property " + superclassName + '.' + property + " on duplicate"); } } else { /* this could be a one-to-many property with direct accessors protected */ final Class<? extends IObject> linkerClass = Class.forName(superclassName) .asSubclass(IObject.class); final Class<? extends IObject> linkedClass = Class.forName(linkedClassName) .asSubclass(IObject.class); final Method reader, writer; try { reader = linkerClass.getMethod("iterate" + StringUtils.capitalize(property)); writer = linkerClass.getMethod("add" + linkedClass.getSimpleName(), linkedClass); } catch (NoSuchMethodException | SecurityException e) { /* no luck, so ignore this property */ continue; } /* copy the linking from the original's property over to the duplicate's */ final Iterator<IObject> linkedTos = (Iterator<IObject>) reader.invoke(original); while (linkedTos.hasNext()) { final IObject linkedTo = linkedTos.next(); /* copy only links to other duplicates, as otherwise we may steal objects from the original */ final IObject duplicateOfLinkedTo = (IObject) duplicateLookup.apply(linkedTo); if (duplicateOfLinkedTo != null) { writer.invoke(duplicate, duplicateOfLinkedTo); } } } } /* process property values that link to the duplicate from other model objects */ for (final Entry<String, String> backwardLink : graphPathBean.getLinkedBy(superclassName)) { /* next backward link */ final String linkingClass = backwardLink.getKey(); final String property = backwardLink.getValue(); /* ignore inaccessible properties */ if (!graphPathBean.isPropertyAccessible(linkingClass, property)) { continue; } for (final Entry<String, Collection<Long>> linkedFromClassIds : graphTraversal .getLinkers(linkingClass, property, original.getId()).asMap().entrySet()) { final String linkedFromClass = linkedFromClassIds.getKey(); final Collection<Long> linkedFromIds = linkedFromClassIds.getValue(); if (classifier.getClass( Class.forName(linkedFromClass).asSubclass(IObject.class)) == Inclusion.IGNORE) { /* these linkers are to be ignored */ continue; } /* load the instances that link to the original */ final String rootQuery = "FROM " + linkedFromClass + " WHERE id IN (:ids)"; for (final List<Long> idsBatch : Iterables.partition(linkedFromIds, BATCH_SIZE)) { final List<IObject> linkers = session.createQuery(rootQuery) .setParameterList("ids", idsBatch).list(); for (final IObject linker : linkers) { if (originalsToDuplicates.containsKey(linker)) { /* ignore linkers that are to be duplicated, those are handled as forward links */ continue; } /* copy the linking from the original's property over to the duplicate's */ Object value; try { value = PropertyUtils.getNestedProperty(linker, property); } catch (NestedNullException e) { continue; } /* for linkers only adjust collection properties */ if (value instanceof Collection) { final Collection<IObject> valueCollection = (Collection<IObject>) value; final Collection<IObject> newDuplicates = new ArrayList<IObject>(); for (final IObject originalLinker : valueCollection) { final IObject duplicateOfValue = originalsToDuplicates .get(originalLinker); if (duplicateOfValue != null) { /* previous had just original, now include duplicate too */ newDuplicates.add(duplicateOfValue); } } valueCollection.addAll(newDuplicates); } } } } } /* process property values that do not relate to edges in the model object graph */ for (final String property : graphPathBean.getSimpleProperties(superclassName)) { /* ignore inaccessible properties */ if (!graphPathBean.isPropertyAccessible(superclassName, property)) { continue; } /* copy original property value to duplicate */ final Object value = PropertyUtils.getProperty(original, property); PropertyUtils.setProperty(duplicate, property, GraphUtil.copyComplexValue(duplicateLookup, value)); } } } catch (ClassNotFoundException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { throw new GraphException("failed to duplicate " + originalClass + ':' + original.getId()); } } }
From source file:org.abstractform.binding.fluent.BeanBasedPresenter.java
@Override public void setPropertyValue(String propertyName, Object value) { try {// w ww . ja v a 2s . c o m PropertyUtils.setProperty(getModel(), propertyName, value); } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { throw new IllegalArgumentException("The property passed as parameter can be wrong", e); } }
From source file:org.abstractform.binding.fluent.BFBeanBasedOwnPropertiesPresenter.java
@Override public void setPropertyValue(String propertyName, Object value) { if (ownProperties.contains(propertyName)) { try {//from ww w . j a v a 2s. c o m PropertyUtils.setProperty(this, propertyName, value); } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { throw new IllegalArgumentException("The property passed as parameter can be wrong", e); } } else { super.setPropertyValue(propertyName, value); } }
From source file:org.ajax4jsf.component.UISelector.java
public void encodeAjaxChild(FacesContext context, String path, Set<String> ids, Set<String> renderedAreas) throws IOException { if (getChildCount() != 1) { throw new FacesException("Selector component must have one, and only one, child"); }/*from w w w .j a va 2 s . co m*/ UIComponent child = (UIComponent) getChildren().get(0); Set<Object> ajaxKeys = getAjaxKeys(); if (null != ajaxKeys) { String iterationProperty = getIterationProperty(); try { Object savedKey = PropertyUtils.getProperty(child, iterationProperty); for (Iterator<Object> iter = ajaxKeys.iterator(); iter.hasNext();) { Object key = (Object) iter.next(); PropertyUtils.setProperty(child, iterationProperty, key); if (true) { childrenRenderer.encodeAjaxChildren(context, this, path, ids, renderedAreas); } } PropertyUtils.setProperty(child, iterationProperty, savedKey); } catch (IllegalAccessException e) { throw new FacesException("Illegal access to iteration selection property " + iterationProperty + " on component " + child.getClientId(context), e); } catch (InvocationTargetException e) { throw new FacesException("Error in iteration selection property " + iterationProperty + " on component " + child.getClientId(context), e.getCause()); } catch (NoSuchMethodException e) { throw new FacesException("No iteration selection property " + iterationProperty + " on component " + child.getClientId(context), e); } } }
From source file:org.alfresco.repo.content.transform.ComplexContentTransformer.java
/** * Sets any transformation option overrides it can. *//* w ww . ja va 2 s.c om*/ private void overrideTransformationOptions(TransformationOptions options) { // Set any transformation options overrides if we can if (options != null && transformationOptionOverrides != null) { for (String key : transformationOptionOverrides.keySet()) { if (PropertyUtils.isWriteable(options, key)) { try { PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(options, key); Class<?> propertyClass = pd.getPropertyType(); Object value = transformationOptionOverrides.get(key); if (value != null) { if (propertyClass.isInstance(value)) { // Nothing to do } else if (value instanceof String && propertyClass.isInstance(Boolean.TRUE)) { // Use relaxed converter value = TransformationOptions.relaxedBooleanTypeConverter.convert((String) value); } else { value = DefaultTypeConverter.INSTANCE.convert(propertyClass, value); } } PropertyUtils.setProperty(options, key, value); } catch (MethodNotFoundException mnfe) { } catch (NoSuchMethodException nsme) { } catch (InvocationTargetException ite) { } catch (IllegalAccessException iae) { } } else { logger.warn("Unable to set override Transformation Option " + key + " on " + options); } } } }
From source file:org.androidtransfuse.processor.Merger.java
private <T extends Mergeable> T mergeMergeable(Class<? extends T> targetClass, T target, T source) throws MergerException { try {//ww w . java 2 s.c o m BeanInfo beanInfo = Introspector.getBeanInfo(targetClass); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { Method getter = propertyDescriptor.getReadMethod(); Method setter = propertyDescriptor.getWriteMethod(); String propertyName = propertyDescriptor.getDisplayName(); if (PropertyUtils.isWriteable(target, propertyName)) { //check for mergeCollection MergeCollection mergeCollection = findAnnotation(MergeCollection.class, getter, setter); if (Collection.class.isAssignableFrom(propertyDescriptor.getPropertyType())) { PropertyUtils.setProperty(target, propertyName, mergeList(mergeCollection, propertyName, target, source)); } //check for merge Merge mergeAnnotation = findAnnotation(Merge.class, getter, setter); PropertyUtils.setProperty(target, propertyName, mergeProperties(mergeAnnotation, propertyName, target, source)); } } } catch (NoSuchMethodException e) { throw new MergerException("NoSuchMethodException while trying to merge", e); } catch (IntrospectionException e) { throw new MergerException("IntrospectionException while trying to merge", e); } catch (IllegalAccessException e) { throw new MergerException("IllegalAccessException while trying to merge", e); } catch (InvocationTargetException e) { throw new MergerException("InvocationTargetException while trying to merge", e); } return target; }
From source file:org.andromda.presentation.gui.FileDownloadServlet.java
/** * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */// w ww . j a va 2 s . c o m @Override public void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { try { final String action = request.getParameter(ACTION); final FacesContext context = FacesContextUtils.getFacesContext(request, response); if (action != null && action.trim().length() > 0) { final MethodBinding methodBinding = context.getApplication() .createMethodBinding("#{" + action + "}", null); methodBinding.invoke(context, null); } final Object form = context.getApplication().getVariableResolver().resolveVariable(context, "form"); final Boolean prompt = Boolean.valueOf(request.getParameter(PROMPT)); final String fileNameProperty = request.getParameter(FILE_NAME); final String outputProperty = request.getParameter(OUTPUT); if (form != null && outputProperty != null && fileNameProperty.trim().length() > 0) { final OutputStream stream = response.getOutputStream(); // - reset the response to clear out any any headers (i.e. so // the user doesn't get "unable to open..." when using IE.) response.reset(); Object output = PropertyUtils.getProperty(form, outputProperty); final String fileName = ObjectUtils.toString(PropertyUtils.getProperty(form, fileNameProperty)); final String contentType = this.getContentType(context, request.getParameter(CONTENT_TYPE), fileName); if (prompt.booleanValue() && fileName != null && fileName.trim().length() > 0) { response.addHeader("Content-disposition", "attachment; filename=\"" + fileName + '"'); } // - for IE we need to set the content type, content length and buffer size and // then the flush the response right away because it seems as if there is any lag time // IE just displays a blank page. With mozilla based clients reports display correctly regardless. if (contentType != null && contentType.length() > 0) { response.setContentType(contentType); } if (output instanceof String) { output = ((String) output).getBytes(); } if (output instanceof byte[]) { byte[] file = (byte[]) output; response.setBufferSize(file.length); response.setContentLength(file.length); response.flushBuffer(); stream.write(file); } else if (output instanceof InputStream) { final InputStream report = (InputStream) output; final byte[] buffer = new byte[BUFFER_SIZE]; response.setBufferSize(BUFFER_SIZE); response.flushBuffer(); for (int ctr = 0; (ctr = report.read(buffer)) > 0;) { stream.write(buffer, 0, ctr); } } stream.flush(); } if (form != null) { // - remove the output now that we're done with it (in case its large) PropertyUtils.setProperty(form, outputProperty, null); } } catch (Throwable throwable) { throw new ServletException(throwable); } }
From source file:org.andromda.presentation.gui.FormPopulator.java
/** * Copies the properties from the <code>fromForm</code> to the <code>toForm</code>. Only passes not-null values to the toForm. * * @param fromForm the form from which we're populating * @param toForm the form to which we're populating * @param override whether or not properties that have already been copied, should be overridden. */// w w w .ja va 2 s . c om @SuppressWarnings("unchecked") // apache commons-beanutils PropertyUtils has no generics public static final void populateForm(final Object fromForm, final Object toForm, boolean override) { if (fromForm != null && toForm != null) { try { final Map<String, Object> parameters = PropertyUtils.describe(fromForm); for (final Iterator<String> iterator = parameters.keySet().iterator(); iterator.hasNext();) { final String name = iterator.next(); if (PropertyUtils.isWriteable(toForm, name)) { // - the property name used for checking whether or not the property value has been set final String isSetPropertyName = name + "Set"; Boolean isToFormPropertySet = null; Boolean isFromFormPropertySet = null; // - only if override isn't true do we care whether or not the to property has been populated if (!override) { if (PropertyUtils.isReadable(toForm, isSetPropertyName)) { isToFormPropertySet = (Boolean) PropertyUtils.getProperty(toForm, isSetPropertyName); } } // - only if override is set to true, we check to see if the from form property has been set if (override) { if (PropertyUtils.isReadable(fromForm, isSetPropertyName)) { isFromFormPropertySet = (Boolean) PropertyUtils.getProperty(fromForm, isSetPropertyName); } } if (!override || (override && isFromFormPropertySet != null && isFromFormPropertySet.booleanValue())) { if (override || (isToFormPropertySet == null || !isToFormPropertySet.booleanValue())) { final PropertyDescriptor toDescriptor = PropertyUtils.getPropertyDescriptor(toForm, name); if (toDescriptor != null) { Object fromValue = parameters.get(name); // - only populate if not null if (fromValue != null) { final PropertyDescriptor fromDescriptor = PropertyUtils .getPropertyDescriptor(fromForm, name); // - only attempt to set if the types match if (fromDescriptor.getPropertyType() == toDescriptor.getPropertyType()) { PropertyUtils.setProperty(toForm, name, fromValue); } } } } } } } } catch (final Throwable throwable) { throw new RuntimeException(throwable); } } }
From source file:org.andromda.presentation.gui.FormPopulator.java
/** * Populates the form from the given map of properties. If a matching property is null or an empty * string, then null is placed on the form. * * @param form the form to populate./* ww w . ja va 2s . c o m*/ * @param formatters any date or time formatters. * @param properties the properties to populate from. * @param ignoreProperties names of any properties to ignore when it comes to populating on the form. * @param override whether or not to override properties already set on the given form. * @param assignableTypesOnly whether or not copying should be attempted only if the property types are assignable. */ @SuppressWarnings("unchecked") // apache commons-beanutils PropertyUtils has no generics public static final void populateFormFromPropertyMap(final Object form, final Map<String, DateFormat> formatters, final Map<String, ?> properties, final String[] ignoreProperties, boolean override, boolean assignableTypesOnly) { if (properties != null) { try { final Collection<String> ignoredProperties = ignoreProperties != null ? Arrays.asList(ignoreProperties) : new ArrayList<String>(); final Map<String, Object> formProperties = PropertyUtils.describe(form); for (final Iterator<String> iterator = formProperties.keySet().iterator(); iterator.hasNext();) { final String name = iterator.next(); if (PropertyUtils.isWriteable(form, name) && !ignoredProperties.contains(name)) { final PropertyDescriptor descriptor = PropertyUtils.getPropertyDescriptor(form, name); if (descriptor != null) { boolean populateProperty = true; if (!override) { final String isSetPropertyName = name + "Set"; if (PropertyUtils.isReadable(form, isSetPropertyName)) { final Boolean isPropertySet = (Boolean) PropertyUtils.getProperty(form, isSetPropertyName); if (isPropertySet.booleanValue()) { populateProperty = false; } } } if (populateProperty) { final Object property = properties.get(name); // - only convert if the string is not empty if (property != null) { Object value = null; if (property instanceof String) { final String propertyAsString = (String) property; if (propertyAsString.trim().length() > 0) { DateFormat formatter = formatters != null ? formatters.get(name) : null; // - if the formatter is available we use that, otherwise we attempt to convert if (formatter != null) { try { value = formatter.parse(propertyAsString); } catch (ParseException parseException) { // - try the default formatter (handles the default java.util.Date.toString() format) formatter = formatters != null ? formatters.get(null) : null; value = formatter.parse(propertyAsString); } } else { value = ConvertUtils.convert(propertyAsString, descriptor.getPropertyType()); } } // - don't attempt to set null on primitive fields if (value != null || !descriptor.getPropertyType().isPrimitive()) { PropertyUtils.setProperty(form, name, value); } } else { value = property; try { if (!assignableTypesOnly || descriptor.getPropertyType() .isAssignableFrom(value.getClass())) { PropertyUtils.setProperty(form, name, value); } } catch (Exception exception) { final String valueTypeName = value.getClass().getName(); final String propertyTypeName = descriptor.getPropertyType().getName(); final StringBuilder message = new StringBuilder( "Can not set form property '" + name + "' of type: " + propertyTypeName + " with value: " + value); if (!descriptor.getPropertyType().isAssignableFrom(value.getClass())) { message.append("; " + valueTypeName + " is not assignable to " + propertyTypeName); } throw new IllegalArgumentException( message + ": " + exception.toString()); } } } } } } } } catch (final Throwable throwable) { throw new RuntimeException(throwable); } } }