org.apache.commons.beanutils.BeanUtils Java Examples

The following examples show how to use org.apache.commons.beanutils.BeanUtils. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CamsFixture.java    From kfs with GNU Affero General Public License v3.0 7 votes vote down vote up
public <T> T buildTestDataObject(Class<? extends T> clazz, Properties properties, String propertyKey, String fieldNames, String delimiter) {
    T object;
    try {
        object = clazz.newInstance();
        String[] fields = fieldNames.split(delimiter, -1);
        String[] values = properties.getProperty(propertyKey).split(delimiter, -1);
        int pos = -1;
        for (String field : fields) {
            pos++;
            BeanUtils.setProperty(object, field, values[pos]);
        }
    }
    catch (Exception e) {
        throw new RuntimeException(e);
    }
    return object;
}
 
Example #2
Source File: AnotherFieldEqualsSpecifiedValueValidator.java    From DDMQ with Apache License 2.0 6 votes vote down vote up
@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 #3
Source File: CSVExport.java    From MtgDesktopCompanion with GNU General Public License v3.0 6 votes vote down vote up
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 #4
Source File: Helper.java    From packagedrone with 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 #5
Source File: BeanTest.java    From wechat-core with 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 #6
Source File: ListPropertyConverter.java    From cia with 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 #7
Source File: XmlUrlRewriteRulesExporter.java    From knox with 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 #8
Source File: OptJTextAreaBinding.java    From beast-mcmc with GNU Lesser General Public License v2.1 6 votes vote down vote up
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 #9
Source File: ActionLoggerInterceptor.java    From entando-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
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 #10
Source File: ComTrackableLinkForm.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
@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 #11
Source File: DatabaseInfo.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * @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 #12
Source File: StrutsFormBase.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 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 #13
Source File: NotEmptyIfFieldSetValidator.java    From qonduit with 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 #14
Source File: SsoUserExtractor.java    From cola with 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 #15
Source File: JsonMapperUtil.java    From ankush with 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 #16
Source File: DatabaseMetadataUtils.java    From document-management-system with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 #17
Source File: DBCPPool.java    From MtgDesktopCompanion with 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 #18
Source File: FidoU2fDeviceTest.java    From SCIM-Client with 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 #19
Source File: XmlPersistenceHelper.java    From OpenID-Attacker with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 #20
Source File: DTSAdmin.java    From dtsopensource with 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 #21
Source File: LuceneEngine.java    From jstarcraft-core with 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 #22
Source File: PlaceHoldersResolver.java    From n2o-framework with 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 #23
Source File: BeanInjection.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 6 votes vote down vote up
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 #24
Source File: JsonConfigurationAction.java    From oxTrust with 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 #25
Source File: FeignUtils.java    From parker with 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 #26
Source File: TrackingRuleRuntimeEventListener.java    From qzr with 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 #27
Source File: DefaultContainer.java    From validator-web with 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 #28
Source File: DumpData.java    From o2oa with 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 #29
Source File: AtlasConfigHelper.java    From atlas with Apache License 2.0 5 votes vote down vote up
public static void setProperty(Object object,
                               String fieldName,
                               String value)
    throws IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchFieldException {

    String[] fieldNames = fieldName.split("\\.");

    Object last = object;
    for (int i = 0; i < fieldNames.length - 1; i++) {

        String field = fieldNames[i];

        if (last instanceof NamedDomainObjectContainer) {
            last = ((NamedDomainObjectContainer)last).maybeCreate(field);
        } else {
            Field declaredField = last.getClass().getField(field);
            declaredField.setAccessible(true);

            if (null == declaredField.get(last)) {
                Object newInstance = declaredField.getType()
                    .getConstructors()
                    .getClass()
                    .newInstance();
                declaredField.set(last, newInstance);
            }

            last = declaredField.get(last);
        }
    }

    BeanUtils.setProperty(last, fieldNames[fieldNames.length - 1], value);
}
 
Example #30
Source File: NetDumperOptions.java    From sailfish-core with Apache License 2.0 5 votes vote down vote up
public void fillFromMap(Map<String, String> options) throws Exception {
       for(Entry<String, String> entry : options.entrySet()) {
           if (entry.getKey().startsWith(STORAGE_PREFIX)) {
			BeanUtils.setProperty(this, entry.getKey().replace(STORAGE_PREFIX, ""), entry.getValue());
		}
	}
}