Java Code Examples for org.apache.commons.beanutils.PropertyUtils#setProperty()

The following examples show how to use org.apache.commons.beanutils.PropertyUtils#setProperty() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: UKResultMapper.java    From youkefu with Apache License 2.0 6 votes vote down vote up
public <T> T mapEntity(String source , SearchHit hit , Class<T> clazz) {
	T t = mapEntity(source , clazz) ;
	
	Map<String, HighlightField> highlightFields = hit.getHighlightFields();
	HighlightField highlightNameField = highlightFields.get("title");
	HighlightField contentHightlightField = highlightFields.get("content");
	try {
		if(highlightNameField!=null&&highlightNameField.fragments()!=null){
			PropertyUtils.setProperty(t, "title" , highlightNameField.fragments()[0].string());
		}
		if(contentHightlightField!=null){
			PropertyUtils.setProperty(t, "content" , contentHightlightField.fragments()[0].string());
		}
		PropertyUtils.setProperty(t, "id" , hit.getId());
	} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
		e.printStackTrace();
	} 
	return t;
}
 
Example 2
Source File: EntityManagerContainer.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
public <T extends JpaObject, W extends GsonPropertyObject> List<T> fetchDescPaging(Class<T> clz,
		List<String> fetchAttributes, Predicate predicate, Integer page, Integer pageSize, String orderAttribute)
		throws Exception {
	List<T> list = new ArrayList<>();
	int max = (pageSize == null || pageSize < 1 || pageSize > MAX_PAGESIZE) ? DEFAULT_PAGESIZE : pageSize;
	int startPosition = (page == null || page < 1) ? 0 : (page - 1) * max;
	List<String> fields = ListTools.trim(fetchAttributes, true, true, JpaObject.id_FIELDNAME);
	EntityManager em = this.get(clz);
	CriteriaBuilder cb = em.getCriteriaBuilder();
	CriteriaQuery<Tuple> cq = cb.createQuery(Tuple.class);
	Root<T> root = cq.from(clz);
	List<Selection<?>> selections = new ArrayList<>();
	for (String str : fields) {
		selections.add(root.get(str));
	}
	cq.multiselect(selections).where(predicate).orderBy(cb.desc(root.get(orderAttribute)));
	T t = null;
	for (Tuple o : em.createQuery(cq).setFirstResult(startPosition).setMaxResults(max).getResultList()) {
		t = clz.newInstance();
		for (int i = 0; i < fields.size(); i++) {
			PropertyUtils.setProperty(t, fields.get(i), o.get(selections.get(i)));
		}
		list.add(t);
	}
	return list;
}
 
Example 3
Source File: OptJTextAreaBinding.java    From beast-mcmc with GNU Lesser General Public License v2.1 6 votes vote down vote up
public void get(IValidatable bean) {
	try {
		String text = _textArea.getText();

		if (_button.isSelected() && !text.equals("")) {
			String[] items = text.split("\n");
			List<Object> list = new ArrayList<Object>();

			for (String s : items) {
				list.add(s);
			}

			PropertyUtils.setProperty(bean, _property, list);
		} else {
			PropertyUtils.setProperty(bean, _property, null);
		}
	} catch (Exception e) {
		throw new BindingException(e);
	}
}
 
Example 4
Source File: ListTools.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T> List<T> addWithProperty(Object obj, String propertyName, boolean ignoreNull, List<T> ts)
		throws Exception {
	List<T> list = new ArrayList<>();
	ListOrderedSet<T> set = new ListOrderedSet<T>();
	Object o = PropertyUtils.getProperty(obj, propertyName);
	if (null != o) {
		set.addAll((List<T>) o);
	}
	if (null != ts) {
		for (T t : ts) {
			if (null == t && ignoreNull) {
				continue;
			}
			if (!set.contains(t)) {
				set.add(t);
				list.add(t);
			}
		}
	}
	PropertyUtils.setProperty(obj, propertyName, set.asList());
	return list;
}
 
Example 5
Source File: ListTools.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T> List<T> addWithProperty(Object obj, String propertyName, boolean ignoreNull, T... ts)
		throws Exception {
	List<T> list = new ArrayList<>();
	ListOrderedSet<T> set = new ListOrderedSet<T>();
	Object o = PropertyUtils.getProperty(obj, propertyName);
	if (null != o) {
		set.addAll((List<T>) o);
	}
	for (T t : ts) {
		if (null == t && ignoreNull) {
			continue;
		}
		if (!set.contains(t)) {
			set.add(t);
			list.add(t);
		}
	}
	PropertyUtils.setProperty(obj, propertyName, set.asList());
	return list;
}
 
Example 6
Source File: JTextAreaBinding.java    From PyramidShader with GNU General Public License v3.0 6 votes vote down vote up
public void get(IValidatable bean) {
	try {
		String text = _textArea.getText();

		if (!text.equals("")) {
			String[] items = text.split("\n");
			List<Object> list = new ArrayList<Object>();

			for (int i = 0; i < items.length; i++) {
				list.add(items[i]);
			}

			PropertyUtils.setProperty(bean, _property, list);
		} else {
			PropertyUtils.setProperty(bean, _property, null);
		}
	} catch (Exception e) {
		throw new BindingException(e);
	}
}
 
Example 7
Source File: PersistableHelper.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
public void createPersistableFields(Persistable persistable)
{
	Date now = new Date(); // time sensitive
	if (log.isDebugEnabled())
	{
		log.debug("modifyPersistableFields(Persistable " + persistable + ")");
	}
	if (persistable == null) throw new IllegalArgumentException("Illegal persistable argument passed!");

	try
	{
		String actor = getActor();

		PropertyUtils.setProperty(persistable, LASTMODIFIEDBY, actor);
		PropertyUtils.setProperty(persistable, LASTMODIFIEDDATE, now);
		PropertyUtils.setProperty(persistable, CREATEDBY, actor);
		PropertyUtils.setProperty(persistable, CREATEDDATE, now);
	}
	catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e)
	{
		log.error(e.getMessage());
		throw new RuntimeException(e);
	}
}
 
Example 8
Source File: JTextAreaBinding.java    From beast-mcmc with GNU Lesser General Public License v2.1 6 votes vote down vote up
public void get(IValidatable bean) {
	try {
		String text = _textArea.getText();

		if (!text.equals("")) {
			String[] items = text.split("\n");
			List<Object> list = new ArrayList<Object>();

			for (int i = 0; i < items.length; i++) {
				list.add(items[i]);
			}

			PropertyUtils.setProperty(bean, _property, list);
		} else {
			PropertyUtils.setProperty(bean, _property, null);
		}
	} catch (Exception e) {
		throw new BindingException(e);
	}
}
 
Example 9
Source File: HighlightResultHelper.java    From mogu_blog_v2 with Apache License 2.0 6 votes vote down vote up
@Override
public <T> T mapSearchHit(SearchHit searchHit, Class<T> clazz) {
    List<T> results = new ArrayList<>();
    for (HighlightField field : searchHit.getHighlightFields().values()) {
        T result = null;
        if (StringUtils.hasText(searchHit.getSourceAsString())) {
            result = JSONObject.parseObject(searchHit.getSourceAsString(), clazz);
        }
        try {
            PropertyUtils.setProperty(result, field.getName(), concat(field.fragments()));
        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            log.error("设置高亮字段异常:{}", e.getMessage(), e);
        }
        results.add(result);
    }
    return null;
}
 
Example 10
Source File: EntityManagerContainer.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
public <T extends JpaObject> List<T> fetchEqual(Class<T> clz, List<String> attributes, String attribute,
		Object value) throws Exception {
	List<T> list = new ArrayList<>();
	List<String> fields = ListTools.trim(attributes, true, true, JpaObject.id_FIELDNAME);
	EntityManager em = this.get(clz);
	CriteriaBuilder cb = em.getCriteriaBuilder();
	CriteriaQuery<Tuple> cq = cb.createQuery(Tuple.class);
	Root<T> root = cq.from(clz);
	List<Selection<?>> selections = new ArrayList<>();
	for (String str : fields) {
		selections.add(root.get(str));
	}
	Predicate p = cb.equal(root.get(attribute), value);
	cq.multiselect(selections).where(p);
	for (Tuple o : em.createQuery(cq).getResultList()) {
		T t = clz.newInstance();
		for (int i = 0; i < fields.size(); i++) {
			PropertyUtils.setProperty(t, fields.get(i), o.get(selections.get(i)));
		}
		list.add(t);
	}
	return list;
}
 
Example 11
Source File: MappingFactory.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
private static void integerListValue(Data data, String path, JpaObject jpaObject, String property)
		throws Exception {
	List<Integer> os = new ArrayList<>();
	Object obj = data.find(path);
	if (null != obj) {
		if (ListTools.isList(obj)) {
			for (Object o : (List<?>) obj) {
				if (NumberUtils.isCreatable(o.toString())) {
					os.add(NumberUtils.createInteger(o.toString()));
				}
			}
		} else {
			if (NumberUtils.isCreatable(obj.toString())) {
				os.add(NumberUtils.createInteger(obj.toString()));
			}
		}
	}
	PropertyUtils.setProperty(jpaObject, property, os);
}
 
Example 12
Source File: ProjectionFactory.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
private static void timeValue(Data data, String path, JpaObject jpaObject, String property) throws Exception {
	Object obj = data.find(path);
	if ((null != obj) && DateTools.isDateTimeOrTime(obj.toString())) {
		PropertyUtils.setProperty(jpaObject, property, DateTools.parse(obj.toString()));
	} else {
		PropertyUtils.setProperty(jpaObject, property, null);
	}
}
 
Example 13
Source File: ObjectUtil.java    From PeonyFramwork with Apache License 2.0 5 votes vote down vote up
/**
 * 设置成员变量
 */
public static void setField(Object obj, String fieldName, Object fieldValue) {
    try {
        if (PropertyUtils.isWriteable(obj, fieldName)) {
            PropertyUtils.setProperty(obj, fieldName, fieldValue);
        }
    } catch (Exception e) {
        logger.error("设置成员变量出错!", e);
        throw new RuntimeException(e);
    }
}
 
Example 14
Source File: MappingFactory.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
private static void integerValue(Data data, String path, JpaObject jpaObject, String property) throws Exception {
	Object obj = data.find(path);
	if (null == obj) {
		PropertyUtils.setProperty(jpaObject, property, null);
	} else {
		if (Number.class.isAssignableFrom(obj.getClass())) {
			PropertyUtils.setProperty(jpaObject, property, ((Number) obj).intValue());
		} else {
			String str = Objects.toString(obj);
			if (NumberUtils.isCreatable(str)) {
				PropertyUtils.setProperty(jpaObject, property, NumberUtils.createInteger(str));
			}
		}
	}
}
 
Example 15
Source File: ProjectionFactory.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
private static void stringMapValue(Data data, String path, JpaObject jpaObject, String property) throws Exception {
	Object obj = data.find(path);
	Map<String, String> map = new TreeMap<String, String>();
	if ((null != obj) && (Map.class.isAssignableFrom(obj.getClass()))) {
		for (Entry<?, ?> en : ((Map<?, ?>) obj).entrySet()) {
			map.put(Objects.toString(en.getKey(), ""), Objects.toString(en.getValue(), ""));
		}
	}
	PropertyUtils.setProperty(jpaObject, property, map);
}
 
Example 16
Source File: MappingFactory.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
private static void stringListValue(Data data, String path, JpaObject jpaObject, String property) throws Exception {
	List<String> os = new ArrayList<>();
	Object obj = data.find(path);
	if (null != obj) {
		if (ListTools.isList(obj)) {
			for (Object o : (List<?>) obj) {
				os.add(o.toString());
			}
		} else {
			os.add(obj.toString());
		}
	}
	PropertyUtils.setProperty(jpaObject, property, os);
}
 
Example 17
Source File: JListBinding.java    From jmkvpropedit with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void get(IValidatable bean) {
	try {
		DefaultListModel model = (DefaultListModel) _list.getModel();
		final int size = model.getSize();
		List<Object> list = new ArrayList<Object>(size);

		for (int i = 0; i < size; i++) {
			list.add(model.get(i));
		}

		PropertyUtils.setProperty(bean, _property, list);
	} catch (Exception e) {
		throw new BindingException(e);
	}
}
 
Example 18
Source File: MappingFactory.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
private static void doubleValue(Data data, String path, JpaObject jpaObject, String property) throws Exception {
	Object obj = data.find(path);
	if (null == obj) {
		PropertyUtils.setProperty(jpaObject, property, null);
	} else {
		if (Number.class.isAssignableFrom(obj.getClass())) {
			PropertyUtils.setProperty(jpaObject, property, ((Number) obj).doubleValue());
		} else {
			String str = Objects.toString(obj);
			if (NumberUtils.isCreatable(str)) {
				PropertyUtils.setProperty(jpaObject, property, NumberUtils.createDouble(str));
			}
		}
	}
}
 
Example 19
Source File: FlatFileParseTrackerImpl.java    From kfs with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Called when a line has completed parsing. Throws an exception if a proper parent
 * is not found for the line being parsed
 */
@Override
   @SuppressWarnings("unchecked")
public void completeLineParse() {
	completedLineCount += 1;
	if (LOG.isDebugEnabled()) {
		LOG.debug("Completing parse of line: "+completedLineCount);
	}

	Object currentObject = parseStack.pop();
	final FlatFileChildMapEntry entry = getEntryForParsedIntoObject(currentObject);

	final Class<?> parentClass = (entry == null) ? null : entry.getParentBeanClass();
	final String propertyName = (entry == null) ? null : entry.getPropertyName();

	while (!parseStack.isEmpty()) {
		Object checkingObject = parseStack.pop();
		if (parentClass != null && parentClass.isAssignableFrom(checkingObject.getClass())) {
			try {
				if (Collection.class.isAssignableFrom(PropertyUtils.getPropertyType(
						checkingObject, propertyName))) {
					Collection childrenList = ((Collection) PropertyUtils.getProperty(
							checkingObject, propertyName));
					childrenList.add(currentObject);
				} else {
					PropertyUtils.setProperty(checkingObject, propertyName,currentObject);
				}
				parseStack.push(checkingObject);
				parseStack.push(currentObject);
				return;
			} catch (Exception e) {
				LOG.error(e.getMessage() + "occured when completing line parse; attempting to set object of type "+currentObject.getClass().getName()+" to the following parent: "+parentClass.getName()+"#"+propertyName, e);
				throw new RuntimeException(e.getMessage() + "occured when completing line parse; attempting to set object of type "+currentObject.getClass().getName()+" to the following parent: "+parentClass.getName()+"#"+propertyName,e);
			}
		}
	}
	if (parentClass == null) {
		parseStack.push(currentObject);
		parsedParentObjects.add(currentObject);
	} else {
		throw new IllegalStateException("A line of class "+currentObject.getClass().getName()+" cannot exist without a proper parent");
	}
}
 
Example 20
Source File: PropertyUtil.java    From feilong-core with Apache License 2.0 3 votes vote down vote up
/**
 * 使用 {@link PropertyUtils#setProperty(Object, String, Object)} 来设置指定bean对象中的指定属性的值.
 * 
 * <h3>说明:</h3>
 * <blockquote>
 * <ol>
 * <li>不会进行类型转换</li>
 * </ol>
 * </blockquote>
 * 
 * <h3>示例:</h3>
 * 
 * <blockquote>
 * 
 * <pre class="code">
 * User newUser = new User();
 * PropertyUtil.setProperty(newUser, "name", "feilong");
 * LOGGER.info(JsonUtil.format(newUser));
 * </pre>
 * 
 * <b>返回:</b>
 * 
 * <pre class="code">
 * {
 * "age": 0,
 * "name": "feilong"
 * }
 * </pre>
 * 
 * </blockquote>
 * 
 * <h3>注意点:</h3>
 * 
 * <blockquote>
 * 
 * <ol>
 * <li>如果 <code>bean</code> 是null,抛出 {@link NullPointerException}</li>
 * <li>如果 <code>propertyName</code> 是null,抛出 {@link NullPointerException}</li>
 * <li>如果 <code>propertyName</code> 是blank,抛出 {@link IllegalArgumentException}</li>
 * <li>如果<code>bean</code>没有传入的 <code>propertyName</code>属性名字,会抛出异常,see
 * {@link PropertyUtilsBean#setSimpleProperty(Object, String, Object) setSimpleProperty} Line2078,转成 {@link BeanOperationException}</li>
 * <li>对于Date类型,<span style="color:red">不需要先注册converter</span></li>
 * </ol>
 * </blockquote>
 *
 * @param bean
 *            Bean whose property is to be modified
 * @param propertyName
 *            属性名称 (can be nested/indexed/mapped/combo),参见 <a href="../BeanUtil.html#propertyName">propertyName</a>
 * @param value
 *            Value to which this property is to be set
 * @see org.apache.commons.beanutils.BeanUtils#setProperty(Object, String, Object)
 * @see org.apache.commons.beanutils.PropertyUtils#setProperty(Object, String, Object)
 * @see BeanUtil#setProperty(Object, String, Object)
 */
public static void setProperty(Object bean,String propertyName,Object value){
    Validate.notNull(bean, MESSAGE_BEAN_IS_NULL);
    Validate.notBlank(propertyName, MESSAGE_PROPERTYNAME_IS_BLANK);

    //---------------------------------------------------------------
    try{
        PropertyUtils.setProperty(bean, propertyName, value);
    }catch (Exception e){
        String pattern = "setProperty exception,bean:[{}],propertyName:[{}],value:[{}]";
        throw new BeanOperationException(Slf4jUtil.format(pattern, bean, propertyName, value), e);
    }
}