List of usage examples for org.apache.commons.beanutils PropertyUtils describe
public static Map describe(Object bean) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException
Return the entire set of properties for which the specified bean provides a read method.
For more details see PropertyUtilsBean
.
From source file:gemlite.core.internal.db.DBSynchronizer.java
/** * Set the key column values in {@link PreparedStatement} for a primary key * based update or delete operation.//w w w. jav a2 s .co m */ protected void setKeysInPrepStatement(final Object keyValues, final List<String> keyFields, Class valueClass, final PreparedStatement ps, int startIndex) throws SQLException { final int numKeyCols = keyFields.size(); if (logger.isDebugEnabled()) { StringBuilder sb = new StringBuilder().append("DBSynchronizer::setKeysInPrepStatement: setting key {"); for (int col = 0; col < numKeyCols; col++) { if (col > 1) { sb.append(','); } // ???? // ?? String field = keyFields.get(col); try { Map map = PropertyUtils.describe(keyValues); Object val = map.get(field); sb.append(val); } catch (Exception e) { throw new SQLException(e); } } sb.append('}'); logger.info(sb.toString()); } for (int colIndex = 0; colIndex < numKeyCols; colIndex++, startIndex++) { String field = keyFields.get(colIndex); try { Map map = PropertyUtils.describe(keyValues); Object val = map.get(field); String type = valueClass.getDeclaredField(field).getType().getName(); helper.setColumnInPrepStatement(type, val, ps, this, startIndex); } catch (Exception e) { throw new SQLException(e); } } }
From source file:hudson.scm.BlameSubversionSCM.java
/** * In preparation for a comparison, char[] needs to be converted that * supports value equality.//www . j a v a 2 s . c om */ private static Map describeBean(Object o) throws InvocationTargetException, NoSuchMethodException, IllegalAccessException { Map<?, ?> m = PropertyUtils.describe(o); for (Entry e : m.entrySet()) { Object v = e.getValue(); if (v instanceof char[]) { char[] chars = (char[]) v; e.setValue(new String(chars)); } } return m; }
From source file:hudson.scm.SubversionSCM.java
/** * In preparation for a comparison, char[] needs to be converted that supports value equality. *///from ww w .ja va2s . co m @SuppressWarnings("unchecked") private static Map describeBean(Object o) throws InvocationTargetException, NoSuchMethodException, IllegalAccessException { Map<?, ?> m = PropertyUtils.describe(o); for (Entry e : m.entrySet()) { Object v = e.getValue(); if (v instanceof char[]) { char[] chars = (char[]) v; e.setValue(new String(chars)); } } return m; }
From source file:niche.newres.timedevents2owl.generator.introspector.GeneralBeanIntrospector.java
/** * Translates a particular bean into a set of statements. * @param bean/*from www.j av a 2 s . c o m*/ * @param id * @param name * @return */ public static List<Statement> fromBean2OWL(Object bean, String id, String name) { List<Statement> objectStatements = new LinkedList<Statement>(); Statement classStatement = StatementFactory.createInstanceOfClassStatement(id, name); objectStatements.add(classStatement); if (bean instanceof JenaOWLfiable) { objectStatements.addAll(StatementFactory.createJenaOWLfiableContentStatements(objectStatements, classStatement, id, name, (JenaOWLfiable) bean)); return objectStatements; } else { Map<String, Object> propertiesMap = new HashMap<String, Object>(); try { propertiesMap = PropertyUtils.describe(bean); } catch (IllegalAccessException ex) { Logger.getLogger(GeneralBeanIntrospector.class.getName()).log(Level.SEVERE, null, ex); } catch (InvocationTargetException ex) { Logger.getLogger(GeneralBeanIntrospector.class.getName()).log(Level.SEVERE, null, ex); } catch (NoSuchMethodException ex) { Logger.getLogger(GeneralBeanIntrospector.class.getName()).log(Level.SEVERE, null, ex); } if (propertiesMap != null) { for (Map.Entry<String, Object> entry : propertiesMap.entrySet()) { StatementFactory.createObjectContentStatements(objectStatements, classStatement, GeneralBeanIntrospector.capitalizeFirstLetter(entry.getKey()), -1, entry.getValue()); //StatementFactory.createPropertyContentStatements(classStatement, entry.getKey(), entry.getValue()); } } //List<Statement> dateStatements = StatementFactory.createDatatypePropertyContentStatements(classStatement, "Date", this.getDate()); objectStatements.add(classStatement); //objectStatements.addAll(typeStatements); //objectStatements.addAll(dateStatements); return objectStatements; } }
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. *//*from w ww. j a v a2 s. co m*/ @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.// w ww. ja va2 s . co 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); } } }
From source file:org.apache.ambari.view.hive.resources.jobs.Aggregator.java
protected JobImpl mergeAtsJobWithViewJob(HiveQueryId atsHiveQuery, TezDagId atsTezDag, Job viewJob) { JobImpl atsJob;//from w ww. ja v a 2 s . c o m try { atsJob = new JobImpl(PropertyUtils.describe(viewJob)); } catch (IllegalAccessException e) { LOG.error("Can't instantiate JobImpl", e); return null; } catch (InvocationTargetException e) { LOG.error("Can't instantiate JobImpl", e); return null; } catch (NoSuchMethodException e) { LOG.error("Can't instantiate JobImpl", e); return null; } fillAtsJobFields(atsJob, atsHiveQuery, atsTezDag); return atsJob; }
From source file:org.apache.ambari.view.hive.resources.jobs.JobService.java
private JSONObject jsonObjectFromJob(JobController jobController) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException { Map createdJobMap = PropertyUtils.describe(jobController.getJob()); createdJobMap.remove("class"); // no need to show Bean class on client JSONObject jobJson = new JSONObject(); jobJson.put("job", createdJobMap); return jobJson; }
From source file:org.apache.ambari.view.hive.resources.jobs.JobService.java
/** * Create job// w w w . j av a 2 s. c om */ @POST @Consumes(MediaType.APPLICATION_JSON) public Response create(JobRequest request, @Context HttpServletResponse response, @Context UriInfo ui) { try { Map jobInfo = PropertyUtils.describe(request.job); Job job = new JobImpl(jobInfo); getResourceManager().create(job); JobController createdJobController = getResourceManager().readController(job.getId()); createdJobController.submit(); response.setHeader("Location", String.format("%s/%s", ui.getAbsolutePath().toString(), job.getId())); JSONObject jobObject = jsonObjectFromJob(createdJobController); return Response.ok(jobObject).status(201).build(); } catch (WebApplicationException ex) { throw ex; } catch (ItemNotFound itemNotFound) { throw new NotFoundFormattedException(itemNotFound.getMessage(), itemNotFound); } catch (Exception ex) { throw new ServiceFormattedException(ex.getMessage(), ex); } }
From source file:org.apache.falcon.entity.EntityUtil.java
@SuppressWarnings("rawtypes") private static void mapToProperties(Object obj, String name, Map<String, String> propMap, String[] filterProps) throws FalconException { if (obj == null) { return;/*from w w w .j a v a 2 s . c om*/ } if (filterProps != null && name != null) { for (String filter : filterProps) { if (name.matches(filter.replace(".", "\\.").replace("[", "\\[").replace("]", "\\]"))) { return; } } } if (Date.class.isAssignableFrom(obj.getClass())) { propMap.put(name, SchemaHelper.formatDateUTC((Date) obj)); } else if (obj.getClass().getPackage().getName().equals("java.lang")) { propMap.put(name, String.valueOf(obj)); } else if (TimeZone.class.isAssignableFrom(obj.getClass())) { propMap.put(name, ((TimeZone) obj).getID()); } else if (Enum.class.isAssignableFrom(obj.getClass())) { propMap.put(name, ((Enum) obj).name()); } else if (List.class.isAssignableFrom(obj.getClass())) { List list = (List) obj; for (int index = 0; index < list.size(); index++) { mapToProperties(list.get(index), name + "[" + index + "]", propMap, filterProps); } } else { try { Method method = obj.getClass().getDeclaredMethod("toString"); propMap.put(name, (String) method.invoke(obj)); } catch (NoSuchMethodException e) { try { Map map = PropertyUtils.describe(obj); for (Object entry : map.entrySet()) { String key = (String) ((Map.Entry) entry).getKey(); if (!key.equals("class")) { mapToProperties(map.get(key), name != null ? name + "." + key : key, propMap, filterProps); } else { // Just add the parent element to the list too. // Required to detect addition/removal of optional elements with child nodes. // For example, late-process propMap.put(((Class) map.get(key)).getSimpleName(), ""); } } } catch (Exception e1) { throw new FalconException(e1); } } catch (Exception e) { throw new FalconException(e); } } }