Java Code Examples for org.apache.commons.beanutils.BeanUtils

The following examples show how to use org.apache.commons.beanutils.BeanUtils. These examples are extracted from open source projects. 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 Project: kfs   Source File: CamsFixture.java    License: 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
/**
 * @return a cloned instance of this object.
 */
@Nonnull
public DatabaseInfo instance()
{
    final DatabaseInfo cloned = new DatabaseInfo();
    try
    {
        BeanUtils.copyProperties( cloned, this );
    }
    catch ( IllegalAccessException | InvocationTargetException e )
    {
        throw new IllegalStateException( e );
    }

    return cloned;
}
 
Example 3
/**
 * Reset unchecked html form checkboxes while working in a strutsaction.
 * Somehow "setUnselectedCheckboxProperties" didn't work because request parameters were empty back there.
 */
public void setUnselectedCheckboxPropertiesInAction(HttpServletRequest request) {
	Enumeration<String> names = request.getParameterNames();
	while (names.hasMoreElements()) {
		String name = names.nextElement();

		try {
			if (name.startsWith(STRUTS_CHECKBOX) && name.length() > STRUTS_CHECKBOX.length()) {
				String propertyName = name.substring(STRUTS_CHECKBOX.length());

				String value = request.getParameter(name);
				if (request.getParameter(propertyName) == null && value != null) {
					BeanUtils.setProperty(this, propertyName, value);
				}
			}
		} catch (Exception e) {
			logger.error("reset: " + e.getMessage());
		}
	}
}
 
Example 4
@Override
public void reset(ActionMapping mapping, HttpServletRequest request) {
	super.reset(mapping, request);
	String aCBox;
	String name;
	String value;
	this.intelliAdShown = false;
	this.staticLink = false;

	Enumeration<String> names = request.getParameterNames();
	while (names.hasMoreElements()) {
		name = names.nextElement();
		if (name.startsWith(STRUTS_CHECKBOX) && name.length() > 18) {
			aCBox = name.substring(18);
			try {
				if ((value = request.getParameter(name)) != null) {
					BeanUtils.setProperty(this, aCBox, value);
				}
			} catch (Exception e) {
				logger.error("reset: " + e.getMessage());
			}
		}
	}
}
 
Example 5
private void includeActionProperties(ActionLogRecord actionRecord, Object action) {
    if (StringUtils.isEmpty(this.getIncludeActionProperties())) {
        return;
    }
    String[] propertyToInclude = this.getIncludeActionProperties().split(",");
    StringBuilder params = new StringBuilder(actionRecord.getParameters());
    for (String property : propertyToInclude) {
        try {
            Object value = BeanUtils.getProperty(action, property);
            if (null != value) {
                params.append(property).append("=").append(value.toString());
                params.append("\n");
            }
        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException ex) {
            _logger.debug("Error extracting property " + property + " from action", ex);
        }
    }
    actionRecord.setParameters(params.toString());
}
 
Example 6
Source Project: wechat-core   Source File: BeanTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testMap2Bean() throws Exception {
    Map<String, Object> map = Maps.newHashMap();
    map.put("Username", "jonnyliu");
    map.put("Age", 39);
    User user = new User();
    Map map1 = Maps.newHashMap();
    map.forEach((x, y) -> {
        char[] charArray = x.toCharArray();
        charArray[0] = Character.toLowerCase(charArray[0]);
        map1.put(new String(charArray), y);
    });
    BeanUtils.populate(user, map1);

    System.out.println(user);
}
 
Example 7
Source Project: qonduit   Source File: NotEmptyIfFieldSetValidator.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
    if (value == null) {
        return true;
    }

    try {
        final String fieldValue = BeanUtils.getProperty(value, fieldName);
        final String notNullFieldValue = BeanUtils.getProperty(value, notNullFieldName);
        if (StringUtils.equals(fieldValue, fieldSetValue) && StringUtils.isEmpty(notNullFieldValue)) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate())
                    .addPropertyNode(notNullFieldName).addConstraintViolation();
            return false;
        }
    } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
        throw new RuntimeException(e);
    }

    return true;
}
 
Example 8
Source Project: cola   Source File: SsoUserExtractor.java    License: MIT License 6 votes vote down vote up
@Override
public Object extractPrincipal(Map<String, Object> map) {
	Object authentication = map.get("userAuthentication");
	if (authentication == null) {
		throw new InvalidTokenException("userAuthentication is empty");
	}
	Object principal = ((Map<String, Object>) authentication).get("principal");
	AuthenticatedUser user = new AuthenticatedUser();
	if (principal == null) {
		throw new InvalidTokenException("principal is empty");
	}
	try {
		BeanUtils.populate(user, (Map<String, Object>) principal);
	} catch (Exception e) {
		throw new InvalidTokenException("populate user error: " + e.getMessage());
	}
	return user;
}
 
Example 9
Source Project: ankush   Source File: JsonMapperUtil.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Gets the node info list.
 * 
 * @param <S>
 *            the generic type
 * @param dataMap
 *            the monitoring info
 * @param key
 *            the key
 * @param targetClass
 *            the target class
 * @return the node info list
 * @throws Exception
 *             the exception
 */
public static <S> List<S> getListObject(List<Map> listMapData,
		Class<S> targetClass) throws Exception {

	// checking if map is null.
	if (listMapData == null) {
		return null;
	}

	// Creating the resultant list object.
	List<S> result = new ArrayList<S>(listMapData.size());

	// populating values in the list object from map.
	for (Map<String, Object> info : listMapData) {
		// creating target class object.
		S status = targetClass.newInstance();
		// populating object with map values.
		BeanUtils.populate(status, info);
		// adding object in result list.
		result.add(status);
	}
	return result;
}
 
Example 10
/**
 * Obtain a Map from a DatabaseMetadataValue.
 */
public static Map<String, String> getDatabaseMetadataValueMap(DatabaseMetadataValue value) throws DatabaseException,
		IllegalAccessException, InvocationTargetException, NoSuchMethodException {
	Map<String, String> map = new HashMap<String, String>();
	List<DatabaseMetadataType> types = DatabaseMetadataDAO.findAllTypes(value.getTable());

	for (DatabaseMetadataType emt : types) {
		if (emt.getVirtualColumn().equals(DatabaseMetadataMap.MV_NAME_ID)
				|| emt.getVirtualColumn().equals(DatabaseMetadataMap.MV_NAME_TABLE)) {
			throw new DatabaseException("Virtual column name restriction violated " + DatabaseMetadataMap.MV_NAME_ID + " or "
					+ DatabaseMetadataMap.MV_NAME_TABLE);
		}

		map.put(emt.getVirtualColumn(), BeanUtils.getProperty(value, emt.getRealColumn()));
	}

	map.put(DatabaseMetadataMap.MV_NAME_TABLE, value.getTable());
	map.put(DatabaseMetadataMap.MV_NAME_ID, String.valueOf(value.getId()));

	return map;
}
 
Example 11
Source Project: SCIM-Client   Source File: FidoU2fDeviceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test(dependsOnMethods = "retrieve")
public void updateWithJson() throws Exception{

    //shallow clone device
    FidoDeviceResource clone=(FidoDeviceResource) BeanUtils.cloneBean(device);

    clone.setDisplayName(Double.toString(Math.random()));
    clone.setNickname("compromised");
    String json=mapper.writeValueAsString(clone);

    logger.debug("Updating device with json");
    Response response=client.updateDevice(json, device.getId(), null, null);
    assertEquals(response.getStatus(), OK.getStatusCode());

    FidoDeviceResource updated=response.readEntity(fidoClass);
    assertNotEquals(updated.getDisplayName(), device.getDisplayName());
    assertEquals(updated.getNickname(), "compromised");

}
 
Example 12
/**
 * Load the current config from an XML file.
 *
 * @param loadFile
 */
public static void mergeConfigFileToConfigObject(final File loadFile, ToolConfiguration currentToolConfig) throws XmlPersistenceError {
    try {
        JAXBContext jaxbContext = JAXBContext.newInstance(ToolConfiguration.class);
        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        ToolConfiguration loadedConfig = (ToolConfiguration) jaxbUnmarshaller.unmarshal(loadFile);
        
        //BeanUtils.copyProperties(currentToolConfig, loadedConfig);
        //ServerController controller = new ServerController();
        BeanUtils.copyProperties(currentToolConfig.getAttackerConfig(), loadedConfig.getAttackerConfig());
        BeanUtils.copyProperties(currentToolConfig.getAnalyzerConfig(), loadedConfig.getAnalyzerConfig());
        
        LOG.info(String.format("Loaded successfully config from '%s'", loadFile.getAbsoluteFile()));
    } catch (InvocationTargetException | IllegalAccessException | JAXBException ex) {
        throw new XmlPersistenceError(String.format("Could not load config from File '%s'", loadFile.getAbsoluteFile()), ex);
    }
}
 
Example 13
Source Project: n2o-framework   Source File: PlaceHoldersResolver.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private static Function<String, Object> function(Object data) {
    if (data instanceof Function) {
        return (Function<String, Object>) data;
    } else if (data instanceof PropertyResolver) {
        return ((PropertyResolver) data)::getProperty;
    } else if (data instanceof Map) {
        return ((Map) data)::get;
    } else if (data instanceof List) {
        return k -> ((List) data).get(Integer.parseInt(k));
    } else if (data != null && data.getClass().isArray()) {
        Object[] array = (Object[]) data;
        return k -> array[Integer.parseInt(k)];
    } else if (data instanceof String || data instanceof Number || data instanceof Date) {
        return k -> data;
    } else {
        try {
            Map<String, String> map = BeanUtils.describe(data);
            return map::get;
        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            throw new IllegalArgumentException(e);
        }
    }
}
 
Example 14
Source Project: oxTrust   Source File: JsonConfigurationAction.java    License: MIT License 6 votes vote down vote up
private String getProtectedOxTrustappConfiguration(AppConfiguration oxTrustappConfiguration) {
	if (oxTrustappConfiguration != null) {
		try {
			AppConfiguration resultOxTrustappConfiguration = (AppConfiguration) BeanUtils
					.cloneBean(oxTrustappConfiguration);
			resultOxTrustappConfiguration.setKeystorePassword(HIDDEN_PASSWORD_TEXT);
			resultOxTrustappConfiguration.setIdpSecurityKeyPassword(HIDDEN_PASSWORD_TEXT);
			resultOxTrustappConfiguration.setIdpBindPassword(HIDDEN_PASSWORD_TEXT);
			resultOxTrustappConfiguration.setCaCertsPassphrase(HIDDEN_PASSWORD_TEXT);
			resultOxTrustappConfiguration.setOxAuthClientPassword(HIDDEN_PASSWORD_TEXT);

			return jsonService.objectToJson(resultOxTrustappConfiguration);
		} catch (Exception ex) {
			log.error("Failed to prepare JSON from appConfiguration: '{}'", oxTrustappConfiguration, ex);
		}

		return null;
	}
	return null;

}
 
Example 15
Source Project: parker   Source File: FeignUtils.java    License: MIT License 6 votes vote down vote up
/**
 * 查询列表
 * @param client
 * @return
 */
public static List<User> list(UserClient client){
    List<User> result = new ArrayList<>();
    ResponseEntity<BaseResult> entity = client.list();
    List<Map<String, Object>> mapList = (ArrayList)entity.getBody().getData();
    if(HttpStatus.OK.value() == entity.getBody().getCode() && mapList != null && mapList.size() > 0){
        mapList.forEach(m -> {
            User o = new User();
            try {
                // 转换时间
                // ConvertUtils.register(new DateConverter(null), java.util.Date.class);
                BeanUtils.populate(o, m);
            } catch (Exception e) {
                e.printStackTrace();
            }
            result.add(o);
        });
    }
    return result;
}
 
Example 16
Source Project: qzr   Source File: TrackingRuleRuntimeEventListener.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void objectUpdated(final ObjectUpdatedEvent event) {
    if ((handleFilter == null  && classFilter == null) 
            || event.getFactHandle() == handleFilter
            || event.getObject().getClass().equals(classFilter)) {
        updates.add(event);
        allEvents.add(event);

        Object fact = event.getObject();
        try {
            factChanges.add(BeanUtils.describe(fact));
        } catch (Exception e) {
            log.error("Unable to get object details for tracking: " + DroolsUtil.objectDetails(fact), e);
        }
        log.trace("Update: " + DroolsUtil.objectDetails(event.getObject()));
    }
}
 
Example 17
Source Project: validator-web   Source File: DefaultContainer.java    License: Apache License 2.0 6 votes vote down vote up
protected void injectValue(Object bean, PropertyDescriptor pd) {
    Method writeMethod = pd.getWriteMethod();
    Value valueAnnotate = writeMethod.getAnnotation(Value.class);
    if (valueAnnotate == null) {
        return;
    }
    String value = valueAnnotate.value();
    if (value.startsWith("${") && value.endsWith("}")) {
        value = value.substring(2, value.length() - 1);
        value = getProperty(value);
    }
    try {
        BeanUtils.setProperty(bean, pd.getName(), value);
    } catch (Exception e) {
        throw new InjectBeanException("Could not inject value: " + writeMethod + "; nested exception is " + e, e);
    }
}
 
Example 18
@Override
public boolean isValid(final Object value, final ConstraintValidatorContext context) {
    if (value == null) {
        return true;
    }

    try {
        String fieldValue       = BeanUtils.getProperty(value, fieldName);
        String dependFieldValue = BeanUtils.getProperty(value, dependFieldName);

        if (expectedFieldValue.equals(fieldValue) && dependFieldValue == null) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate())
                    .addNode(dependFieldName)
                    .addConstraintViolation();
            return false;
        }

    } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) {
        throw new RuntimeException(ex);
    }

    return true;
}
 
Example 19
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException{
    User user = new User();
    HashMap map = new HashMap();
    Enumeration names = request.getParameterNames();
    while (names.hasMoreElements()) {
        String name = (String) names.nextElement();
        map.put(name, request.getParameterValues(name));
    }
    try{
        BeanUtils.populate(user, map); //BAD

        BeanUtilsBean beanUtl = BeanUtilsBean.getInstance();
        beanUtl.populate(user, map); //BAD
    }catch(Exception e){
        e.printStackTrace();
    }
}
 
Example 20
Source Project: jstarcraft-core   Source File: LuceneEngine.java    License: Apache License 2.0 6 votes vote down vote up
public LuceneEngine(IndexWriterConfig config, Path path) {
    try {
        this.config = config;
        Directory transienceDirectory = new ByteBuffersDirectory();
        this.transienceManager = new TransienceManager((IndexWriterConfig) BeanUtils.cloneBean(config), transienceDirectory);
        Directory persistenceDirectory = FSDirectory.open(path);
        this.persistenceManager = new PersistenceManager((IndexWriterConfig) BeanUtils.cloneBean(config), persistenceDirectory);
        this.searcher = new LuceneSearcher(this.transienceManager, this.persistenceManager);

        this.semaphore = new AtomicInteger();
        ReadWriteLock lock = new ReentrantReadWriteLock();
        this.readLock = lock.readLock();
        this.writeLock = lock.writeLock();
    } catch (Exception exception) {
        throw new StorageException(exception);
    }
}
 
Example 21
Source Project: dtsopensource   Source File: DTSAdmin.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @param activityRuleVO
 * @return
 */
@ResponseBody
@RequestMapping(value = "/queryActivity", method = RequestMethod.POST)
public Map<String, Object> queryActivity(ActivityRuleVO activityRuleVO) {
    Map<String, Object> result = Maps.newHashMap();
    result.put("result", DTSResultCode.SUCCESS);
    try {
        ActivityRuleEntity activityRuleEntity = new ActivityRuleEntity();
        BeanUtils.copyProperties(activityRuleEntity, activityRuleVO);
        List<ActivityRuleEntity> list = acticityRuleApplication.queryActivityRule(activityRuleEntity);
        result.put("list", list);
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        result.put("result", DTSResultCode.FAIL);
        result.put("message", e.getMessage());
    }
    return result;
}
 
Example 22
Source Project: MtgDesktopCompanion   Source File: DBCPPool.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public void init(String url, String user, String pass, boolean enable) {

	logger.debug("init connection to " + url + ", Pooling="+enable);
	dataSource =  new BasicDataSource();
       dataSource.setUrl(url);
       dataSource.setUsername(user);
       dataSource.setPassword(pass);

       props.entrySet().forEach(ks->{
       	try {
			BeanUtils.setProperty(dataSource, ks.getKey().toString(), ks.getValue());
		} catch (Exception e) {
			logger.error(e);
		} 
       });
       
       if(!enable) {
		  dataSource.setMinIdle(1);
          dataSource.setMaxIdle(1);
          dataSource.setInitialSize(0);
          dataSource.setMaxTotal(1);
	  }
 	}
 
Example 23
Source Project: o2oa   Source File: DumpData.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
private <T> void dump(Class<T> cls, EntityManager em) throws Exception {
	/** 创建最终存储文件的目录 */
	File directory = new File(dir, cls.getName());
	FileUtils.forceMkdir(directory);
	FileUtils.cleanDirectory(directory);
	int count = 0;
	int size = Config.dumpRestoreData().getBatchSize();
	String id = "";
	List<T> list = null;
	do {
		list = this.list(em, cls, id, size);
		if (ListTools.isNotEmpty(list)) {
			count = count + list.size();
			id = BeanUtils.getProperty(list.get(list.size() - 1), JpaObject.id_FIELDNAME);
			File file = new File(directory, count + ".json");
			FileUtils.write(file, pureGsonDateFormated.toJson(list), DefaultCharset.charset);
		}
		em.clear();
		Runtime.getRuntime().gc();
	} while (ListTools.isNotEmpty(list));
	this.catalog.put(cls.getName(), count);
}
 
Example 24
Source Project: packagedrone   Source File: Helper.java    License: Eclipse Public License 1.0 6 votes vote down vote up
public static String makeString ( final Object o, final String path, final String defaultValue )
{
    if ( path != null && !path.isEmpty () )
    {
        try
        {
            return BeanUtils.getProperty ( o, path );
        }
        catch ( IllegalAccessException | InvocationTargetException | NoSuchMethodException e )
        {
            throw new RuntimeException ( e );
        }
    }

    if ( o == null )
    {
        return defaultValue;
    }

    return o.toString ();
}
 
Example 25
private void writeExtraMap(MagicCard mc, StringBuilder bw) 
{
		for (String k : getArray(EXTRA_PROPERTIES)) 
		{
			String val = null;
			try {
				val = BeanUtils.getProperty(mc, k);
			} catch (Exception e) {
				logger.error("Error reading bean", e);
			}
			
			if (val == null)
				val = "";
			
			bw.append(val.replaceAll(System.lineSeparator(), "")).append(getSeparator());
		}
		notify(mc);
}
 
Example 26
Source Project: cia   Source File: ListPropertyConverter.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Append object presentation.
 *
 * @param stringBuilder
 *            the string builder
 * @param object
 *            the object
 */
private void appendObjectPresentation(final StringBuilder stringBuilder, final Object object) {
	try {
		final String beanProperty = BeanUtils.getProperty(object, property);

		if (beanProperty != null) {
			stringBuilder.append(beanProperty);
		} else {
			addFallbackValue(stringBuilder, object);
		}

	} catch (final IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
		LOGGER.warn("Problem getting property {}, object {} , exception {}", property, object, e);
	}
	stringBuilder.append(CONTENT_SEPARATOR);
}
 
Example 27
public void put(IValidatable bean) {
	try {
		boolean selected = "true".equals(BeanUtils.getProperty(bean,
				_stateProperty));
		_button.setSelected(selected);
		_textArea.setEnabled(selected);
		List<?> list = (List<?>) PropertyUtils.getProperty(bean, _property);
		StringBuffer sb = new StringBuffer();

		if (list != null) {
			for (int i = 0; i < list.size(); i++) {
				sb.append(list.get(i));
				if (i < list.size() - 1) {
					sb.append("\n");
				}
			}
		}

		_textArea.setText(sb.toString());
	} catch (Exception e) {
		throw new BindingException(e);
	}
}
 
Example 28
Source Project: knox   Source File: XmlUrlRewriteRulesExporter.java    License: Apache License 2.0 6 votes vote down vote up
private Element createElement( Document document, String name, Object bean )
    throws IntrospectionException, InvocationTargetException, NoSuchMethodException, IllegalAccessException {
  Element element = document.createElement( name );
  BeanInfo beanInfo = Introspector.getBeanInfo( bean.getClass(), Object.class );
  for( PropertyDescriptor propInfo: beanInfo.getPropertyDescriptors() ) {
    String propName = propInfo.getName();
    if( propInfo.getReadMethod() != null && String.class.isAssignableFrom( propInfo.getPropertyType() ) ) {
      String propValue = BeanUtils.getProperty( bean, propName );
      if( propValue != null && !propValue.isEmpty() ) {
        // Doing it the hard way to avoid having the &'s in the query string escaped at &amp;
        Attr attr = document.createAttribute( propName );
        attr.setValue( propValue );
        element.setAttributeNode( attr );
        //element.setAttribute( propName, propValue );
      }
    }
  }
  return element;
}
 
Example 29
public static WorkflowInstanceStateModel create( WorkflowInstanceState woin ){
    WorkflowInstanceStateModel model = new WorkflowInstanceStateModel();
    try{
        BeanUtils.copyProperties( model, woin );
    }
    catch( IllegalAccessException | InvocationTargetException e ){
        throw new RuntimeException( "Error creating model", e );
    }
    return model;
}
 
Example 30
Source Project: oxTrust   Source File: JsonConfigurationAction.java    License: MIT License 5 votes vote down vote up
private void processPasswordProperty(AppConfiguration source, AppConfiguration current, String property)
		throws IllegalAccessException, InvocationTargetException, NoSuchMethodException, EncryptionException {
	String currentValue = BeanUtils.getProperty(current, property);
	if (StringHelper.equals(currentValue, HIDDEN_PASSWORD_TEXT)) {
		BeanUtils.setProperty(current, property, BeanUtils.getSimpleProperty(source, property));
	} else {
		BeanUtils.setProperty(current, property, encryptionService.encrypt(currentValue));
	}
}