下面列出了javax.persistence.PrePersist#org.apache.commons.beanutils.BeanUtilsBean 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static <T> void populate(T targetObject, Map<String, Object> properties) {
if (properties == null) {
return;
}
T target = getTargetObject(targetObject);
try {
BeanUtilsBean beanUtils = new BeanUtilsBean();
beanUtils.getPropertyUtils().addBeanIntrospector(DefaultBeanIntrospector.INSTANCE);
beanUtils.getPropertyUtils().addBeanIntrospector(new KebabCasePropertyBeanIntrospector());
beanUtils.getPropertyUtils().addBeanIntrospector(SuppressPropertiesBeanIntrospector.SUPPRESS_CLASS);
beanUtils.copyProperties(target, properties);
}
catch (IllegalAccessException | InvocationTargetException e) {
throw new IllegalArgumentException("Failed to populate target of type " + targetObject.getClass()
+ " with properties " + properties, e);
}
}
public void onApplyEnvParams() {
logger.info("onApplyEnvParams: start");
try {
EnvironmentSettings environmentSettings = BeanUtil.getSfContext().getEnvironmentManager().getEnvironmentSettings();
BeanMap environmentBeanMap = new BeanMap(environmentSettings);
for (EnvironmentEntity entry : environmentParamsList) {
Class<?> type = environmentBeanMap.getType(entry.getParamName());
Object convertedValue = BeanUtilsBean.getInstance().getConvertUtils().convert(entry.getParamValue(), type);
environmentBeanMap.put(entry.getParamName(), convertedValue);
}
BeanUtil.getSfContext().getEnvironmentManager().updateEnvironmentSettings((EnvironmentSettings) environmentBeanMap.getBean());
BeanUtil.showMessage(FacesMessage.SEVERITY_INFO, "INFO", "Successfully saved. Some options will be applied only after Sailfish restart");
} catch (Exception e){
logger.error(e.getMessage(), e);
BeanUtil.showMessage(FacesMessage.SEVERITY_ERROR, "ERROR", e.getMessage());
}
logger.info("onApplyEnvParams: end");
}
/**
* Checks if the Property Values of the item are valid for the Request.
*
* @param item
* @throws AirtableException
* @throws IllegalAccessException
* @throws InvocationTargetException
* @throws NoSuchMethodException
*/
private void checkProperties(T item) throws AirtableException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
if (propertyExists(item, FIELD_ID) || propertyExists(item, FIELD_CREATED_TIME)) {
Field[] attributes = item.getClass().getDeclaredFields();
for (Field attribute : attributes) {
String attrName = attribute.getName();
if (FIELD_ID.equals(attrName) || FIELD_CREATED_TIME.equals(attrName)) {
if (BeanUtils.getProperty(item, attribute.getName()) != null) {
throw new AirtableException("Property " + attrName + " should be null!");
}
} else if ("photos".equals(attrName)) {
List<Attachment> obj = (List<Attachment>) BeanUtilsBean.getInstance().getPropertyUtils().getProperty(item, "photos");
checkPropertiesOfAttachement(obj);
}
}
}
}
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();
}
}
/**
* @param accesses 不可操作的字段
* @param params 参数上下文
* @return true
* @see BeanUtilsBean
* @see org.apache.commons.beanutils.PropertyUtilsBean
*/
protected boolean doUpdateAccess(FieldFilterDataAccessConfig accesses, AuthorizingContext params) {
Map<String, Object> paramsMap = params.getParamContext().getParams();
Object supportParam = paramsMap.size() == 0 ?
paramsMap.values().iterator().next() :
paramsMap.values().stream()
.filter(param -> (param instanceof Entity) || (param instanceof Model) || (param instanceof Map))
.findAny()
.orElse(null);
if (null != supportParam) {
for (String field : accesses.getFields()) {
try {
//设置值为null,跳过修改
BeanUtilsBean.getInstance()
.getPropertyUtils()
.setProperty(supportParam, field, null);
} catch (Exception e) {
logger.warn("can't set {} null", field, e);
}
}
} else {
logger.warn("doUpdateAccess skip ,because can not found any support entity in param!");
}
return true;
}
@Test
public void testTCPURI() throws Exception {
TransportConfiguration tc = new TransportConfiguration(NettyConnectorFactory.class.getName());
HashMap<String, Object> params = new HashMap<>();
params.put("host", "localhost1");
params.put("port", 61617);
TransportConfiguration tc2 = new TransportConfiguration(NettyConnectorFactory.class.getName(), params);
HashMap<String, Object> params2 = new HashMap<>();
params2.put("host", "localhost2");
params2.put("port", 61618);
TransportConfiguration tc3 = new TransportConfiguration(NettyConnectorFactory.class.getName(), params2);
ActiveMQConnectionFactory connectionFactoryWithHA = ActiveMQJMSClient.createConnectionFactoryWithHA(JMSFactoryType.CF, tc, tc2, tc3);
URI tcp = parser.createSchema("tcp", connectionFactoryWithHA);
ActiveMQConnectionFactory factory = parser.newObject(tcp, null);
BeanUtilsBean bean = new BeanUtilsBean();
checkEquals(bean, connectionFactoryWithHA, factory);
}
@Test
public void testJGroupsFileURI() throws Exception {
DiscoveryGroupConfiguration discoveryGroupConfiguration = new DiscoveryGroupConfiguration();
JGroupsFileBroadcastEndpointFactory endpointFactory = new JGroupsFileBroadcastEndpointFactory().setChannelName("channel-name").setFile("channel-file.xml");
discoveryGroupConfiguration.setName("foo").setRefreshTimeout(12345).setDiscoveryInitialWaitTimeout(5678).setBroadcastEndpointFactory(endpointFactory);
ActiveMQConnectionFactory connectionFactoryWithHA = ActiveMQJMSClient.createConnectionFactoryWithHA(discoveryGroupConfiguration, JMSFactoryType.CF);
URI tcp = parser.createSchema("jgroups", connectionFactoryWithHA);
ActiveMQConnectionFactory factory = parser.newObject(tcp, null);
DiscoveryGroupConfiguration dgc = factory.getDiscoveryGroupConfiguration();
Assert.assertNotNull(dgc);
BroadcastEndpointFactory befc = dgc.getBroadcastEndpointFactory();
Assert.assertNotNull(befc);
Assert.assertTrue(befc instanceof JGroupsFileBroadcastEndpointFactory);
Assert.assertEquals(dgc.getName(), "foo");
Assert.assertEquals(dgc.getDiscoveryInitialWaitTimeout(), 5678);
Assert.assertEquals(dgc.getRefreshTimeout(), 12345);
JGroupsFileBroadcastEndpointFactory fileBroadcastEndpointFactory = (JGroupsFileBroadcastEndpointFactory) befc;
Assert.assertEquals(fileBroadcastEndpointFactory.getFile(), "channel-file.xml");
Assert.assertEquals(fileBroadcastEndpointFactory.getChannelName(), "channel-name");
BeanUtilsBean bean = new BeanUtilsBean();
checkEquals(bean, connectionFactoryWithHA, factory);
}
@Test
public void testJGroupsPropertiesURI() throws Exception {
DiscoveryGroupConfiguration discoveryGroupConfiguration = new DiscoveryGroupConfiguration();
JGroupsPropertiesBroadcastEndpointFactory endpointFactory = new JGroupsPropertiesBroadcastEndpointFactory().setChannelName("channel-name").setProperties("param=val,param2-val2");
discoveryGroupConfiguration.setName("foo").setRefreshTimeout(12345).setDiscoveryInitialWaitTimeout(5678).setBroadcastEndpointFactory(endpointFactory);
ActiveMQConnectionFactory connectionFactoryWithHA = ActiveMQJMSClient.createConnectionFactoryWithHA(discoveryGroupConfiguration, JMSFactoryType.CF);
URI tcp = parser.createSchema("jgroups", connectionFactoryWithHA);
ActiveMQConnectionFactory factory = parser.newObject(tcp, null);
DiscoveryGroupConfiguration dgc = factory.getDiscoveryGroupConfiguration();
Assert.assertNotNull(dgc);
BroadcastEndpointFactory broadcastEndpointFactory = dgc.getBroadcastEndpointFactory();
Assert.assertNotNull(broadcastEndpointFactory);
Assert.assertTrue(broadcastEndpointFactory instanceof JGroupsPropertiesBroadcastEndpointFactory);
Assert.assertEquals(dgc.getName(), "foo");
Assert.assertEquals(dgc.getDiscoveryInitialWaitTimeout(), 5678);
Assert.assertEquals(dgc.getRefreshTimeout(), 12345);
JGroupsPropertiesBroadcastEndpointFactory propertiesBroadcastEndpointFactory = (JGroupsPropertiesBroadcastEndpointFactory) broadcastEndpointFactory;
Assert.assertEquals(propertiesBroadcastEndpointFactory.getProperties(), "param=val,param2-val2");
Assert.assertEquals(propertiesBroadcastEndpointFactory.getChannelName(), "channel-name");
BeanUtilsBean bean = new BeanUtilsBean();
checkEquals(bean, connectionFactoryWithHA, factory);
}
/**
* BeanUtil initialization, considering Lutèce availables locales and date format properties
*/
public static void init( )
{
_mapBeanUtilsBeans = new HashMap<>( );
for ( Locale locale : I18nService.getAdminAvailableLocales( ) )
{
BeanUtilsBean beanUtilsBean = new BeanUtilsBean( );
beanUtilsBean.getPropertyUtils( ).addBeanIntrospector( SuppressPropertiesBeanIntrospector.SUPPRESS_CLASS );
DateConverter dateConverter = new DateConverter( null );
dateConverter.setPattern( I18nService.getDateFormatShortPattern( locale ) );
beanUtilsBean.getConvertUtils( ).register( dateConverter, Date.class );
_mapBeanUtilsBeans.put( locale.getLanguage( ), beanUtilsBean );
}
}
@Test
public void testAllPropertiesTransit() {
PollingConfigBean pollingConfigBean = new PollingConfigBean();
pollingConfigBean.setIdleTimeBetweenReadsInMillis(1000);
pollingConfigBean.setMaxGetRecordsThreadPool(20);
pollingConfigBean.setMaxRecords(5000);
pollingConfigBean.setRetryGetRecordsInSeconds(30);
ConvertUtilsBean convertUtilsBean = new ConvertUtilsBean();
BeanUtilsBean utilsBean = new BeanUtilsBean(convertUtilsBean);
MultiLangDaemonConfiguration multiLangDaemonConfiguration = new MultiLangDaemonConfiguration(utilsBean, convertUtilsBean);
multiLangDaemonConfiguration.setStreamName("test-stream");
PollingConfig pollingConfig = pollingConfigBean.build(kinesisAsyncClient, multiLangDaemonConfiguration);
assertThat(pollingConfig.kinesisClient(), equalTo(kinesisAsyncClient));
assertThat(pollingConfig.streamName(), equalTo(multiLangDaemonConfiguration.getStreamName()));
assertThat(pollingConfig.idleTimeBetweenReadsInMillis(), equalTo(pollingConfigBean.getIdleTimeBetweenReadsInMillis()));
assertThat(pollingConfig.maxGetRecordsThreadPool(), equalTo(Optional.of(pollingConfigBean.getMaxGetRecordsThreadPool())));
assertThat(pollingConfig.maxRecords(), equalTo(pollingConfigBean.getMaxRecords()));
assertThat(pollingConfig.retryGetRecordsInSeconds(), equalTo(Optional.of(pollingConfigBean.getRetryGetRecordsInSeconds())));
}
protected Type getPropertyType(Object instance, String propertyName) {
try {
if (instance != null) {
Field field = instance.getClass().getField(propertyName);
return field.getGenericType();
} else {
// instance is null for anonymous class, use default type
}
} catch (NoSuchFieldException e1) {
try {
BeanUtilsBean beanUtilsBean = BeanUtilsBean.getInstance();
PropertyUtilsBean propertyUtils = beanUtilsBean.getPropertyUtils();
PropertyDescriptor propertyDescriptor = propertyUtils.getPropertyDescriptor(instance, propertyName);
return propertyDescriptor.getReadMethod().getGenericReturnType();
} catch (Exception e2) {
// nothing
}
} catch (Exception e) {
// ignore other exceptions
}
// return Object class type by default
return Object.class;
}
/**
* <p>Reads an XML document from an {@link URL}
* and uses it to configure this {@link FactoryConfiguration}.</p>
*
* @param url the URL to read from
*/
protected void readImpl(URL url) throws IOException
{
// since beanutils 1.9.4, we need to relax access to the 'class' method
BeanUtilsBean.getInstance().getPropertyUtils().removeBeanIntrospector(SuppressPropertiesBeanIntrospector.SUPPRESS_CLASS);
Digester digester = new Digester();
digester.setNamespaceAware(true);
digester.setXIncludeAware(true);
digester.setValidating(false);
digester.setUseContextClassLoader(true);
digester.push(this);
digester.addRuleSet(getRuleSet());
try
{
digester.parse(url);
}
catch (SAXException saxe)
{
throw new RuntimeException("There was an error while parsing the InputStream", saxe);
}
finally
{
BeanUtilsBean.getInstance().getPropertyUtils().resetBeanIntrospectors();
}
}
private static void copyProperties(Object from,Object to,BeanUtilsBean bub){
try {
bub.copyProperties(to,from);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 从 data 对象中抽取出相应的属性值保持到attributes中,
* 在执行build()方法时可以将attributes写入到entity的payload中
*
* @param data javabean 或者 Map对象
* @param keys 需要抽取的属性名称集合
* @return
*/
public ResultEntityBuilder extract(Object data, String... keys) {
for (String key : keys) {
try {
attr(key, BeanUtilsBean.getInstance().getPropertyUtils().getProperty(data, key));
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
}
return this;
}
/**
*
* Filter the Fields of the PostRecord Object. Id and created Time are set
* to null so Object Mapper doesent convert them to JSON.
*
* @param item
* @return
* @throws IllegalAccessException
* @throws InvocationTargetException
* @throws NoSuchMethodException
*/
private T filterFields(T item) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
final Field[] attributes = item.getClass().getDeclaredFields();
for (Field attribute : attributes) {
String attrName = attribute.getName();
if ((FIELD_ID.equals(attrName) || FIELD_CREATED_TIME.equals(attrName))
&& (BeanUtils.getProperty(item, attrName) != null)) {
BeanUtilsBean.getInstance().getPropertyUtils().setProperty(item, attrName, null);
}
}
return item;
}
public static void beanUtils() throws InvocationTargetException, IllegalAccessException, NoSuchMethodException, InstantiationException {
BeanUtilsBean beanUtilsBean = new BeanUtilsBean2();
beanUtilsBean.getConvertUtils().register(false, false, 0);//错误不抛出异常、不使用Null做默认值,数组的默认大小为0
User user = new User();
user.setName("test");
TestUser testUser = new TestUser();
beanUtilsBean.copyProperties(testUser, user);
System.out.println(testUser);
}
protected void setObjectPropertyNull(Object obj, Set<String> fields) {
if (null == obj) {
return;
}
for (String field : fields) {
try {
BeanUtilsBean.getInstance().getPropertyUtils().setProperty(obj, field, null);
} catch (Exception ignore) {
}
}
}
protected boolean propertyInScope(Object obj, String property, Set<Object> scope) {
if (null == obj) {
return false;
}
try {
Object value = BeanUtilsBean.getInstance().getProperty(obj, property);
if (null != value) {
return scope.contains(value);
}
} catch (Exception ignore) {
logger.warn("can not get property {} from {},{}", property, obj, ignore.getMessage());
}
return true;
}
@Override
public void wrapper(ColumnMetadata instance, int index, String attr, Object value) {
try {
BeanUtilsBean.getInstance().setProperty(instance, attr, value);
} catch (Exception e) {
e.printStackTrace();
}
}
public Object getValue(Object dataObject) {
PropertyUtilsBean utils = BeanUtilsBean.getInstance().getPropertyUtils();
try {
return utils.getNestedProperty(dataObject, getName());
}
catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
throw new IllegalStateException("cannot access field " + getName() + " for " + dataObject.getClass().getName(), e);
}
}
public void setValue(Object dataObject, Object value) {
PropertyUtilsBean utils = BeanUtilsBean.getInstance().getPropertyUtils();
try {
utils.setNestedProperty(dataObject, getName(), value);
}
catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
throw new IllegalStateException("cannot access field " + getName() + " for " + dataObject.getClass().getName(), e);
}
}
protected void createAttributes(T meta) {
Class<?> implClass = meta.getImplementationClass();
PropertyUtilsBean utils = BeanUtilsBean.getInstance().getPropertyUtils();
PropertyDescriptor[] descriptors = utils.getPropertyDescriptors(implClass);
for (PropertyDescriptor desc : descriptors) {
if (desc.getReadMethod().getDeclaringClass() != implClass)
continue; // contained in super type
createAttribute(meta, desc);
}
//
}
public void initialize(ConfigurableApplicationContext applicationContext) {
logger.debug("Context is initialized");
BeanUtilsBean.getInstance().
getConvertUtils().register(new LongConverter(null),
Long.class);
BeanUtilsBean.getInstance()
.getConvertUtils().register(new BigDecimalConverter(null),
BigDecimal.class);
}
/**
* Instantiates an object of the specified type and populates properties of the object from the provided
* parameters.
*
* @param parameters a {@link Map} of values to populate the object from
* @param cls the {@link Class} representing the type of the object to instantiate and populate
* @param <T> the type of the object to instantiate and populate
* @return the instantiated and populated object
*/
public static <T> T mapParametersToBean(Map<String, Object> parameters, Class<T> cls) {
try {
T bean = cls.newInstance();
BeanUtilsBean beanUtils = new BeanUtilsBean();
beanUtils.getPropertyUtils().addBeanIntrospector(SuppressPropertiesBeanIntrospector.SUPPRESS_CLASS);
beanUtils.populate(bean, parameters);
return bean;
}
catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
throw new IllegalArgumentException("Error mapping parameters to class of type " + cls.getName(), e);
}
}
/**
* Register the following converters:
* <ul>
* <li>{@link EmailAddressConverter}</li>
* <li>{@link SmsSenderConverter}</li>
* </ul>
*
* If a conversion error occurs it throws an exception.
*/
public static void registerDefaultConverters() {
// TODO: auto-detect converters in the classpath ?
// Add converter for being able to convert string address into
// EmailAddress
ConvertUtils.register(new EmailAddressConverter(), EmailAddress.class);
// Add converter for being able to convert string into
// SMS sender
ConvertUtils.register(new SmsSenderConverter(), Sender.class);
BeanUtilsBean.getInstance().getConvertUtils().register(true, false, 0);
}
@PrePersist
public void onCreate(Object object) {
final String ID = "id";
final String CREATED_AT = "createdAt";
final String LAST_MODIFIED_AT = "lastModifiedAt";
BeanUtilsBean beanUtilsBean = BeanUtilsBean2.getInstance();
try {
if (Objects.equals(beanUtilsBean.getProperty(object, ID), CommonsConstant.ZERO)) {
beanUtilsBean.setProperty(object, CREATED_AT, System.currentTimeMillis());
beanUtilsBean.setProperty(object, LAST_MODIFIED_AT, System.currentTimeMillis());
}
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException ignore) {}
}
@PrePersist
public void onCreate(Object object) {
final String ID = "id";
final String VALID_FLAG = "validFlag";
BeanUtilsBean beanUtilsBean = BeanUtilsBean2.getInstance();
try {
if (Objects.equals(beanUtilsBean.getProperty(object, ID), CommonsConstant.ZERO)) {
beanUtilsBean.setProperty(object, VALID_FLAG, ValidFlag.VALID);
}
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException ignore) {}
}
private static void checkEquals(Object factory,
Object factory2) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
BeanUtilsBean bean = new BeanUtilsBean();
PropertyDescriptor[] descriptors = bean.getPropertyUtils().getPropertyDescriptors(factory);
for (PropertyDescriptor descriptor : descriptors) {
if (descriptor.getWriteMethod() != null && descriptor.getReadMethod() != null) {
Assert.assertEquals(descriptor.getName() + " incorrect", bean.getProperty(factory, descriptor.getName()), bean.getProperty(factory2, descriptor.getName()));
}
}
}
@Test
public void testTCPAllProperties() throws Exception {
StringBuilder sb = new StringBuilder();
sb.append("tcp://localhost:3030?ha=true");
BeanUtilsBean bean = new BeanUtilsBean();
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(true, (TransportConfiguration) null);
populate(sb, bean, factory);
ActiveMQConnectionFactory factory2 = parser.newObject(new URI(sb.toString()), null);
checkEquals(bean, factory, factory2);
}
@Test
public void testUDPAllProperties() throws Exception {
StringBuilder sb = new StringBuilder();
sb.append("udp://localhost:3030?ha=true");
BeanUtilsBean bean = new BeanUtilsBean();
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(true, (TransportConfiguration) null);
populate(sb, bean, factory);
ActiveMQConnectionFactory factory2 = parser.newObject(new URI(sb.toString()), null);
checkEquals(bean, factory, factory2);
}