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

The following examples show how to use org.apache.commons.beanutils.BeanUtils#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: CamsFixture.java    From kfs with GNU Affero General Public License v3.0 7 votes vote down vote up
public <T> T buildTestDataObject(Class<? extends T> clazz, Properties properties, String propertyKey, String fieldNames, String delimiter) {
    T object;
    try {
        object = clazz.newInstance();
        String[] fields = fieldNames.split(delimiter, -1);
        String[] values = properties.getProperty(propertyKey).split(delimiter, -1);
        int pos = -1;
        for (String field : fields) {
            pos++;
            BeanUtils.setProperty(object, field, values[pos]);
        }
    }
    catch (Exception e) {
        throw new RuntimeException(e);
    }
    return object;
}
 
Example 2
Source File: JTextComponentBinding.java    From beast-mcmc with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void get(IValidatable bean) {
	try {
		BeanUtils.setProperty(bean, _property, _textComponent.getText());
	} catch (Exception e) {
		throw new BindingException(e);
	}
}
 
Example 3
Source File: TransformedPropertyRule.java    From jasperreports with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void begin(String namespace, String name, Attributes attributes)
		throws Exception
{
	String attrValue = attributes.getValue(attributeName);
	if (attrValue != null)
	{
		Object value = toPropertyValue(attrValue);
		if (value != null)
		{
			Object top = digester.peek();
			
			if (log.isDebugEnabled())
			{
				log.debug("Setting property " + propertyName + " on " + top
						+ " to " + value + " from attribute \"" + attrValue + "\"");
			}
			
			BeanUtils.setProperty(top, propertyName, value);
		}
		else
		{
			if (log.isDebugEnabled())
			{
				log.debug("Attribute value " + attrValue 
						+ " resulted in null property value, not setting");
			}
		}
	}
}
 
Example 4
Source File: StorageConverter.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * Creates the FileSystemHandler and set all its properties.
 * Will also call the init method if it exists.
 */
private static FileSystemHandler getFileSystemHandler(Properties p, String fileSystemHandlerName) throws ClassNotFoundException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException{
    String clazz = p.getProperty(fileSystemHandlerName);
    log.info("Building FileSystemHandler: " + clazz);
    Class<? extends FileSystemHandler> fshClass = Class.forName(clazz).asSubclass(FileSystemHandler.class);
    FileSystemHandler fsh = fshClass.newInstance();

    Enumeration<String> propertyNames = (Enumeration<String>) p.propertyNames();
    while (propertyNames.hasMoreElements()) {
        String fullProperty = propertyNames.nextElement();
        if (fullProperty.startsWith(fileSystemHandlerName + ".")) {
            String property = fullProperty.substring(fullProperty.indexOf(".")+1);
            log.info("Setting property: " + property);
            BeanUtils.setProperty(fsh, property, p.getProperty(fullProperty));
        }
    }

    try {
        log.info("Check if there is a init method...");
        MethodUtils.invokeExactMethod(fsh, "init", (Object[])null);
        log.info("init method invoked...");
    } catch (NoSuchMethodException e) {
        log.info("No init method...");
    }
    log.info("Done with FileSystemHandler: " + clazz);
    return fsh;
}
 
Example 5
Source File: ServiceActions.java    From sailfish-core with Apache License 2.0 5 votes vote down vote up
@CommonColumns(@CommonColumn(value = Column.ServiceName, required = true))
@ActionMethod
   public void initService(IActionContext actionContext, HashMap<?, ?> message) throws IllegalAccessException, InvocationTargetException, InterruptedException, IOException {
	ServiceName serviceName = ServiceName.parse(actionContext.getServiceName());
	IActionServiceManager serviceManager = actionContext.getServiceManager();

	try {
           IServiceSettings serviceSettings = serviceManager.getServiceSettings(serviceName);
		BeanMap beanMap = new BeanMap(serviceSettings);
		Set<String> editedProperty = new HashSet<>();
		Set<String> incorrectProperty = new HashSet<>();
		for (Entry<?, ?> entry : message.entrySet()) {
			String property = convertProperty(entry.getKey().toString());
			if (beanMap.containsKey(property)){
				BeanUtils.setProperty(serviceSettings, property, converter.get().convert((Object)unwrapFilters(entry.getValue()), beanMap.getType(property)));
                   editedProperty.add(property);
			} else {
				incorrectProperty.add(property);
			}
		}

		if (!incorrectProperty.isEmpty()) {
			throw new EPSCommonException(serviceSettings.getClass().getName() + " does not contain properties: " + incorrectProperty);
		}

           serviceManager.updateService(serviceName, serviceSettings, null).get();

		try (FileOutputStream out = new FileOutputStream(actionContext.getReport().createFile(StatusType.NA, servicesFolder, changingSettingFolder, serviceName + FORMATTER.format(DateTimeUtility.nowLocalDateTime()) + servicesFileExpression))) {
               actionContext.getServiceManager().serializeServiceSettings(serviceName, out);
           }
       } catch (ExecutionException e) {
           ExceptionUtils.rethrow(ObjectUtils.defaultIfNull(e.getCause(), e));
       }
}
 
Example 6
Source File: EMailServiceSettings.java    From sailfish-core with Apache License 2.0 5 votes vote down vote up
@Override
public void fillFromMap(Map<String, String> options) throws Exception {
    for(Entry<String, String> entry : options.entrySet()) {
        if(entry.getKey().startsWith(STORAGE_PREFIX)) {
            BeanUtils.setProperty(this, entry.getKey().replace(STORAGE_PREFIX, ""), entry.getValue());
        }
    }
    this.serviceEnabled = BooleanUtils.toBoolean(ObjectUtils.defaultIfNull(options.get(ENABLED_KEY), "true"));
}
 
Example 7
Source File: ServiceStorageHelper.java    From sailfish-core with Apache License 2.0 5 votes vote down vote up
public static void convertMapToServiceSettings(IServiceSettings serviceSettings, Map<String, String> params) {
    ConvertUtilsBean converter = new ConvertUtilsBean();
    PropertyUtilsBean beanUtils = new PropertyUtilsBean();
    PropertyDescriptor[] descriptors = beanUtils.getPropertyDescriptors(serviceSettings);

    converter.register(new SailfishURIConverter(), SailfishURI.class);
    converter.register(true, false, 0);

    for(PropertyDescriptor descriptor : descriptors) {
        if(descriptor.getWriteMethod() == null) {
            continue;
        }

        String name = descriptor.getName();
        String value = params.get(name);

        if(value == null) {
            continue;
        }

        try {
            BeanUtils.setProperty(serviceSettings, name, converter.convert(value, descriptor.getPropertyType()));
        } catch(Exception e) {
            throw new EPSCommonException(String.format("Failed to set setting '%s' to: %s", name, value), e);
        }
    }
}
 
Example 8
Source File: JSONHelper.java    From jeewx-api with Apache License 2.0 5 votes vote down vote up
/***
 * 将JSON文本反序列化为主从关系的实体
 * 
 * @param <T>
 *            主实体类型
 * @param jsonString
 *            JSON文本
 * @param mainClass
 *            主实体类型
 * @param detailClass
 *            存放了多个从实体在主实体中属性名称和类型
 * @return
 */
public static <T> T toBean(String jsonString, Class<T> mainClass,
		HashMap<String, Class> detailClass) {
	JSONObject jsonObject = JSONObject.fromObject(jsonString);
	T mainEntity = JSONHelper.toBean(jsonObject, mainClass);
	for (Object key : detailClass.keySet()) {
		try {
			Class value = (Class) detailClass.get(key);
			BeanUtils.setProperty(mainEntity, key.toString(), value);
		} catch (Exception ex) {
			throw new RuntimeException("主从关系JSON反序列化实体失败!");
		}
	}
	return mainEntity;
}
 
Example 9
Source File: AbstractParameterizablePlugin.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Parses the arguments and injects values into the beans via properties.
 */
public int parseArgument(Options opt, String[] args, int start)
		throws BadCommandLineException, IOException {

	int consumed = 0;
	final String optionPrefix = "-" + getOptionName() + "-";
	final int optionPrefixLength = optionPrefix.length();

	final String arg = args[start];
	final int equalsPosition = arg.indexOf('=');

	if (arg.startsWith(optionPrefix) && equalsPosition > optionPrefixLength) {
		final String propertyName = arg.substring(optionPrefixLength,
				equalsPosition);

		final String value = arg.substring(equalsPosition + 1);
		consumed++;
		try {
			BeanUtils.setProperty(this, propertyName, value);
		} catch (Exception ex) {
			ex.printStackTrace();
			throw new BadCommandLineException("Error setting property ["
					+ propertyName + "], value [" + value + "].");
		}
	}
	return consumed;
}
 
Example 10
Source File: PropertiesParser.java    From haven-platform with Apache License 2.0 5 votes vote down vote up
public void parse(Map<String, Object> map, ContainerSource arg) {
    for (Map.Entry<String, Object> el : map.entrySet()) {
        String propKey = el.getKey();
        Object elValue = el.getValue();
        if (elValue instanceof String) {
            String val = (String) elValue;
            String[] split = StringUtils.split(propKey, ".");
            if (split != null && StringUtils.hasText(val)) {
                String key = split[1];
                switch (split[0]) {
                    case ENV:
                        arg.getEnvironment().add(key + "=" + val);
                        break;
                    case LABELS:
                        arg.getLabels().put(key, val);
                        break;
                }
            } else {
                try {
                    Object value;
                    if (val.contains(":")) {
                        value = parseMap(val);
                    } else if (val.contains(",")) {
                        value = parseList(val);
                    } else {
                        value = el.getValue();
                    }
                    BeanUtils.setProperty(arg, propKey, value);
                } catch (Exception e) {
                    log.error("can't set value {} to property {}", propKey, el.getValue(), e);
                }
            }
        }
    }
    log.info("Result of parsing {}", arg);
}
 
Example 11
Source File: FdfsParamMapper.java    From FastDFS_Client with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 按列顺序映射
 *
 * @param content
 * @param genericType
 * @param objectMap
 * @return
 * @throws InstantiationException
 * @throws IllegalAccessException
 * @throws InvocationTargetException
 */
private static <T> T mapByIndex(byte[] content, Class<T> genericType, ObjectMetaData objectMap, Charset charset)
        throws InstantiationException, IllegalAccessException, InvocationTargetException {

    List<FieldMetaData> mappingFields = objectMap.getFieldList();
    T obj = genericType.newInstance();
    for (int i = 0; i < mappingFields.size(); i++) {
        FieldMetaData field = mappingFields.get(i);
        // 设置属性值
        LOGGER.debug("设置值是 " + field + field.getValue(content, charset));
        BeanUtils.setProperty(obj, field.getFieldName(), field.getValue(content, charset));
    }

    return obj;
}
 
Example 12
Source File: ApexStreamImpl.java    From attic-apex-malhar with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public ApexStream<T> with(String propName, Object value)
{
  try {
    BeanUtils.setProperty(lastBrick.nodeMeta.getOperator(), propName, value);
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
  return this;
}
 
Example 13
Source File: SqlBuilder.java    From mybatis.flying with Apache License 2.0 5 votes vote down vote up
private static void handleInsertSql(KeyHandler keyHandler, StringBuilder valueSql, FieldMapper fieldMapper,
		Object object, boolean uniqueKeyHandled, Integer batchIndex)
		throws IllegalAccessException, NoSuchFieldException, InvocationTargetException {
	if (!uniqueKeyHandled) {
		valueSql.append(POUND_OPENBRACE);
		if (batchIndex != null) {
			valueSql.append("collection[" + batchIndex + "].");
		}
		valueSql.append(fieldMapper.getFieldName()).append(COMMA).append(JDBCTYPE_EQUAL)
				.append(fieldMapper.getJdbcType()).append(CLOSEBRACE_COMMA);
	}
	BeanUtils.setProperty(object, fieldMapper.getFieldName(), keyHandler.getKey());
}
 
Example 14
Source File: JstlFunctions.java    From kfs with GNU Affero General Public License v3.0 5 votes vote down vote up
private static void addParametersToFinder(Map<String, Object> params, KeyValuesFinder finder) {
        if (finder != null && params != null) {
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                try {
                    BeanUtils.setProperty(finder, entry.getKey(), entry.getValue());
//                    setProperty(finder, entry.getKey(), entry.getValue());
                } catch (Exception e) {
                    warn(PROPERTY_SETTING_EXC_PROLOG + entry.getKey(), e);
                    e.printStackTrace();
                }
            }
        }
    }
 
Example 15
Source File: ApiDocTool.java    From nuls-v2 with MIT License 5 votes vote down vote up
private static Object newInstance(Class cls) throws IllegalAccessException, InstantiationException, InvocationTargetException {
    Object o = cls.newInstance();
    Field[] fields = cls.getDeclaredFields();
    for(Field field : fields) {
        if(!baseType.contains(field.getType())) {
            Object o1;
            if(field.getType() == List.class) {
                o1 = new ArrayList<>();
                List o2 = (List) o1;
                ApiModelProperty apiModelProperty = field.getAnnotation(ApiModelProperty.class);
                if(apiModelProperty != null) {
                    Class<?> element = apiModelProperty.type().collectionElement();
                    if(!baseType.contains(element)) {
                        o2.add(newInstance(element));
                    }
                }
            } else if(field.getType() == Map.class) {
                o1 = new HashMap<>();
            } else if(field.getType() == Set.class) {
                o1 = new HashSet<>();
            } else if(field.getType().isArray()) {
                o1 = Array.newInstance(field.getType(), 0);
            } else {
                o1 = field.getType().newInstance();

            }
            BeanUtils.setProperty(o, field.getName(), o1);
        }
    }
    return o;
}
 
Example 16
Source File: Utils.java    From urule with Apache License 2.0 5 votes vote down vote up
public static void setObjectProperty(Object object,String property,Object value){
	try {
		BeanUtils.setProperty(object, property, value);
	} catch (Exception e) {
		throw new RuleException(e);
	}
}
 
Example 17
Source File: ListConverter.java    From airtable.java with MIT License 5 votes vote down vote up
/**
 *
 * Convert the Input Object into a List of Attachements
 *
 * This Method handles the conversion from a List of LinkedHashMaps to a
 * List of Attachement Objects.
 *
 * <p>
 * If the Input Object is no List or the List Item is no LinkedHashMap
 * everything will be converted into a (List?) String.</p>
 *
 * @param type The type of the Input Object
 * @param value The value of the Input Object
 * @return A List
 * @throws java.lang.InstantiationException If no Instance of the listClass
 * can be instantiated
 * @throws java.lang.IllegalAccessException If the Object can't be accest
 * @throws java.lang.reflect.InvocationTargetException If th Target can't be
 * accessed
 */
@Override
protected <T> T convertToType(final Class<T> type, Object value) throws InstantiationException, IllegalAccessException, InvocationTargetException {

    if (listClass == null) {
        throw new IllegalAccessException("listClass is not initialized by setListClass().");
    }

    List<T> returnList = new ArrayList<>();

    if (value instanceof List) {
        for (T item : ((List<T>) value)) {
            if (item instanceof LinkedTreeMap) {
                Object instanz = listClass.newInstance();
                for (String key : ((LinkedTreeMap<String, Object>) item).keySet()) {
                    Object val = ((LinkedTreeMap) item).get(key);
                    BeanUtils.setProperty(instanz, key, val);
                }
                returnList = toClassList(item.getClass(), instanz, returnList);
            }
            if (item instanceof String) {
                returnList = toStringList(item.getClass(), item.toString(), returnList);
            }

        }
        return (T) returnList;
    }

    //TODO überarbeiten
    if (value instanceof String) {
        return (T) toStringList(value.getClass(), value.toString(), returnList);
    }

    final String stringValue = value.toString().trim();
    if (stringValue.length() == 0) {
        return handleMissing(type);
    }

    return (T) toStringList(value.getClass(), stringValue, returnList);
}
 
Example 18
Source File: RegexParser.java    From attic-apex-malhar with Apache License 2.0 4 votes vote down vote up
@Override
public void processTuple(byte[] tuple)
{
  if (tuple == null) {
    if (err.isConnected()) {
      err.emit(new KeyValPair<String, String>(null, "Blank/null tuple"));
    }
    errorTupleCount++;
    return;
  }
  String incomingString = new String(tuple);
  if (StringUtils.isBlank(incomingString)) {
    if (err.isConnected()) {
      err.emit(new KeyValPair<String, String>(incomingString, "Blank tuple"));
    }
    errorTupleCount++;
    return;
  }
  try {
    if (out.isConnected() && clazz != null) {
      Matcher matcher = pattern.matcher(incomingString);
      boolean patternMatched = false;
      Constructor<?> ctor = clazz.getConstructor();
      Object object = ctor.newInstance();

      if (matcher.find()) {
        for (int i = 0; i <= matcher.groupCount() - 1; i++) {
          if (delimitedParserSchema.getFields().get(i).getType() == DelimitedSchema.FieldType.DATE) {
            DateTimeConverter dtConverter = new DateConverter();
            dtConverter.setPattern((String)delimitedParserSchema.getFields().get(i).getConstraints().get(DelimitedSchema.DATE_FORMAT));
            ConvertUtils.register(dtConverter, Date.class);
          }
          BeanUtils.setProperty(object, delimitedParserSchema.getFields().get(i).getName(), matcher.group(i + 1));
        }
        patternMatched = true;
      }
      if (!patternMatched) {
        throw new ConversionException("The incoming tuple do not match with the Regex pattern defined.");
      }

      out.emit(object);
      emittedObjectCount++;
    }

  } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException | InstantiationException | ConversionException e) {
    if (err.isConnected()) {
      err.emit(new KeyValPair<String, String>(incomingString, e.getMessage()));
      logger.debug("Regex Expression : {} Incoming tuple : {}", splitRegexPattern, incomingString);
    }
    errorTupleCount++;
    logger.error("Tuple could not be parsed. Reason {}", e.getMessage());
  }
}
 
Example 19
Source File: JSONHelper.java    From jeewx-api with Apache License 2.0 4 votes vote down vote up
/***
 * 将JSON文本反序列化为主从关系的实体
 * 
 * @param <T>
 *            泛型T 代表主实体类型
 * @param <D>
 *            泛型D 代表从实体类型
 * @param jsonString
 *            JSON文本
 * @param mainClass
 *            主实体类型
 * @param detailName
 *            从实体类在主实体类中的属性名称
 * @param detailClass
 *            从实体类型
 * @return
 */
public static <T, D> T toBean(String jsonString, Class<T> mainClass,
		String detailName, Class<D> detailClass) {
	JSONObject jsonObject = JSONObject.fromObject(jsonString);
	JSONArray jsonArray = (JSONArray) jsonObject.get(detailName);

	T mainEntity = JSONHelper.toBean(jsonObject, mainClass);
	List<D> detailList = JSONHelper.toList(jsonArray, detailClass);

	try {
		BeanUtils.setProperty(mainEntity, detailName, detailList);
	} catch (Exception ex) {
		throw new RuntimeException("主从关系JSON反序列化实体失败!");
	}

	return mainEntity;
}
 
Example 20
Source File: HibernateStorageSettings.java    From sailfish-core with Apache License 2.0 3 votes vote down vote up
public void fillFromMap(Map<String, String> options) throws Exception {

        for(Entry<String, String> entry : options.entrySet()) {
            
            if(entry.getKey().startsWith(storagePrefix)) {
                
                BeanUtils.setProperty(this, entry.getKey().replace(storagePrefix, ""), entry.getValue());
                
            }
            
        }
        
    }