Java Examples for org.apache.commons.beanutils.BeanUtils
The following java examples will help you to understand the usage of org.apache.commons.beanutils.BeanUtils. These source code samples are taken from different open source projects.
Example 1
| Project: bamboo-artifactory-plugin-master File: BeanUtilsHelper.java View source code |
public static void populateWithPrefix(Object object, Map<String, String> env, String prefix) {
try {
for (Map.Entry<String, String> entry : Utils.filterMapKeysByPrefix(env, prefix).entrySet()) {
BeanUtils.setProperty(object, entry.getKey().substring(prefix.length()), entry.getValue());
}
} catch (Exception e) {
throw new RuntimeException("Could not set populate bean properties.", e);
}
}Example 2
| Project: consumer-dispatcher-master File: CustomerVistor.java View source code |
public void visit(Attribute attr) {
try {
if (null == attr.getText() || attr.getText().isEmpty()) {
BeanUtils.copyProperty(object, attr.getName(), attr.getValue());
} else {
BeanUtils.copyProperty(object, attr.getName(), attr.getText());
}
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}Example 3
| Project: detective-master File: GroovyUtils.java View source code |
public static Object getProperty(Object object, String property) {
//still have get property? it's maybe a map or list
if (object != null) {
if (object instanceof GroovyObjectSupport) {
Object value = ((GroovyObjectSupport) object).getProperty(property);
return value;
} else {
MetaClass metaClass = REGISTRY.getMetaClass(object.getClass());
if (metaClass != null) {
Object value = metaClass.getProperty(object, property);
return value;
}
}
}
//return BeanUtils.getProperty(realValue, property);
return null;
}Example 4
| Project: ServletStudyDemo-master File: RequestDemo2.java View source code |
//»ñÈ¡ÇëÇóÊý¾ÝÏà¹ØµÄ·½·¨
private void test2(HttpServletRequest request) throws IOException {
System.out.println("------»ñÈ¡Êý¾Ý·½Ê½1-------");
//Ò»°ã»ñµÃÇëÇóÊý¾ÝÖ®ºó¶¼ÒªÏȼì²éºóʹÓÃ
String nameValue = request.getParameter("username");
if (nameValue != null && !nameValue.trim().equals("")) {
System.out.println(nameValue);
}
String nameValue2 = request.getParameter("password");
System.out.println(nameValue2);
System.out.println("------»ñÈ¡Êý¾Ý·½Ê½2-------");
Enumeration e = request.getParameterNames();
while (e.hasMoreElements()) {
String name = (String) e.nextElement();
String value = request.getParameter(name);
System.out.println(name + " = " + value);
}
System.out.println("------»ñÈ¡Êý¾Ý·½Ê½3-------");
String values[] = request.getParameterValues("username");
for (int i = 0; values != null && i < values.length; i++) {
System.out.println(values[i]);
}
System.out.println("------»ñÈ¡Êý¾Ý·½Ê½4-------");
Map<String, String[]> map = request.getParameterMap();
UserData userData = new UserData();
try {
//ÓÃmap¼¯ºÏÖеÄÊý¾ÝÌî³äbean
BeanUtils.populate(userData, map);
//BeanUtils.copyProperties(userData, fromBean); beanµÄ¿½±´
} catch (Exception e1) {
e1.printStackTrace();
}
System.out.println(userData);
System.out.println("------»ñÈ¡Êý¾Ý·½Ê½5£¨ÊʺÏÓëÎļþÉÏ´«£¬Ò»°ã»ñÈ¡Êý¾Ý²»ÓÃÕâÖÖ·½·¨£©-------");
InputStream in = request.getInputStream();
int len = 0;
byte buffer[] = new byte[1024];
while ((len = in.read(buffer)) > 0) {
System.out.println(new String(buffer, 0, len));
}
}Example 5
| Project: beanfuse-master File: ConfigLoader.java View source code |
public synchronized AccessConfig getConfig() {
if (null != config) {
return config;
}
Properties props = new Properties();
InputStream is = ConfigLoader.class.getResourceAsStream("/access.properties");
if (null == is) {
is = ConfigLoader.class.getResourceAsStream("/org/beanfuse/security/access/access-default.properties");
}
try {
logger.debug("Loading config...");
props.load(is);
config = new AccessConfig();
for (Iterator iterator = props.keySet().iterator(); iterator.hasNext(); ) {
String name = (String) iterator.next();
BeanUtils.copyProperty(config, name, props.getProperty(name));
}
logger.info(config.toString());
} catch (Exception e) {
logger.error("Exception", e);
throw new RuntimeException(e.getMessage());
}
return config;
}Example 6
| Project: bjug-querydsl-master File: HibernateFieldInitializer.java View source code |
/**
* Access a field to initialize it
* with special treatment for collections
* @param entity
* @param name
*/
private void initializeField(Object entity, String name) {
// Accessing the field initializes it
Object value;
try {
value = BeanUtils.getProperty(entity, name);
// Unless it's a collection
if (Iterable.class.isAssignableFrom(value.getClass())) {
// In which this will
Iterable.class.cast(value).iterator();
}
} catch (Exception e) {
throw new RuntimeException(String.format("Error accessing field %s in type %s.", name, entity.getClass()), e);
}
}Example 7
| Project: CSTIB-Echo-master File: BaseData.java View source code |
public void save() {
if (hasId()) {
getResource().update(this);
} else {
Map<String, Object> result = (Map) getResource().create(this);
for (String key : result.keySet()) {
try {
BeanUtils.setProperty(this, key, result.get(key));
} catch (Exception e) {
}
}
}
}Example 8
| Project: dbfound-master File: Entity.java View source code |
@SuppressWarnings("unchecked")
public void init(Element element) {
List<DefaultAttribute> list = element.attributes();
for (DefaultAttribute attribute : list) {
try {
BeanUtils.setProperty(this, attribute.getName(), attribute.getValue());
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}Example 9
| Project: find-sec-bugs-master File: BeanInjection.java View source code |
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 {
//BAD
BeanUtils.populate(user, map);
BeanUtilsBean beanUtl = BeanUtilsBean.getInstance();
//BAD
beanUtl.populate(user, map);
} catch (Exception e) {
e.printStackTrace();
}
}Example 10
| Project: HermesJMS-master File: HTMLBeanHelper.java View source code |
public static String format(String text, Object bean) {
Map properties;
try {
properties = BeanUtils.describe(bean);
} catch (Exception ex) {
cat.error("getting properties: " + ex.getMessage(), ex);
return bean.getClass().getName() + ": cannot get properties: " + ex.getMessage();
}
return format(text, properties);
}Example 11
| Project: iMatrix6.0.0Dev-master File: TableViewTag.java View source code |
@SuppressWarnings("unchecked")
@Override
public int doStartTag() throws JspException {
FormViewManager formViewManager = (FormViewManager) ContextUtils.getBean("formViewManager");
WorkflowTask task = null;
if (taskId != null) {
task = ApiFactory.getTaskService().getTask(taskId);
}
FormView form = null;
if (version != null) {
form = formViewManager.getCurrentFormViewByCodeAndVersion(code, version);
} else {
form = formViewManager.getHighFormViewByCode(code);
}
String html = new String("");
if (form != null) {
if (form.getStandard()) {
html = form.getHtml();
} else {
html = "<input id='id' name='id' type='hidden'/><input id='instance_id' name='instance_id' type='hidden'/><input id='form_code' name='form_code' type='hidden' value='" + form.getCode() + "'/><input id='form_version' name='form_version' type='hidden' value='" + form.getVersion() + "'/>" + form.getHtml();
}
}
if (StringUtils.isNotEmpty(html)) {
Long id = null;
if (form.getStandard()) {
try {
if (entity != null) {
Object value = BeanUtils.getProperty(entity, "id");
if (value != null)
id = Long.valueOf(value.toString());
}
} catch (Exception e) {
throw new RuntimeException(e);
}
} else {
if (entity instanceof Map) {
if (((Map) entity).get("id") != null) {
id = Long.valueOf(((Map) entity).get("id").toString());
}
}
}
String attachInfo = "";
if (id != null) {
attachInfo = form.getDataTable().getName() + "," + id;
}
html = html + "<input id='__attachInfo' type='hidden' value='" + (attachInfo == null ? "" : attachInfo) + "'/>";
html = formViewManager.getHtml(form, html, id, true, entity, collection, signatureVisible, attachInfo, viewable, task);
}
JspWriter out = pageContext.getOut();
try {
out.print(html);
} catch (Exception e) {
log.error(e);
throw new JspException(e);
}
return Tag.EVAL_PAGE;
}Example 12
| Project: ismp_manager-master File: SystemLogAction.java View source code |
public ActionForward query(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
SystemLog log = new SystemLog();
SystemLogActionForm systemLogActionForm = (SystemLogActionForm) form;
// System.out.println("--------------"+systemLogActionForm.getModuleName());
PageBean pageBean = new PageBean();
if (request.getParameter("type") == null || !request.getParameter("type").equals("page")) {
if (!systemLogActionForm.getModuleName().equals("all")) {
BeanUtils.copyProperties(log, systemLogActionForm);
// System.out.println("--------------"+log.getModuleName()+"--"+log.getTime());
}
List dateList = new ArrayList();
dateList.add(systemLogActionForm.getBeginDate());
dateList.add(systemLogActionForm.getEndDate());
request.getSession().setAttribute("systemLogListQuery_date", dateList);
request.getSession().setAttribute("systemLogListQuery_log", log);
}
int pageNo = 1;
if (request.getParameter("pageNo") != null && request.getParameter("pageNo") != "")
pageNo = Integer.valueOf(request.getParameter("pageNo"));
pageBean.setPageRowNum(12);
pageBean.setPageNo(pageNo);
List<SystemLog> systemlog = systemlogService.getPageBySystemLog((SystemLog) request.getSession().getAttribute("systemLogListQuery_log"), (pageBean.getPageNo() - 1) * pageBean.getPageRowNum(), pageBean.getPageRowNum(), Timestamp.valueOf(((List) request.getSession().getAttribute("systemLogListQuery_date")).get(0).toString()), Timestamp.valueOf(((List) request.getSession().getAttribute("systemLogListQuery_date")).get(1).toString()));
pageBean.setResultRowSum(systemlogService.getSystemLogCount((SystemLog) request.getSession().getAttribute("systemLogListQuery_log"), Timestamp.valueOf(((List) request.getSession().getAttribute("systemLogListQuery_date")).get(0).toString()), Timestamp.valueOf(((List) request.getSession().getAttribute("systemLogListQuery_date")).get(1).toString())));
pageBean.setPageMaxSum((pageBean.getResultRowSum() + (pageBean.getPageRowNum() - 1)) / pageBean.getPageRowNum());
pageBean.setPageResult(systemlog);
request.setAttribute("pageResult", pageBean);
return mapping.findForward("systemLogDisplay");
}Example 13
| Project: JFinal-ext2-master File: DefaultLogProccesor.java View source code |
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public void process(SysLog sysLog) {
Map map = null;
try {
map = BeanUtils.describe(sysLog);
map.remove("class");
} catch (Exception e) {
e.printStackTrace();
}
Record record = new Record();
record.setColumns(map);
System.out.println(record);
// Db.save("syslog", record);
}Example 14
| Project: kntoos-master File: F170_EntityMgtAction.java View source code |
public String executeAct(Connection oConn, ActionMapping actionMapping, ActionForm actionForm, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
F170_EntityMgtForm piForm = (F170_EntityMgtForm) actionForm;
String sForward = piForm.getForward();
if (piForm.getOp().equals("select") == true) {
F170_EntityMgtLBean pnLBean = new F170_EntityMgtLBean();
F170_EntityMgt selData = new F170_EntityMgt();
try {
BeanUtils.copyProperties(selData, piForm);
} catch (Exception e) {
log.error("error: " + e.toString());
throw e;
}
List rootList = pnLBean.SelectData();
piForm.setRootList(rootList);
}
return sForward;
}Example 15
| Project: ORCID-Source-master File: StringMatchIgnoreCaseValidator.java View source code |
@Override
public boolean isValid(final Object value, final ConstraintValidatorContext context) {
try {
final Object firstObj = BeanUtils.getProperty(value, firstFieldName);
final Object secondObj = BeanUtils.getProperty(value, secondFieldName);
if (firstObj instanceof String && secondObj instanceof String) {
String firstString = (String) firstObj;
String secondString = (String) secondObj;
return firstString.equalsIgnoreCase(secondString);
}
return firstObj == null && secondObj == null;
} catch (final Exception ignore) {
}
return true;
}Example 16
| Project: osgi-sample-master File: EntityServiceImpl.java View source code |
@Override
public Entity updateUser(String id, Entity user) {
Entity current = users.get(id);
if (current == null) {
throw new IllegalArgumentException("Node with ID " + id + " does not exist. Cannot update.");
}
try {
BeanUtils.copyProperties(current, user);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
current.setLastModified(new Date());
return current;
}Example 17
| Project: tapestry-model-master File: ReflectionDescriptorFactory.java View source code |
/**
* Given a type, build a class descriptor
*
* @param type The type to build for
* @return a completed class descriptor
*/
public TynamoClassDescriptor buildClassDescriptor(Class type) {
try {
TynamoClassDescriptor descriptor = new TynamoClassDescriptorImpl(type);
BeanInfo beanInfo = Introspector.getBeanInfo(type);
BeanUtils.copyProperties(descriptor, beanInfo.getBeanDescriptor());
descriptor.setPropertyDescriptors(propertyDescriptorFactory.buildPropertyDescriptors(type, beanInfo));
descriptor.setMethodDescriptors(methodDescriptorFactory.buildMethodDescriptors(type, beanInfo));
descriptor = applyDecorators(descriptor);
return descriptor;
} catch (IllegalAccessException e) {
logger.error("couldn't build class descriptor for: " + type.getSimpleName(), e);
throw new TynamoRuntimeException(e, type);
} catch (InvocationTargetException e) {
logger.error("couldn't build class descriptor for: " + type.getSimpleName(), e);
throw new TynamoRuntimeException(e, type);
} catch (IntrospectionException e) {
logger.error("couldn't build class descriptor for: " + type.getSimpleName(), e);
throw new TynamoRuntimeException(e, type);
}
}Example 18
| Project: viritin-master File: FieldMatchValidator.java View source code |
@Override
public boolean isValid(final Object value, final ConstraintValidatorContext context) {
try {
final Object firstObj = BeanUtils.getProperty(value, firstFieldName);
final Object secondObj = BeanUtils.getProperty(value, secondFieldName);
return firstObj == null && secondObj == null || firstObj != null && firstObj.equals(secondObj);
} catch (final IllegalAccessExceptionNoSuchMethodException | InvocationTargetException | ignore) {
}
return true;
}Example 19
| Project: cambodia-master File: EntityMapper.java View source code |
/**
* <p> 实现row result 的转�。</p>
*/
public Object mapRow(ResultSet rs, int row) throws SQLException {
if (columnsIsNull())
setCurrentColumns(rs);
Object item = null, value = null;
String c = "";
try {
item = entityClass.newInstance();
for (String element : columns) {
c = element;
value = rs.getObject(c);
if (value == null) {
continue;
}
//logger.debug( c + " -> " + o.getClass().getName());
BeanUtils.setProperty(item, element.toLowerCase(), value);
}
} catch (InstantiationException e) {
LoggerHelper.error(EntityMapper.class, e.getMessage());
throw new SQLException("转�结果集时,实例化" + entityClass.getName() + "实体对象出错!");
} catch (Exception e) {
LoggerHelper.error(EntityMapper.class, e.getMessage());
throw new SQLException("设置实体属性值出错!" + c);
}
return item;
}Example 20
| Project: cloudify-master File: OpenspacesDomainStatisticsAdapter.java View source code |
private org.openspaces.admin.config.AbstractConfig createStatisticsConfig(final AbstractConfig config) throws InstantiationException, IllegalAccessException, ClassNotFoundException, InvocationTargetException {
final String configClassName = config.getClass().getSimpleName();
final String openspacesInstanceStatisticsClass = OPENSPACES_STATISTICS_CONFIG_PACKAGE_NAME + "." + configClassName;
Object obj = Class.forName(openspacesInstanceStatisticsClass).newInstance();
//copy all properties from DSL POJO to its equivalent openspaces object.
BeanUtils.copyProperties(obj, config);
return (org.openspaces.admin.config.AbstractConfig) obj;
}Example 21
| Project: comeon-master File: ExternalMetadataTable.java View source code |
@Override
protected List<Entry> getValues(Object content) {
List<Entry> values;
try {
final Map<String, String> properties = BeanUtils.describe(content);
properties.remove(CLASS_PROPERTY_NAME);
values = new ArrayList<>(properties.size());
for (final Map.Entry<String, String> property : properties.entrySet()) {
final String propertyName = property.getKey();
final String propertyValue = BeanUtils.getProperty(content, propertyName);
values.add(new Entry(propertyName, propertyValue));
}
} catch (final IllegalAccessExceptionInvocationTargetException | NoSuchMethodException | e) {
LOGGER.warn("Could not extract properties", e);
values = Collections.emptyList();
}
return values;
}Example 22
| Project: dddlib-master File: C3P0DataSourceCreatorTest.java View source code |
@Test
public void createDataSourceForTenantByMysqlAndDbname() throws Exception {
instance.setDbType(DbType.MYSQL);
instance.setMappingStrategy(TenantDbMappingStrategy.DBNAME);
String url = "jdbc:mysql://localhost:3306/DB_ABC?useUnicode=true&characterEncoding=utf-8";
DataSource result = instance.createDataSourceForTenant(tenant);
assertThat(result, instanceOf(ComboPooledDataSource.class));
assertEquals("com.mysql.jdbc.Driver", BeanUtils.getProperty(result, "driverClass"));
assertEquals(url, BeanUtils.getProperty(result, "jdbcUrl"));
assertEquals("root", BeanUtils.getProperty(result, "user"));
assertEquals("1234", BeanUtils.getProperty(result, "password"));
assertEquals("5", BeanUtils.getProperty(result, "minPoolSize"));
assertEquals("30", BeanUtils.getProperty(result, "maxPoolSize"));
assertEquals("10", BeanUtils.getProperty(result, "initialPoolSize"));
}Example 23
| Project: drupal-services-api-master File: EntityConverter.java View source code |
public Map<String, String> convert(T entity) {
Map<String, String> params = new HashMap<String, String>();
try {
Map<String, String> properties = BeanUtils.describe(entity);
for (Map.Entry<String, String> entry : properties.entrySet()) {
try {
Field field = entity.getClass().getDeclaredField(entry.getKey());
SerializedName annotation = field.getAnnotation(SerializedName.class);
params.put(annotation != null ? annotation.value() : entry.getKey(), entry.getValue());
} catch (NoSuchFieldException e) {
}
}
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
return params;
}Example 24
| Project: geoserver-2.0.x-master File: ConfirmRemovalServicePanel.java View source code |
String name(Object object) {
try {
return (String) BeanUtils.getProperty(object, "service") + "." + (String) BeanUtils.getProperty(object, "method") + "=" + (String) BeanUtils.getProperty(object, "roles");
} catch (Exception e) {
throw new RuntimeException("A data object that does not have " + "a 'name' property has been used, this is unexpected", e);
}
}Example 25
| Project: geoserver-enterprise-master File: JMSLoggingHandler.java View source code |
@Override
public boolean synchronize(LoggingInfo info) throws Exception {
if (info == null) {
throw new NullArgumentException("Incoming object is null");
}
try {
// LOCALIZE service
final LoggingInfo localObject = geoServer.getLogging();
// overwrite local object members with new incoming settings
BeanUtils.copyProperties(localObject, info);
// disable the message producer to avoid recursion
producer.disable();
// save the localized object
geoServer.save(localObject);
} catch (Exception e) {
if (LOGGER.isLoggable(java.util.logging.Level.SEVERE))
LOGGER.severe(this.getClass() + " is unable to synchronize the incoming event: " + info);
throw e;
} finally {
// enable message the producer
producer.enable();
}
return true;
}Example 26
| Project: geoserver-master File: BeanPropertyAccessor.java View source code |
@Override
public <T> T get(Object object, String xpath, Class<T> target) throws IllegalArgumentException {
Object value;
try {
value = BeanUtils.getProperty(object, xpath);
} catch (IllegalAccessExceptionInvocationTargetException | NoSuchMethodException | e) {
throw new WPSException("Failed to retrieve property " + xpath + " in " + object, e);
}
if (target != null) {
return Converters.convert(value, target);
} else {
return (T) value;
}
}Example 27
| Project: geoserver-old-master File: ConfirmRemovalServicePanel.java View source code |
String name(Object object) {
try {
return (String) BeanUtils.getProperty(object, "service") + "." + (String) BeanUtils.getProperty(object, "method") + "=" + (String) BeanUtils.getProperty(object, "roles");
} catch (Exception e) {
throw new RuntimeException("A data object that does not have " + "a 'name' property has been used, this is unexpected", e);
}
}Example 28
| Project: geoserver_trunk-master File: ConfirmRemovalServicePanel.java View source code |
String name(Object object) {
try {
return (String) BeanUtils.getProperty(object, "service") + "." + (String) BeanUtils.getProperty(object, "method") + "=" + (String) BeanUtils.getProperty(object, "roles");
} catch (Exception e) {
throw new RuntimeException("A data object that does not have " + "a 'name' property has been used, this is unexpected", e);
}
}Example 29
| Project: JavaX-master File: Cheat.java View source code |
public static boolean process(String cmdLine) {
if (!cmdLine.startsWith("$$ ")) {
return false;
}
String[] args = cmdLine.substring(3).split(" ");
if (args.length < 3) {
return false;
}
System.out.println("cheat: " + cmdLine);
try {
String cmd = args[1];
Player player = ApplicationHelper.getApplication().getContext().getPlayer();
PlayerVO playerdata = player.getData();
Map<String, Object> data = BeanUtils.describe(playerdata);
Map<String, Object> newdata = new HashMap<String, Object>();
if (cmd.equals("=")) {
Object value = args[2];
if (args[0].equals("xy")) {
args[0] = "sceneLocation";
}
if (args[0].equals("sceneLocation")) {
value = parsePoint(args[2]);
}
newdata.put(args[0], value);
} else if (cmd.equals("+")) {
int value = (Integer) data.get(args[0]);
value += Integer.parseInt(args[2]);
newdata.put(args[0], value);
} else if (cmd.equals("-")) {
int value = (Integer) data.get(args[0]);
value -= Integer.parseInt(args[2]);
newdata.put(args[0], value);
}
BeanUtils.populate(playerdata, newdata);
player.setData(playerdata);
SceneCanvas canvas = (SceneCanvas) ApplicationHelper.getApplication().getCanvas();
canvas.setPlayerSceneLocation(playerdata.getSceneLocation());
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}Example 30
| Project: jaxb2-commons-master File: AbstractParameterizablePlugin.java View source code |
/**
* 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 31
| Project: jw-community-master File: DynamicDataSource.java View source code |
protected void setProperties(Properties properties) {
for (Map.Entry<Object, Object> e : properties.entrySet()) {
String key = (String) e.getKey();
String value = (String) e.getValue();
if (key.endsWith(DRIVER) || key.endsWith(URL) || key.endsWith(USER) || key.endsWith(PASSWORD) || key.endsWith("profileName") || key.endsWith("encryption")) {
continue;
}
try {
BeanUtils.setProperty(this, key, value);
} catch (Exception ex) {
}
}
}Example 32
| Project: mockjndi-master File: ObjectBinding.java View source code |
@Override
public Object createBoundObject() {
try {
final Object object = type.newInstance();
BeanUtils.populate(object, properties);
return object;
} catch (InstantiationException e) {
return null;
} catch (IllegalAccessException e) {
return null;
} catch (InvocationTargetException e) {
return null;
}
}Example 33
| Project: nuxeo-master File: NuxeoConnectionManagerFactory.java View source code |
@Override
public Object getObjectInstance(Object obj, Name objName, Context nameCtx, Hashtable<?, ?> env) {
Reference ref = (Reference) obj;
if (!ConnectionManager.class.getName().equals(ref.getClassName())) {
return null;
}
String name;
int size = objName.size();
if (size == 1) {
name = "default";
} else {
name = objName.get(size - 1);
}
final ConnectionManager cm = NuxeoContainer.connectionManagers.get(name);
if (cm != null) {
return cm;
}
NuxeoConnectionManagerConfiguration config = new NuxeoConnectionManagerConfiguration();
for (RefAddr addr : Collections.list(ref.getAll())) {
String type = addr.getType();
String content = (String) addr.getContent();
try {
BeanUtils.setProperty(config, type, content);
} catch (ReflectiveOperationException e) {
log.error(String.format("NuxeoConnectionManagerFactory cannot set %s = %s", type, content));
}
}
return NuxeoContainer.initConnectionManager(config);
}Example 34
| Project: org.eclipse.ecr-master File: NuxeoTransactionManagerFactory.java View source code |
@Override
public Object getObjectInstance(Object obj, Name objName, Context nameCtx, Hashtable<?, ?> env) throws Exception {
Reference ref = (Reference) obj;
if (!TransactionManager.class.getName().equals(ref.getClassName())) {
return null;
}
if (NuxeoContainer.getTransactionManager() == null) {
// initialize
TransactionManagerConfiguration config = new TransactionManagerConfiguration();
for (RefAddr addr : Collections.list(ref.getAll())) {
String name = addr.getType();
String value = (String) addr.getContent();
try {
BeanUtils.setProperty(config, name, value);
} catch (Exception e) {
log.error(String.format("NuxeoTransactionManagerFactory cannot set %s = %s", name, value));
}
}
NuxeoContainer.initTransactionManager(config);
}
return NuxeoContainer.getTransactionManager();
}Example 35
| Project: osiris-master File: SimpleAssembler.java View source code |
public T createDataTransferObject(K application) throws AssemblyException {
T transferObject;
try {
transferObject = dtoClass.newInstance();
BeanUtils.copyProperties(transferObject, application);
} catch (IllegalAccessException e) {
throw new AssemblyException(e);
} catch (InstantiationException e) {
throw new AssemblyException(e);
} catch (InvocationTargetException e) {
throw new AssemblyException(e);
}
return transferObject;
}Example 36
| Project: package-drone-master File: OptionList.java View source code |
protected void renderOption(final WriterHelper writer, final Object o) throws JspException {
try {
final Object result = BeanUtils.getProperty(o, this.itemValue);
renderOption(writer, result, o, false);
} catch (NoSuchMethodExceptionSecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | e) {
throw new JspException(e);
}
}Example 37
| Project: patientview-master File: UserDeleteAction.java View source code |
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
String username = BeanUtils.getProperty(form, "username");
String unitcode = BeanUtils.getProperty(form, "unitcode");
String nhsno = BeanUtils.getProperty(form, "nhsno");
PatientLogon patient = new PatientLogon();
Unit unit = UnitUtils.retrieveUnit(unitcode);
patient.setUsername(username);
patient.setNhsno(nhsno);
User user = LegacySpringUtils.getUserManager().get(username);
patient.setName(user.getName());
LegacySpringUtils.getUserManager().delete(username, unitcode);
AddLog.addLog(LegacySpringUtils.getSecurityUserManager().getLoggedInUsername(), AddLog.PATIENT_DELETE, username, nhsno, unitcode, "");
String mappingToFind = "success";
request.setAttribute("units", LegacySpringUtils.getUnitManager().getAll(false));
request.setAttribute("patient", patient);
request.setAttribute("unit", unit);
return mapping.findForward(mappingToFind);
}Example 38
| Project: riena-master File: ThreadLocalMapResolver.java View source code |
/*
* (non-Javadoc)
*
* @see
* org.eclipse.core.variables.IDynamicVariableResolver#resolveValue(org.
* eclipse.core.variables.IDynamicVariable, java.lang.String)
*/
/**
* @since 4.0
*/
public String resolveValue(final IDynamicVariable variable, final String argument) throws CoreException {
final Map<String, Object> currentMapping = variableMapping.get();
if (currentMapping == null) {
return null;
} else {
final Object obj = currentMapping.get(variable.getName());
if (argument == null) {
return obj == null ? null : String.valueOf(obj);
} else {
try {
return BeanUtils.getProperty(obj, argument);
} catch (final Exception ex) {
return obj == null ? null : String.valueOf(obj);
}
}
}
}Example 39
| Project: siscofe-master File: UserActionTest.java View source code |
public void testSave() throws Exception {
UserForm userForm = new UserForm();
BeanUtils.copyProperties(userForm, user);
userForm.setPassword("tomcat");
userForm.setConfirmPassword(userForm.getPassword());
getRequest().setAttribute(Constants.USER_KEY, userForm);
setRequestPathInfo("/saveUser");
addRequestParameter("encryptPass", "true");
addRequestParameter("method", "Save");
addRequestParameter("from", "list");
actionPerform();
verifyForward("edit");
assertTrue(getRequest().getAttribute(Constants.USER_KEY) != null);
verifyNoActionErrors();
}Example 40
| Project: SOAP-master File: PropertySupport.java View source code |
public static void applySystemProperties(Object target, String scope, ModelItem modelItem) {
PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(target);
DefaultPropertyExpansionContext context = new DefaultPropertyExpansionContext(modelItem);
Properties properties = System.getProperties();
for (PropertyDescriptor descriptor : descriptors) {
String name = descriptor.getName();
String key = scope + "." + name;
if (PropertyUtils.isWriteable(target, name) && properties.containsKey(key)) {
try {
String value = context.expand(String.valueOf(properties.get(key)));
BeanUtils.setProperty(target, name, value);
SoapUI.log.info("Set property [" + name + "] to [" + value + "] in scope [" + scope + "]");
} catch (Throwable e) {
SoapUI.logError(e);
}
}
}
}Example 41
| Project: soapui-master File: PropertySupport.java View source code |
public static void applySystemProperties(Object target, String scope, ModelItem modelItem) {
PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(target);
DefaultPropertyExpansionContext context = new DefaultPropertyExpansionContext(modelItem);
Properties properties = System.getProperties();
for (PropertyDescriptor descriptor : descriptors) {
String name = descriptor.getName();
String key = scope + "." + name;
if (PropertyUtils.isWriteable(target, name) && properties.containsKey(key)) {
try {
String value = context.expand(String.valueOf(properties.get(key)));
BeanUtils.setProperty(target, name, value);
SoapUI.log.info("Set property [" + name + "] to [" + value + "] in scope [" + scope + "]");
} catch (Throwable e) {
SoapUI.logError(e);
}
}
}
}Example 42
| Project: splout-db-master File: BaseBean.java View source code |
public String toString() {
try {
return BeanUtils.describe(this).toString();
} catch (IllegalAccessException e) {
log.error("Error in toString() method", e);
} catch (InvocationTargetException e) {
log.error("Error in toString() method", e);
} catch (NoSuchMethodException e) {
log.error("Error in toString() method", e);
}
return super.toString();
}Example 43
| Project: spring-data-redis-master File: BeanUtilsHashMapper.java View source code |
/*
* (non-Javadoc)
* @see org.springframework.data.redis.hash.HashMapper#toHash(java.lang.Object)
*/
@Override
public Map<String, String> toHash(T object) {
try {
Map<String, String> map = BeanUtils.describe(object);
Map<String, String> result = new LinkedHashMap<String, String>();
for (Entry<String, String> entry : map.entrySet()) {
if (entry.getValue() != null) {
result.put(entry.getKey(), entry.getValue());
}
}
return result;
} catch (Exception ex) {
throw new IllegalArgumentException("Cannot describe object " + object, ex);
}
}Example 44
| Project: tamper-master File: MapPerformance.java View source code |
public static void main(String args[]) throws Exception {
final int testCount = 1000 * 100 * 20;
CopyBean bean = getBean();
// BeanMap测试
final CopyBean beanMapTarget = new CopyBean();
final BeanMap beanMap = BeanMap.create(CopyBean.class);
testTemplate(new TestCallback() {
public String getName() {
return "BeanMap";
}
public CopyBean call(CopyBean source) {
try {
Map result = beanMap.describe(source);
beanMap.populate(beanMapTarget, result);
} catch (Exception e) {
e.printStackTrace();
}
return beanMapTarget;
}
}, bean, testCount);
// BeanUtils测试
final CopyBean beanUtilsTarget = new CopyBean();
testTemplate(new TestCallback() {
public String getName() {
return "BeanUtils";
}
public CopyBean call(CopyBean source) {
try {
Map result = BeanUtils.describe(source);
BeanUtils.populate(beanUtilsTarget, result);
} catch (Exception e) {
e.printStackTrace();
}
return beanUtilsTarget;
}
}, bean, testCount);
// Cglib测试
final CopyBean cglibTarget = new CopyBean();
final net.sf.cglib.beans.BeanMap cglibBeanMap = net.sf.cglib.beans.BeanMap.create(bean);
testTemplate(new TestCallback() {
public String getName() {
return "Cglib.BeanMap";
}
public CopyBean call(CopyBean source) {
try {
cglibBeanMap.setBean(source);
Set set = cglibBeanMap.keySet();
Map result = new HashMap();
for (Iterator iter = set.iterator(); iter.hasNext(); ) {
Object key = iter.next();
result.put(key, cglibBeanMap.get(key));
}
cglibBeanMap.setBean(cglibTarget);
cglibBeanMap.putAll(result);
} catch (Exception e) {
e.printStackTrace();
}
return beanUtilsTarget;
}
}, bean, testCount);
}Example 45
| Project: udaLib-master File: RowNumResultSetExtractor.java View source code |
@Override
public List<TableRowDto<T>> extractData(ResultSet resultSet) throws SQLException, DataAccessException {
List<TableRowDto<T>> listTableRow = new ArrayList<TableRowDto<T>>();
while (resultSet.next()) {
TableRowDto<T> tableRow = new TableRowDto<T>();
tableRow.setPage(resultSet.getInt("PAGE"));
tableRow.setPageLine(resultSet.getInt("PAGELINE"));
tableRow.setTableLine(resultSet.getInt("TABLELINE"));
T model = rowMapper.mapRow(resultSet, resultSet.getRow());
tableRow.setModel(model);
try {
for (String pk : this.pkColums) {
tableRow.addPrimaryKey(pk, BeanUtils.getProperty(model, pk));
}
listTableRow.add(tableRow);
} catch (IllegalAccessException e) {
throw new SQLException(e);
} catch (InvocationTargetException e) {
throw new SQLException(e);
} catch (NoSuchMethodException e) {
throw new SQLException(e);
}
}
return listTableRow;
}Example 46
| Project: unomi-master File: GeoLocationByPointSessionConditionEvaluator.java View source code |
@Override
public boolean eval(Condition condition, Item item, Map<String, Object> context, ConditionEvaluatorDispatcher dispatcher) {
try {
Double latitude1 = Double.parseDouble((String) condition.getParameter("latitude"));
Double longitude1 = Double.parseDouble((String) condition.getParameter("longitude"));
Double latitude2 = Double.parseDouble(BeanUtils.getProperty(item, "properties.location.lat"));
Double longitude2 = Double.parseDouble(BeanUtils.getProperty(item, "properties.location.lon"));
DistanceUnit.Distance distance = DistanceUnit.Distance.parseDistance((String) condition.getParameter("distance"));
double d = GeoDistance.DEFAULT.calculate(latitude1, longitude1, latitude2, longitude2, distance.unit);
return d < distance.value;
} catch (Exception e) {
logger.debug("Cannot get properties", e);
}
return false;
}Example 47
| Project: URLManager-master File: GenericGetAndPostParameterUnserializer.java View source code |
@Override
public T unserialize(HttpServletRequest request) {
T bean;
Map httpParameterMap;
httpParameterMap = new HashMap(request.getParameterMap());
try {
bean = targetClass.newInstance();
} catch (Exception ex) {
Logger.getLogger(GenericGetAndPostParameterUnserializer.class.getName()).log(Level.SEVERE, null, ex);
throw new BadClientRequestException("Unable to unserialize requested entity", ex);
}
prePopulate(bean, httpParameterMap);
try {
BeanUtils.populate(bean, httpParameterMap);
} catch (Exception ex) {
Logger.getLogger(GenericGetAndPostParameterUnserializer.class.getName()).log(Level.SEVERE, null, ex);
throw new BadClientRequestException("Unable to unserialize requested entity", ex);
}
return bean;
}Example 48
| Project: 5.2.0.RC-master File: TableViewTag.java View source code |
@SuppressWarnings("unchecked")
@Override
public int doStartTag() throws JspException {
FormViewManager formViewManager = (FormViewManager) ContextUtils.getBean("formViewManager");
FormView form = null;
if (version != null) {
form = formViewManager.getCurrentFormViewByCodeAndVersion(code, version);
} else {
form = formViewManager.getHighFormViewByCode(code);
}
String html = new String("");
if (form != null) {
if (form.getStandard()) {
html = form.getHtml();
} else {
html = "<input id='id' name='id' type='hidden'/><input id='instance_id' name='instance_id' type='hidden'/><input id='form_code' name='form_code' type='hidden' value='" + form.getCode() + "'/><input id='form_version' name='form_version' type='hidden' value='" + form.getVersion() + "'/>" + form.getHtml();
}
}
if (StringUtils.isNotEmpty(html)) {
Long id = null;
if (form.getStandard()) {
try {
if (entity != null) {
Object value = BeanUtils.getProperty(entity, "id");
if (value != null)
id = Long.valueOf(value.toString());
}
} catch (Exception e) {
throw new RuntimeException(e);
}
} else {
if (entity instanceof Map) {
if (((Map) entity).get("id") != null) {
id = Long.valueOf(((Map) entity).get("id").toString());
}
}
}
html = formViewManager.getHtml(form, html, id, true, entity, collection, signatureVisible);
}
JspWriter out = pageContext.getOut();
try {
out.print(html);
} catch (Exception e) {
log.error(e);
throw new JspException(e);
}
return Tag.EVAL_PAGE;
}Example 49
| Project: appfuse-master File: BaseDaoTestCase.java View source code |
/**
* Utility method to populate a javabean-style object with values
* from a Properties file
* @param obj the model object to populate
* @return Object populated object
* @throws Exception if BeanUtils fails to copy properly
*/
protected Object populate(Object obj) throws Exception {
// loop through all the beans methods and set its properties from its .properties file
Map<String, String> map = new HashMap<String, String>();
for (Enumeration<String> keys = rb.getKeys(); keys.hasMoreElements(); ) {
String key = keys.nextElement();
map.put(key, rb.getString(key));
}
BeanUtils.copyProperties(obj, map);
return obj;
}Example 50
| Project: CarRental-master File: MainServlet.java View source code |
private void autorizeByCookies(HttpServletRequest request) {
Cookie[] cookies = request.getCookies();
if (cookies != null && cookies.length > 1) {
Map<String, String> userMap = new HashMap<>();
for (Cookie cookie : cookies) {
userMap.put(cookie.getName(), cookie.getValue());
}
User user = new User();
try {
BeanUtils.populate(user, userMap);
} catch (ReflectiveOperationException e) {
logger.error("BeanUtilsError", e);
}
request.getSession().setAttribute("user", user);
}
}Example 51
| Project: cattle-master File: GenericResourceProcessState.java View source code |
protected String lookupState() {
try {
if (resource == null) {
return null;
}
return BeanUtils.getProperty(resource, getStatesDefinition().getStateField());
} catch (IllegalAccessException e) {
throw new IllegalStateException(e);
} catch (InvocationTargetException e) {
throw new IllegalStateException(e);
} catch (NoSuchMethodException e) {
throw new IllegalStateException(e);
}
}Example 52
| Project: ConcesionariaDB-master File: TransformedPropertyRule.java View source code |
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 53
| Project: converge-1.x-master File: EntityConverter.java View source code |
public Map<String, String> convert(T entity) {
Map<String, String> params = new HashMap<String, String>();
try {
Map<String, String> properties = BeanUtils.describe(entity);
for (Map.Entry<String, String> entry : properties.entrySet()) {
getField(entity, entry, params);
}
} catch (IllegalAccessException e) {
LOG.log(Level.WARNING, e.getMessage());
LOG.log(Level.FINEST, "", e);
} catch (InvocationTargetException e) {
LOG.log(Level.WARNING, e.getMessage());
LOG.log(Level.FINEST, "", e);
} catch (NoSuchMethodException e) {
LOG.log(Level.WARNING, e.getMessage());
LOG.log(Level.FINEST, "", e);
}
return params;
}Example 54
| Project: eMonocot-master File: MailSenderStubImpl.java View source code |
/* (non-Javadoc)
* @see org.emonocot.service.EmailService#sendEmail(java.lang.String, java.util.Map, java.lang.String, java.lang.String)
*/
@Override
public void sendEmail(String templateName, Map model, String toAddress, String subject) {
logger.info("Received sendEmail with template:" + templateName + ", model:" + model + ", to:" + toAddress + " subject:" + subject);
for (Object key : model.keySet()) {
try {
logger.info(key + " was " + BeanUtils.describe(model.get(key)));
} catch (Exception e) {
e.printStackTrace();
}
}
}Example 55
| Project: entando-plugins-parent-master File: CoordsAttributeHandler.java View source code |
/**
* Sets coordinate property
* @param textBuffer property value
* @param property property name
*/
private void endCoords(StringBuffer textBuffer, String property) {
if (null != textBuffer && null != this.getCurrentAttr()) {
String coordsString = textBuffer.toString();
double coord = Double.parseDouble(coordsString);
CoordsAttribute attribute = (CoordsAttribute) this.getCurrentAttr();
try {
BeanUtils.setProperty(attribute, property, new Double(coord));
} catch (Throwable t) {
throw new RuntimeException("Error setting '" + property + "' property", t);
}
}
}Example 56
| Project: hale-master File: ConfigurationMapServerFactory.java View source code |
/**
* @see AbstractConfigurationFactory#createExtensionObject()
*/
@Override
public MapServer createExtensionObject() throws Exception {
MapServer server = super.createExtensionObject();
// set name
server.setName(getDisplayName());
// configure map server
IConfigurationElement[] properties = conf.getChildren();
for (IConfigurationElement property : properties) {
//$NON-NLS-1$
String name = property.getAttribute("name");
//$NON-NLS-1$
String value = property.getAttribute("value");
BeanUtils.setProperty(server, name, value);
}
return server;
}Example 57
| Project: hsweb-framework-master File: GroovyDycBeanValidator.java View source code |
public boolean validateMap(Map<Object, Object> data, Operation operation) {
ValidateResults results = new ValidateResults();
try {
Class validatorTargetClass = (Class) engine.execute(className, new HashMap<>()).getIfSuccess();
Object validatorTarget = validatorTargetClass.newInstance();
Set<ConstraintViolation<Object>> result = new LinkedHashSet<>();
if (operation == Operation.INSERT) {
data.forEach(( key, value) -> {
try {
BeanUtils.setProperty(validatorTarget, (String) key, value);
} catch (Exception e) {
}
});
result.addAll(hibernateValidator.validate(validatorTarget));
} else
data.forEach(( key, value) -> {
Field field = ReflectionUtils.findField(validatorTargetClass, (String) key);
if (field != null)
result.addAll(hibernateValidator.validateValue(validatorTargetClass, (String) key, value));
});
if (result.size() > 0) {
for (ConstraintViolation<Object> violation : result) {
String property = violation.getPropertyPath().toString();
results.addResult(property, violation.getMessage());
}
}
} catch (Exception e) {
throw new BusinessException("验�器异常�", e, 500);
}
if (results.size() > 0)
throw new ValidationException(results.get(0).getMessage(), results);
return true;
}Example 58
| Project: java.old-master File: DigesterUtils.java View source code |
/**
* 从XML文件ä¸è¯»å?–æ•°æ?®
* @param obj ä¿?å˜æ•°æ?®çš„对象
* @param inputUrl 所�读�的XML文件对应的URL
* @param rulesUrl XML文件读�规则对应的URL
* @return 读�数��对应的对象,如果读�失败,则返回null
*/
public static Object parse(Object obj, URL inputUrl, URL rulesUrl) {
// Digester 1.8 需è¦?的关é—的日志
Logger.getLogger("org.apache.commons.digester.Digester").setLevel(Level.OFF);
Logger.getLogger("org.apache.commons.beanutils.BeanUtils").setLevel(Level.OFF);
Logger.getLogger("org.apache.commons.beanutils.ConvertUtils").setLevel(Level.OFF);
// Digester 2.0 新增的需è¦?的关é—的日志
Logger.getLogger("org.apache.commons.beanutils.converters").setLevel(Level.OFF);
InputStream inputStream = null;
try {
inputStream = new FileInputStream(inputUrl.getFile());
obj = parse(obj, inputStream, rulesUrl);
} catch (Exception e) {
RunLogger.warn("Failed to read XML", e);
} finally {
if (null != inputStream) {
try {
inputStream.close();
} catch (IOException e) {
}
}
}
return obj;
}Example 59
| Project: jdal-master File: PropertyComparator.java View source code |
/**
* @param o1 one bean
* @param o2 another bean
* @return see the see
* @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
*/
public int compare(Object o1, Object o2) {
try {
String value1 = (String) BeanUtils.getProperty(o1, name).trim();
String value2;
value2 = (String) BeanUtils.getProperty(o2, name).trim();
return comparator.compare(value1, value2);
} catch (Exception e) {
log.error(e);
}
return 0;
}Example 60
| Project: jubula.core-master File: KeywordQuery.java View source code |
/**
* Add the given node to the result, if it has the matching type and
* the name contains the search string.
* {@inheritDoc}
*/
protected boolean operate(INodePO node) {
FieldName[] searchableFieldNames = getSearchOptions().getSearchableFieldNames();
if (matchingSearchType(node)) {
for (FieldName field : searchableFieldNames) {
if (field.isSelected()) {
try {
String fieldValue = StringUtils.defaultString(BeanUtils.getProperty(node, field.getName()), StringConstants.EMPTY);
if (matchSearchString(fieldValue)) {
// found node with keyword and correct type
add(node);
}
} catch (IllegalAccessExceptionInvocationTargetException | NoSuchMethodException | e) {
}
}
}
}
return true;
}Example 61
| Project: kagura-master File: ParameterUtils.java View source code |
public static void insertParameters(Parameters parameters, ReportConnector reportConnector, List<String> errors) {
if (reportConnector.getParameterConfig() != null) {
for (ParamConfig paramConfig : reportConnector.getParameterConfig()) {
if (parameters.getParameters().containsKey(paramConfig.getId())) {
Object o = parameters.getParameters().get(paramConfig.getId());
try {
if (o != null && StringUtils.isNotBlank(o.toString()))
BeanUtils.setProperty(paramConfig, "value", o);
else
BeanUtils.setProperty(paramConfig, "value", null);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (ConversionException e) {
e.printStackTrace();
errors.add("Could not convert parameter: " + paramConfig.getId() + " value " + o);
}
}
}
}
}Example 62
| Project: kfs-master File: CamsFixture.java View source code |
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 63
| Project: levelup-java-examples-master File: ConvertBeanToMap.java View source code |
@Test
public void convert_object_to_map_apache_commons() throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
NoteBook fieldNoteBook = new NoteBook(878, "Field Notebook");
@SuppressWarnings("unchecked") Map<String, Object> objectAsMap = BeanUtils.describe(fieldNoteBook);
assertThat(objectAsMap, hasEntry("numberOfSheets", (Object) "878.0"));
assertThat(objectAsMap, hasEntry("description", (Object) "Field Notebook"));
}Example 64
| Project: Megapode-master File: FormUtil.java View source code |
public static <T> T map(List<NameValuePair> formValues, T bean, List<NameValuePair> unMapped) {
for (NameValuePair element : formValues) {
try {
PropertyDescriptor descriptor = PropertyUtils.getPropertyDescriptor(bean, element.getName());
if (descriptor == null) {
unMapped.add(element);
continue;
} else {
Class<?> type = descriptor.getPropertyType();
if (List.class.isAssignableFrom(type)) {
addElementToList(bean, element, descriptor);
continue;
}
if (Set.class.isAssignableFrom(type)) {
addElementToSet(bean, element, descriptor);
continue;
}
BeanUtils.setProperty(bean, element.getName(), element.getValue());
}
} catch (IllegalAccessExceptionInvocationTargetException | NoSuchMethodException | e) {
e.printStackTrace();
}
}
return bean;
}Example 65
| Project: mini-blog-master File: JobAspect.java View source code |
/**
* 新增用户时通过MQ创建用户索引
* @param user
* @throws Exception
*/
@After("com.xiaozhi.blog.aop.SystemArchitecture.userAddAopFuction()&&args(user)")
protected void creatUserIndex(User user) throws Exception {
if (isDebug) {
logger.debug("#########�置置通知开始��");
logger.debug("----------------->user :" + user.toString());
}
UserIndexData data = new UserIndexData();
BeanUtils.copyProperties(data, user);
//rabbitUserDataMessageGateway.sendMessage(data);//rabbitmq实现
//dubbo远程异æ¥è°ƒç”¨å®žçް
this.userIndexCreater.addOrUpdateBean(data);
}Example 66
| Project: mycar-master File: UserSnapshotCacheTag.java View source code |
// ----------------------------------------------------------------------------------
@Override
public int doStartTag() throws JspException {
JspWriter out = this.pageContext.getOut();
CacheService service = SpringUtils.getBean(CacheService.class);
UserSnapshot ud = service.findAllUserSnapshot().get(getEntityId());
if (ud == null) {
print(out, StringUtils.EMPTY);
return SKIP_BODY;
}
String propertyValue = null;
try {
propertyValue = BeanUtils.getProperty(ud, property);
} catch (Exception e) {
throw new JspException(e.getMessage(), e);
}
print(out, propertyValue);
return SKIP_BODY;
}Example 67
| Project: OG-Platform-master File: FunctionBlacklistComponentFactory.java View source code |
@Override
public void init(final ComponentRepository repo, final LinkedHashMap<String, String> configuration) {
String classifier = "default";
final Iterator<Map.Entry<String, String>> itr = configuration.entrySet().iterator();
while (itr.hasNext()) {
final Map.Entry<String, String> conf = itr.next();
if ("classifier".equals(conf.getKey())) {
classifier = conf.getValue();
} else {
try {
if (conf.getValue().startsWith("::")) {
final Class<?> property = PropertyUtils.getPropertyType(_bean, conf.getKey());
final ComponentInfo info = repo.findInfo(property, conf.getValue().substring(2));
if (info != null) {
BeanUtils.setProperty(_bean, conf.getKey(), repo.getInstance(info));
} else {
BeanUtils.setProperty(_bean, conf.getKey(), conf.getValue());
}
} else {
BeanUtils.setProperty(_bean, conf.getKey(), conf.getValue());
}
} catch (Exception e) {
throw new OpenGammaRuntimeException("invalid property '" + conf.getKey() + "' on " + _bean, e);
}
}
itr.remove();
}
final FunctionBlacklist blacklist = _bean.getObjectCreating();
ComponentInfo infoRO = new ComponentInfo(FunctionBlacklist.class, classifier);
infoRO.addAttribute(ComponentInfoAttributes.LEVEL, 1);
infoRO.addAttribute(ComponentInfoAttributes.REMOTE_CLIENT_JAVA, RemoteFunctionBlacklist.class);
repo.registerComponent(infoRO, blacklist);
if (blacklist instanceof ManageableFunctionBlacklist) {
ComponentInfo infoMng = new ComponentInfo(ManageableFunctionBlacklist.class, classifier);
infoMng.addAttribute(ComponentInfoAttributes.LEVEL, 1);
infoMng.addAttribute(ComponentInfoAttributes.REMOTE_CLIENT_JAVA, RemoteManageableFunctionBlacklist.class);
repo.registerComponent(infoMng, blacklist);
}
}Example 68
| Project: openmrs-core-master File: CachePropertiesUtil.java View source code |
private static CacheConfiguration createCacheConfiguration(OpenmrsCacheConfiguration openmrsCacheConfiguration) {
CacheConfiguration cacheConfiguration = new CacheConfiguration();
openmrsCacheConfiguration.getAllKeys().forEach( key -> {
try {
BeanUtils.setProperty(cacheConfiguration, key, openmrsCacheConfiguration.getProperty(key));
} catch (IllegalAccessExceptionInvocationTargetException | e) {
throw new IllegalStateException(e);
}
});
return cacheConfiguration;
}Example 69
| Project: opennms_dashboard-master File: SDOMapper.java View source code |
public static RemoteReportSDO getSDO(Object bean) {
RemoteReportSDO reportResult = new RemoteReportSDO();
try {
BeanUtils.copyProperties(reportResult, bean);
} catch (IllegalAccessException e) {
logger.debug("getSDObyConnectReport IllegalAssessException while copyProperties from '{}' to '{}' with exception.", reportResult, bean);
logger.error("getSDObyConnectReport IllegalAssessException while copyProperties '{}'", e);
e.printStackTrace();
} catch (InvocationTargetException e) {
logger.debug("getSDObyConnectReport InvocationTargetException while copyProperties from '{}' to '{}' with exception.", reportResult, bean);
logger.error("getSDObyConnectReport InvocationTargetException while copyProperties '{}'", e);
e.printStackTrace();
}
return reportResult;
}Example 70
| Project: rapid-framework-master File: MapAndObjectTest.java View source code |
public void testPerfoemance2() throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
long start = System.currentTimeMillis();
int count = 10000 * 10;
for (int i = 0; i < count; i++) {
BeanUtils.describe(role);
}
long cost = System.currentTimeMillis() - start;
System.out.println("BeanUtils.describe(role) costTime:" + cost + " per request cost:" + (cost / (float) count));
}Example 71
| Project: service-framework-master File: ParamBinding.java View source code |
public void toModel(Object model) {
for (Map.Entry<String, String> entry : rootValues.entrySet()) {
try {
BeanUtils.setProperty(model, entry.getKey(), entry.getValue());
} catch (Exception e) {
}
}
for (Map.Entry<String, Map<String, String>> entry : _children.entrySet()) {
Object newModel;
try {
Object obj = BeanUtils.getProperty(model, entry.getKey());
if (obj != null) {
newModel = obj;
} else {
Class clzz = model.getClass().getDeclaredField(entry.getKey()).getType();
newModel = clzz.newInstance();
}
} catch (Exception e) {
e.printStackTrace();
continue;
}
for (Map.Entry<String, String> entry1 : entry.getValue().entrySet()) {
try {
BeanUtils.setProperty(newModel, entry1.getKey(), entry1.getValue());
BeanUtils.setProperty(model, entry.getKey(), newModel);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}Example 72
| Project: SOEMPI-master File: ConvertingWrapDynaBean.java View source code |
@SuppressWarnings({ "unchecked", "rawtypes" })
public Set<String> getPropertyNames() {
Set<String> properties = new HashSet<String>();
try {
Map map = BeanUtils.describe(getInstance());
for (Iterator<String> iter = (Iterator<String>) map.keySet().iterator(); iter.hasNext(); ) {
String name = iter.next();
if (!name.equals("class")) {
properties.add(name);
}
}
} catch (Exception e) {
log.warn("Failed while extracting bean properties: " + e, e);
}
return properties;
}Example 73
| Project: tourismwork-master File: BaseDaoTestCase.java View source code |
/**
* Utility method to populate a javabean-style object with values
* from a Properties file
*
* @param obj the model object to populate
* @return Object populated object
* @throws Exception if BeanUtils fails to copy properly
*/
protected Object populate(Object obj) throws Exception {
// loop through all the beans methods and set its properties from its .properties file
Map<String, String> map = new HashMap<String, String>();
for (Enumeration<String> keys = rb.getKeys(); keys.hasMoreElements(); ) {
String key = keys.nextElement();
map.put(key, rb.getString(key));
}
BeanUtils.copyProperties(obj, map);
return obj;
}Example 74
| Project: zengsource-mvc-master File: AbstractAction.java View source code |
protected void setFieldValue(String name, String value) throws MvcException {
logger.info("Save parameter: [" + name + "] = [" + value + "]");
try {
BeanUtils.setProperty(this, name, value);
} catch (IllegalAccessException e) {
throw new MvcException(e);
} catch (InvocationTargetException e) {
throw new MvcException(e);
}
}Example 75
| Project: jaulp.core-master File: ObjectExtensions.java View source code |
/**
* Try to clone the given object.
*
* @param object
* The object to clone.
* @return The cloned object or null if the clone process failed.
* @throws NoSuchMethodException
* the no such method exception
* @throws SecurityException
* Thrown if the security manager indicates a security violation.
* @throws IllegalAccessException
* the illegal access exception
* @throws IllegalArgumentException
* the illegal argument exception
* @throws InvocationTargetException
* the invocation target exception
* @throws ClassNotFoundException
* the class not found exception
* @throws InstantiationException
* the instantiation exception
* @throws IOException
* Signals that an I/O exception has occurred.
*/
public static Object cloneObject(final Object object) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, ClassNotFoundException, InstantiationException, IOException {
Object clone = null;
// Try to clone the object if it implements Serializable.
if (object instanceof Serializable) {
clone = SerializedObjectUtils.copySerializedObject((Serializable) object);
if (clone != null) {
return clone;
}
}
// Try to clone the object if it is Cloneble.
if (clone == null && object instanceof Cloneable) {
if (object.getClass().isArray()) {
final Class<?> componentType = object.getClass().getComponentType();
if (componentType.isPrimitive()) {
int length = Array.getLength(object);
clone = Array.newInstance(componentType, length);
while (length-- > 0) {
Array.set(clone, length, Array.get(object, length));
}
} else {
clone = ((Object[]) object).clone();
}
if (clone != null) {
return clone;
}
}
final Class<?> clazz = object.getClass();
final Method cloneMethod = clazz.getMethod("clone", (Class[]) null);
clone = cloneMethod.invoke(object, (Object[]) null);
if (clone != null) {
return clone;
}
}
// the BeanUtils.copyProperties() method.
if (clone == null) {
clone = ReflectionUtils.getNewInstance(object);
BeanUtils.copyProperties(clone, object);
}
return clone;
}Example 76
| Project: aperte-workflow-core-master File: LogStepTest.java View source code |
private void processAutowiredProperties(Object object, Map<String, String> m) {
Class cls = object.getClass();
for (Field f : cls.getDeclaredFields()) {
String autoName = null;
for (Annotation a : f.getAnnotations()) {
if (a instanceof AutoWiredProperty) {
AutoWiredProperty awp = (AutoWiredProperty) a;
if (AutoWiredProperty.DEFAULT.equals(awp.name())) {
autoName = f.getName();
} else {
autoName = awp.name();
}
}
}
String value = m.get(autoName);
if (autoName != null && value != null) {
try {
BeanUtils.setProperty(object, autoName, value);
} catch (Exception e) {
logger.log(Level.SEVERE, "Error setting attribute " + autoName + ": " + e.getMessage(), e);
}
}
}
}Example 77
| Project: atricore-idbus-master File: UserModifyCommand.java View source code |
@Override
protected RequestType buildSpmlRequest(ProvisioningServiceProvider psp, PsPChannel pspChannel) throws Exception {
ModifyRequestType spmlRequest = new ModifyRequestType();
spmlRequest.setRequestID(uuidGenerator.generateId());
spmlRequest.getOtherAttributes().put(SPMLR2Constants.userAttr, "true");
PSOType psoUser = lookupUser(pspChannel, id);
UserType spmlUser = (UserType) psoUser.getData();
BeanUtils.copyProperties(spmlUser, this);
if (this.groupName != null) {
spmlUser.getGroup().clear();
for (String groupName : this.groupName) {
PSOType psoGroup = lookupGroup(pspChannel, groupName);
GroupType spmlGroup = (GroupType) psoGroup.getData();
spmlUser.getGroup().add(spmlGroup);
}
}
ModificationType mod = new ModificationType();
mod.setModificationMode(ModificationModeType.REPLACE);
mod.setData(spmlUser);
spmlRequest.setPsoID(psoUser.getPsoID());
spmlRequest.getModification().add(mod);
return spmlRequest;
}Example 78
| Project: carewebframework-core-master File: TestH2.java View source code |
private void testDB(Map<String, Object> params, DBMode dbMode, String expectedException) throws IllegalAccessException, InvocationTargetException {
String error = null;
H2DataSource h2 = new H2DataSource();
BeanUtils.populate(h2, params);
h2.setMode(dbMode.toString());
try (H2DataSource ds = h2.init();
Connection connection = ds.getConnection();
PreparedStatement ps = connection.prepareStatement("SELECT X FROM SYSTEM_RANGE(1, 9);");
ResultSet rs = ps.executeQuery()) {
assertEquals(dbMode, ds.getMode());
int i = 0;
while (rs.next()) {
i++;
assertEquals(i, rs.getInt("X"));
}
assertEquals(i, 9);
} catch (AssertionError e) {
throw e;
} catch (Exception e) {
error = e.getMessage();
}
if (expectedException == null) {
assertNull(error);
} else {
assertNotNull(error);
assertTrue(error, error.contains(expectedException));
}
}Example 79
| Project: coding2017-master File: Struts.java View source code |
public static View runAction(String actionName, Map<String, String> parameters) throws Exception {
/*
0. 读��置文件struts.xml
1. æ ¹æ?®actionName找到相对应的class , 例如LoginAction, 通过å??射实例化(创建对象)
æ?®parametersä¸çš„æ•°æ?®ï¼Œè°ƒç”¨å¯¹è±¡çš„setter方法, 例如parametersä¸çš„æ•°æ?®æ˜¯
("name"="test" , "password"="1234") ,
那就应该调用 setName和setPassword方法
2. 通过å??射调用对象的execute 方法, 并获得返回值,例如"success"
3. 通过å??射找到对象的所有getter方法(例如 getMessage),
通过å??å°„æ?¥è°ƒç”¨ï¼Œ 把值和属性形æˆ?一个HashMap , 例如 {"message": "登录æˆ?功"} ,
放到View对象的parameters
4. æ ¹æ?®struts.xmlä¸çš„ <result> é…?ç½®,以å?Šexecute的返回值, 确定哪一个jsp,
放到View对象的jspå—æ®µä¸ã€‚
*/
SAXReader reader = new SAXReader();
Document doc = reader.read("./src/struts.xml");
Element root = doc.getRootElement();
Element el = root.element("action");
Attribute attr = el.attribute("class");
String value = attr.getValue();
System.out.println(attr.getValue());
Class<?> clazz = Class.forName(value);
LoginAction login = (LoginAction) clazz.newInstance();
Method setN = clazz.getMethod("setName", String.class);
setN.invoke(login, "test");
Method setP = clazz.getMethod("setPassword", String.class);
setP.invoke(login, "1234");
Method getM = clazz.getMethod("execute", null);
String str = (String) getM.invoke(login, null);
System.out.println(str);
/*PropertyDescriptor pro = new PropertyDescriptor("name", LoginAction.class);
Method readM = pro.getReadMethod();
String message = (String) readM.invoke(login, null);*/
String bean = BeanUtils.getProperty(login, "name");
System.out.println(bean);
return null;
}Example 80
| Project: cooper-master File: PersistentBean.java View source code |
protected void loadData() {
File file = new File(getPersistentFileName());
FileInputStream in = null;
ObjectInputStream s = null;
boolean serialVersionUIDFailure = false;
try {
if (file.exists()) {
in = new FileInputStream(file);
s = new ObjectInputStream(in);
BeanUtils.copyProperties(this, s.readObject());
this.isExist = true;
} else {
this.isExist = false;
}
} catch (Exception ex) {
ex.printStackTrace();
serialVersionUIDFailure = true;
} finally {
try {
if (s != null)
s.close();
if (in != null)
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (serialVersionUIDFailure) {
file.delete();
}
}Example 81
| Project: cosmos-message-master File: ExcelUtils.java View source code |
/**
* 获�导入数�为对象的List
*
* @param data
* @param clazz
* @param excelColumnNames
* @param checkExcel
* @param <T>
* @return
* @throws Exception
*/
public static <T> List<T> makeData(List<Map<String, String>> data, Class<T> clazz, List<String> excelColumnNames, CheckExcel checkExcel) throws Exception {
if (data == null || data.isEmpty() || clazz == null || checkExcel == null) {
return Collections.EMPTY_LIST;
}
List<T> result = new ArrayList<T>(data.size());
for (Map<String, String> d : data) {
if (checkExcel != null && !checkExcel.check(d)) {
continue;
}
T entity = clazz.newInstance();
for (String column : excelColumnNames) {
BeanUtils.setProperty(entity, column, d.get(column));
}
result.add(entity);
}
return result;
}Example 82
| Project: entando-components-master File: CoordsAttributeHandler.java View source code |
/**
* Sets coordinate property
* @param textBuffer property value
* @param property property name
*/
private void endCoords(StringBuffer textBuffer, String property) {
if (null != textBuffer && null != this.getCurrentAttr()) {
String coordsString = textBuffer.toString();
double coord = Double.parseDouble(coordsString);
CoordsAttribute attribute = (CoordsAttribute) this.getCurrentAttr();
try {
BeanUtils.setProperty(attribute, property, new Double(coord));
} catch (Throwable t) {
throw new RuntimeException("Error setting '" + property + "' property", t);
}
}
}Example 83
| Project: extreme-fishbowl-master File: Jira369TestCase.java View source code |
/**
* Test {@link BeanUtils} getProperty() for property "aRatedCd".
*/
public void testBeanUtilsGetProperty_aRatedCd() throws Exception {
TestBean bean = new TestBean();
bean.setARatedCd("foo");
try {
assertEquals("foo", BeanUtils.getProperty(bean, "aRatedCd"));
fail("Expected NoSuchMethodException");
} catch (NoSuchMethodException e) {
} catch (Exception e) {
fail("Threw " + e);
}
}Example 84
| Project: eXtremecomponents-master File: TreeNode.java View source code |
/**
* @param bean
* The bean to set.
*/
public void setBean(Object bean) {
this.bean = bean;
PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(bean);
for (int i = 0; i < descriptors.length; i++) {
try {
String propertyName = descriptors[i].getDisplayName();
Object val = BeanUtils.getProperty(bean, propertyName);
this.put(propertyName, val);
} catch (Exception e) {
logger.error("TreeNode.setBean() Problem", e);
}
}
}Example 85
| Project: fenixedu-academic-master File: EmailIdentityRenderer.java View source code |
@Override
public HtmlComponent createComponent(Object object, Class type) {
if (object == null) {
return new HtmlText();
}
String email = null;
String name = null;
try {
email = BeanUtils.getProperty(object, getAddress());
name = BeanUtils.getProperty(object, getText());
} catch (Exception e) {
throw new RuntimeException(e);
}
HtmlText nameHtml = new HtmlText(name);
HtmlLink emailHtml = new HtmlLink();
emailHtml.setContextRelative(false);
emailHtml.setUrl("mailto:" + email);
if (!isCollapsed()) {
emailHtml.setText(email);
HtmlInlineContainer container = new HtmlInlineContainer();
container.addChild(nameHtml);
container.addChild(new HtmlText(" <", true));
container.addChild(emailHtml);
container.addChild(new HtmlText(">", true));
container.setIndented(false);
return container;
} else {
emailHtml.setText(name);
return emailHtml;
}
}Example 86
| Project: fensy-master File: BaseEntity.java View source code |
/**
* 列出è¦?æ?’入到数æ?®åº“的域集å?ˆï¼Œå?ç±»å?¯ä»¥è¦†ç›–æ¤æ–¹æ³•
*
* @return
*/
@SuppressWarnings("unchecked")
protected Map<String, Object> listInsertableFields() {
try {
Map<String, Object> props = BeanUtils.describe(this);
if (getId() <= 0)
props.remove("id");
props.remove("class");
Map<String, Object> priMap = new HashMap<String, Object>();
for (Entry<String, Object> entry : props.entrySet()) {
Field field = null;
try {
// 有些方法å?¯èƒ½å¹¶æ²¡æœ‰å¯¹åº”的属性,如果å˜åœ¨åˆ™è·³è¿‡ã€‚
field = this.getClass().getDeclaredField(entry.getKey());
} catch (NoSuchFieldException e) {
continue;
}
if (QueryHelper.isPrimitive(field.getType())) {
priMap.put(entry.getKey(), entry.getValue());
}
}
return priMap;
} catch (Exception e) {
throw new RuntimeException("Exception when Fetching fields of " + this, e);
}
}Example 87
| Project: fods-master File: Main.java View source code |
private void readConfig(InputStream configInputStream) throws IOException, IllegalAccessException, InvocationTargetException {
Properties properties = new Properties();
properties.load(configInputStream);
TesterConfig tc = new TesterConfig();
Map<String, Object> propertiesMap = new HashMap<>();
for (Object pk : properties.keySet()) {
propertiesMap.put(pk.toString(), properties.get(pk));
}
BeanUtils.populate(tc, propertiesMap);
testerConfig = tc;
}Example 88
| Project: Fudan-Sakai-master File: BeanSortComparator.java View source code |
/** * protected utility method to wrap BeanUtils * * @param o DOCUMENTATION PENDING * * @return DOCUMENTATION PENDING * * @throws java.lang.UnsupportedOperationException DOCUMENTATION PENDING */ protected Map describeBean(Object o) { Map m = null; try { m = BeanUtils.describe((Serializable) o); } catch (Throwable t) { log.debug("Caught error in BeanUtils.describe(): " + t.getMessage()); t.printStackTrace(); throw new java.lang.UnsupportedOperationException("Invalid describeBean. Objects may not be Java Beans. " + t); } return m; }
Example 89
| Project: gtitool-master File: OptListBinding.java View source code |
public void put(IValidatable bean) {
try {
boolean selected = "true".equals(BeanUtils.getProperty(bean, _stateProperty));
_button.setSelected(selected);
_textArea.setEnabled(selected);
String[] items = (String[]) PropertyUtils.getProperty(bean, _property);
StringBuffer sb = new StringBuffer();
for (int i = 0; i < items.length; i++) {
sb.append(items[i]);
if (i < items.length - 1) {
sb.append("\n");
}
}
_textArea.setText(sb.toString());
} catch (Exception e) {
throw new BindingException(e);
}
}Example 90
| Project: gxt-tools-master File: XlsExporter.java View source code |
@Override
public void exportData(ExportParameters exportParameters, OutputStream outputStream) {
try {
HSSFWorkbook wb = new HSSFWorkbook();
CreationHelper createHelper = wb.getCreationHelper();
//Workbook wb = new XSSFWorkbook();
HSSFSheet sheet = wb.createSheet("Export z NSW");
wb.createSheet("new sheet2");
ExportData exportData = exportData(exportParameters);
String[] headerNames = exportData.headers;
DataFormat dataFormat = wb.createDataFormat();
CellStyle dateStyle = wb.createCellStyle();
dateStyle.setDataFormat(createHelper.createDataFormat().getFormat("dd/mm/yyyy"));
dateStyle.setDataFormat(dataFormat.getFormat("dd-mmm-yy"));
CellStyle decimalStyle = wb.createCellStyle();
decimalStyle.setDataFormat(createHelper.createDataFormat().getFormat("0.00"));
HSSFRow headerRow = sheet.createRow(0);
for (int i = 0; i < headerNames.length; i++) {
// Create a cell and put a value in it.
HSSFCell cell = headerRow.createCell(i);
cell.setCellValue(headerNames[i]);
}
for (int rowIter = 0; rowIter < exportData.data.size(); rowIter++) {
HSSFRow row = sheet.createRow(rowIter + 1);
for (int i = 0; i < headerNames.length; i++) {
// Create a cell and put a value in it.
HSSFCell cell = row.createCell(i);
Object data = exportData.data.get(rowIter);
if (data instanceof List) {
data = ((List) data).get(i);
} else {
data = BeanUtils.getProperty(exportData.data.get(rowIter), headerNames[i]);
}
setCellValue(cell, data, dateStyle, decimalStyle);
}
}
wb.write(outputStream);
return;
} catch (Exception ex) {
ex.printStackTrace();
return;
}
}Example 91
| Project: iaf-master File: SenderMonitorAdapter.java View source code |
public void addNonDefaultAttribute(XmlBuilder senderXml, ISender sender, String attribute) {
try {
PropertyUtilsBean pub = new PropertyUtilsBean();
if (pub.isReadable(sender, attribute) && pub.isWriteable(sender, attribute)) {
String value = BeanUtils.getProperty(sender, attribute);
Object defaultSender;
Class[] classParm = null;
Object[] objectParm = null;
Class cl = sender.getClass();
java.lang.reflect.Constructor co = cl.getConstructor(classParm);
defaultSender = co.newInstance(objectParm);
String defaultValue = BeanUtils.getProperty(defaultSender, attribute);
if (value != null && !value.equals(defaultValue)) {
senderXml.addAttribute(attribute, value);
}
}
} catch (Exception e) {
log.error("cannot retrieve attribute [" + attribute + "] from sender [" + ClassUtils.nameOf(sender) + "]");
}
}Example 92
| Project: intellij-javadocs-master File: JavaDocSettings.java View source code |
@Override
public Object clone() throws CloneNotSupportedException {
JavaDocSettings result = new JavaDocSettings();
try {
if (this.generalSettings != null) {
result.generalSettings = (GeneralSettings) BeanUtils.cloneBean(this.generalSettings);
}
if (this.templateSettings != null) {
result.templateSettings = (TemplateSettings) BeanUtils.cloneBean(this.templateSettings);
}
} catch (Exception e) {
throw new CloneNotSupportedException(e.getMessage());
}
return result;
}Example 93
| Project: javablog-master File: BeanUtil.java View source code |
public static void main(String[] args) throws Exception {
//从文件ä¸è¯»å?–到的数æ?®éƒ½æ˜¯å—符串的数æ?®ï¼Œæˆ–者是表å?•æ??交的数æ?®èŽ·å?–到的时候也是å—符串的数æ?®ã€‚
String id = "22";
String name = "pecae";
String salary = "2000.0";
//需�注册类型转�器
String birthday = "1992-01-02";
//注册一个类型转�器
ConvertUtils.register(new Converter() {
@Override
public // type : 目�所�到的数�类型。 value :目��数的值。
Object convert(// type : 目�所�到的数�类型。 value :目��数的值。
Class type, // type : 目�所�到的数�类型。 value :目��数的值。
Object value) {
Date date = null;
try {
//调用转æ?¢æ ¼å¼?
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
date = //转��的值
dateFormat.parse(//转��的值
(String) value);
} catch (Exception e) {
e.printStackTrace();
}
return date;
}
}, Date.class);
Emp e = new Emp();
//基本类型�以自动转�
BeanUtils.setProperty(e, "id", id);
BeanUtils.setProperty(e, "name", name);
BeanUtils.setProperty(e, "salary", salary);
//需�注册转�器
BeanUtils.setProperty(e, "birthday", birthday);
System.out.println(e);
}Example 94
| Project: jBilling-master File: DateRangeValidator.java View source code |
public boolean isValid(Object object, ConstraintValidatorContext constraintValidatorContext) {
try {
String startDateString = BeanUtils.getProperty(object, startDateFieldName);
String endDateString = BeanUtils.getProperty(object, endDateFieldName);
// only validate if both dates are present
if (StringUtils.isBlank(startDateString))
return true;
if (StringUtils.isBlank(endDateString))
return true;
Date startDate = DEFAULT_DATE_FORMAT.parse(startDateString);
Date endDate = DEFAULT_DATE_FORMAT.parse(endDateString);
return startDate.before(endDate);
} catch (IllegalAccessException e) {
LOG.debug("Illegal access to the date range property fields.");
} catch (NoSuchMethodException e) {
LOG.debug("Date range property missing getter/setter methods.");
} catch (InvocationTargetException e) {
LOG.debug("Date property field cannot be accessed.");
} catch (ParseException e) {
LOG.debug("Date property values cannot be parsed.");
}
return false;
}Example 95
| Project: ldrbrd-master File: ObjectUtils.java View source code |
@SuppressWarnings("unchecked")
public static Map<String, Object> describe(Object bean) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
if (bean == null)
return null;
Map<String, Object> map = (Map<String, Object>) BeanUtils.describe(bean);
map = new LinkedHashMap<String, Object>(map);
for (Field field : bean.getClass().getFields()) {
map.put(field.getName(), field.get(bean));
}
return Collections.unmodifiableMap(map);
}Example 96
| Project: light-admin-master File: AbstractFieldSetConfigurationBuilder.java View source code |
@SuppressWarnings("unchecked")
protected B withCustomControl(SimpleTag customControl) {
assertFieldMetadataType(currentFieldMetadata, AbstractFieldMetadata.class);
try {
BeanUtils.setProperty(customControl, "field", currentFieldMetadata.getUuid());
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
AbstractFieldMetadata fieldMetadata = (AbstractFieldMetadata) currentFieldMetadata;
fieldMetadata.setCustomControlFactory(PrototypeFactory.getInstance(customControl));
return (B) this;
}Example 97
| Project: MusicRecital-master File: BaseDaoTestCase.java View source code |
/**
* Utility method to populate a javabean-style object with values
* from a Properties file
*
* @param obj the model object to populate
* @return Object populated object
* @throws Exception if BeanUtils fails to copy properly
*/
protected Object populate(final Object obj) throws Exception {
// loop through all the beans methods and set its properties from its .properties file
Map<String, String> map = new HashMap<String, String>();
for (Enumeration<String> keys = rb.getKeys(); keys.hasMoreElements(); ) {
String key = keys.nextElement();
map.put(key, rb.getString(key));
}
BeanUtils.copyProperties(obj, map);
return obj;
}Example 98
| Project: Mycat-Server-master File: ZkRuleConfigLoader.java View source code |
private AbstractPartitionAlgorithm instanceFunction(JSONObject ruleJson) {
String functionName = ruleJson.getString(FUNCTION_NAME_KEY);
String ruleName = ruleJson.getString(RULE_NAME_KEY);
//for bean copy
ruleJson.remove(COLUMN_NAME_KEY);
ruleJson.remove(FUNCTION_NAME_KEY);
ruleJson.remove(RULE_NAME_KEY);
AbstractPartitionAlgorithm algorithm;
try {
Class<?> clz = Class.forName(functionName);
if (!AbstractPartitionAlgorithm.class.isAssignableFrom(clz)) {
throw new IllegalArgumentException("rule function must implements " + AbstractPartitionAlgorithm.class.getName() + ", name=" + ruleName);
}
algorithm = (AbstractPartitionAlgorithm) clz.newInstance();
} catch (ClassNotFoundExceptionInstantiationException | IllegalAccessException | e) {
LOGGER.warn("instance function class error: {}", e.getMessage(), e);
throw new ConfigException(e);
}
try {
BeanUtils.populate(algorithm, ruleJson);
} catch (IllegalAccessExceptionInvocationTargetException | e) {
throw new ConfigException("copy property to " + functionName + " error: ", e);
}
//init
algorithm.init();
LOGGER.trace("instanced function class : {}", functionName);
return algorithm;
}Example 99
| Project: netxilia-master File: EnumerationFormatter.java View source code |
private String enumValue(String enumValueProperty, Enum<?> enumItem) {
if (enumValueProperty == null || ENUM_VALUE_NAME.equals(enumValueProperty)) {
return enumItem.name();
}
if (ENUM_VALUE_ORDINAL.equals(enumValueProperty)) {
return String.valueOf(enumItem.ordinal());
}
try {
return BeanUtils.getSimpleProperty(enumItem, enumValueProperty);
} catch (Exception e) {
throw new IllegalArgumentException("Unknown property:" + enumItem.getClass() + "." + enumValueProperty);
}
}Example 100
| Project: odn-search-master File: SolrFactory.java View source code |
/**
* Converts solr document into record according to solr document type property
*
* @param solrDocument output entry of solr response
* @return abstract representation of record
*/
public static AbstractRecord sorlToRecord(SolrDocument solrDocument) {
AbstractRecord record = null;
String type = (String) solrDocument.get("type");
if (type == null)
return null;
if (type.equals(SolrType.ORGANIZATION.getTypeString())) {
record = new OrganizationRecord();
} else if (type.equals(SolrType.POLITICAL_PARTY_DONATION.getTypeString())) {
record = new PoliticalPartyDonationRecord();
} else if (type.equals(SolrType.PROCUREMENT.getTypeString())) {
record = new ProcurementRecord();
}
try {
BeanUtils.copyProperties(record, solrDocument);
} catch (IllegalAccessException e) {
logger.error("IllegalAccessException", e);
} catch (InvocationTargetException e) {
logger.error("InvocationTargetException", e);
}
return record;
}Example 101
| Project: openmrs-module-webservices.rest-master File: ObsComplexValueController1_8.java View source code |
@RequestMapping(value = "/{uuid}/value", method = RequestMethod.GET)
public void getFile(@PathVariable("uuid") String uuid, @RequestParam(required = false, defaultValue = "RAW_VIEW") String view, HttpServletResponse response) throws Exception {
Obs obs = obsService.getObsByUuid(uuid);
if (!obs.isComplex()) {
throw new IllegalRequestException("It is not a complex obs, thus have no data.");
}
obs = obsService.getComplexObs(obs.getId(), view);
ComplexData complexData = obs.getComplexData();
String mimeType;
try {
mimeType = BeanUtils.getProperty(complexData, "mimeType");
} catch (Exception e) {
mimeType = "application/force-download";
}
response.setContentType(mimeType);
if (StringUtils.isNotBlank(complexData.getTitle())) {
response.setHeader("Content-Disposition", "attachment; filename=" + complexData.getTitle());
}
Object data = complexData.getData();
if (data instanceof byte[]) {
response.getOutputStream().write((byte[]) data);
} else if (data instanceof InputStream) {
IOUtils.copy((InputStream) data, response.getOutputStream());
} else if (data instanceof BufferedImage) {
//special case for ImageHandler
BufferedImage image = (BufferedImage) data;
File file = AbstractHandler.getComplexDataFile(obs);
String type = StringUtils.substringAfterLast(file.getName(), ".");
if (type == null) {
type = "jpg";
}
ImageIO.write(image, type, response.getOutputStream());
}
response.flushBuffer();
}