Java Examples for org.apache.commons.beanutils.PropertyUtils
The following java examples will help you to understand the usage of org.apache.commons.beanutils.PropertyUtils. These source code samples are taken from different open source projects.
Example 1
Project: cattle-master File: ObjectDataPostInstantiationHandler.java View source code |
protected boolean hasDataField(Object obj) {
PropertyDescriptor desc;
try {
desc = PropertyUtils.getPropertyDescriptor(obj, "data");
} catch (IllegalAccessException e) {
return false;
} catch (InvocationTargetException e) {
return false;
} catch (NoSuchMethodException e) {
return false;
}
if (desc == null || desc.getReadMethod() == null || desc.getPropertyType() != Map.class) {
return false;
}
return true;
}
Example 2
Project: cyrille-leclerc-master File: BeanComparator.java View source code |
/** * @return a negative integer, zero, or a positive integer as the first argument is less than, * equal to, or greater than the second. * @throws ClassCastException * if the arguments' types prevent them from being compared by this Comparator. */ public int compare(Object o1, Object o2) { // System.out.println("Compare"); // System.out.println("\t'" + o1 + "'"); // System.out.println("\t'" + o2 + "'"); int result = 0; try { int sortFieldsCounter = 0; while (result == 0 && sortFieldsCounter < this.sortFields.length) { Object currentO1 = o1; Object currentO2 = o2; String[] propertiesNames = (String[]) this.sortFields[sortFieldsCounter][PROPERTIES_NAMES]; boolean ascending = ((Boolean) this.sortFields[sortFieldsCounter][ASCENDINGS]).booleanValue(); int i = 0; while (currentO1 != null && currentO2 != null && i < propertiesNames.length) { currentO1 = PropertyUtils.getProperty(currentO1, propertiesNames[i]); currentO2 = PropertyUtils.getProperty(currentO2, propertiesNames[i]); i++; } if (currentO1 == null) { if (currentO2 == null) { result = 0; } else { result = +1; } } else { if (currentO2 == null) { // result = -1; result = -1; } else { if (!(currentO1 instanceof Comparable)) { throw new RuntimeException("Not comparable for getter " + currentO1.toString()); } result = ((Comparable) currentO1).compareTo(currentO2); } } result = (ascending == true ? result : -result); // System.out.println("\t\t on '" + sortField + "' = '" + result + "'"); sortFieldsCounter++; } return result; } catch (Exception e) { throw new RuntimeException(e); } }
Example 3
Project: yoga-master File: PropertyUtil.java View source code |
public static List<PropertyDescriptor> getReadableProperties(Class<?> instanceType) {
List<PropertyDescriptor> result = new ArrayList<PropertyDescriptor>();
for (PropertyDescriptor descriptor : PropertyUtils.getPropertyDescriptors(instanceType)) {
if (descriptor.getReadMethod() != null && !descriptor.getName().equals("class")) {
result.add(descriptor);
}
}
return result;
}
Example 4
Project: tcSlackBuildNotifier-master File: SlackNotificationBeanUtilsVariableResolver.java View source code |
@Override
public String resolve(String variableName) {
String value = "UNRESOLVED";
try {
value = (String) PropertyUtils.getProperty(bean, variableName);
} catch (IllegalAccessException e) {
Loggers.SERVER.warn(this.getClass().getSimpleName() + " :: " + e.getClass() + EXCEPTION_MESSAGE + variableName);
Loggers.SERVER.debug(e);
} catch (InvocationTargetException e) {
Loggers.SERVER.warn(this.getClass().getSimpleName() + " :: " + e.getClass() + EXCEPTION_MESSAGE + variableName);
Loggers.SERVER.debug(e);
} catch (NoSuchMethodException e) {
Loggers.SERVER.warn(this.getClass().getSimpleName() + " :: " + e.getClass() + EXCEPTION_MESSAGE + variableName);
Loggers.SERVER.debug(e);
}
return value;
}
Example 5
Project: appfuse-light-master File: BeanDateComparator.java View source code |
@SuppressWarnings("unchecked") public int compare(Object o1, Object o2) { if (getProperty() == null) { // compare the actual objects return getComparator().compare(o1, o2); } try { Object value1 = PropertyUtils.getProperty(o1, getProperty()); Object value2 = PropertyUtils.getProperty(o2, getProperty()); if (value1 == null) { return -1; } else if (value2 == null) { return 1; } int result = getComparator().compare(value1, value2); if (result == 1) return -1; else return 1; } catch (Exception e) { throw new ClassCastException(e.toString()); } }
Example 6
Project: bean-query-master File: DefaultNullValuePropertyValueGetter.java View source code |
public static Object getProperty(Object from, String propertyName) {
if (null == from || StringUtils.isBlank(propertyName)) {
LoggerFactory.getLogger(DefaultNullValuePropertyValueGetter.class).info("Object is null or the property [{}] is blank, returning null", propertyName);
return null;
}
try {
return PropertyUtils.getProperty(from, propertyName);
} catch (Exception e) {
LoggerFactory.getLogger(DefaultNullValuePropertyValueGetter.class).info("Exception [{}] when fetching property [{}] from object [{}], returning null as the value.", e.toString(), propertyName, from);
return null;
}
}
Example 7
Project: fluent-interface-proxy-master File: SetterAttributeAccessStrategy.java View source code |
public boolean hasProperty(Class<?> builtClass, String propertyName) {
PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(builtClass);
for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
if (propertyDescriptor.getName().equals(propertyName)) {
return true;
}
}
return false;
}
Example 8
Project: idart-jss-master File: BaseImportColumn.java View source code |
@Override public void applyValue(Patient currentPatient) throws PatientException { try { if (beanProperty.contains(".")) { PropertyUtils.setNestedProperty(currentPatient, beanProperty, convertedValue); } else { PropertyUtils.setProperty(currentPatient, beanProperty, convertedValue); } } catch (Exception e) { throw new PatientException("Error applying value '" + getRawValue() + "' to patient property '" + beanProperty + "'"); } }
Example 9
Project: thucydides-master File: BeanFields.java View source code |
public Object forField(String fieldName) {
try {
if (isAMap(bean)) {
return ((Map) bean).get(fieldName);
} else {
return PropertyUtils.getProperty(bean, fieldName);
}
} catch (Exception e) {
throw new IllegalArgumentException("Could not find property value for " + fieldName);
}
}
Example 10
Project: yajsw-master File: ObservableObject.java View source code |
public void update(String field, Object obj) { Object newValue; try { newValue = PropertyUtils.getSimpleProperty(obj, field); Object oldValue = PropertyUtils.getSimpleProperty(_root, field); if (oldValue != null && !oldValue.equals(newValue)) { PropertyUtils.setSimpleProperty(_root, field, newValue); support.firePropertyChange(field, oldValue, newValue); } } catch (Exception e) { e.printStackTrace(); } }
Example 11
Project: yajsw-maven-master File: ObservableObject.java View source code |
public void update(String field, Object obj) { Object newValue; try { newValue = PropertyUtils.getSimpleProperty(obj, field); Object oldValue = PropertyUtils.getSimpleProperty(_root, field); if (oldValue != null && !oldValue.equals(newValue)) { PropertyUtils.setSimpleProperty(_root, field, newValue); support.firePropertyChange(field, oldValue, newValue); } } catch (Exception e) { e.printStackTrace(); } }
Example 12
Project: yajsw-maven-mk2-master File: ObservableObject.java View source code |
public void update(String field, Object obj) { Object newValue; try { newValue = PropertyUtils.getSimpleProperty(obj, field); Object oldValue = PropertyUtils.getSimpleProperty(_root, field); if (oldValue != null && !oldValue.equals(newValue)) { PropertyUtils.setSimpleProperty(_root, field, newValue); support.firePropertyChange(field, oldValue, newValue); } } catch (Exception e) { e.printStackTrace(); } }
Example 13
Project: autopojo-master File: ObjectResolver.java View source code |
public Object resolve(Class<?> clazz, int maxDepth, Type... genericTypes) {
if (clazz.equals(Object.class)) {
return new Object();
}
maxDepth -= 1;
Map<TypeVariable<?>, Type> genericParameters = getGenericParameterMap(clazz, genericTypes);
Object pojo = constructPojo(clazz, genericParameters, maxDepth);
if (!PropertyUtil.isSimpleProperty(clazz)) {
for (PropertyDescriptor descriptor : PropertyUtils.getPropertyDescriptors(clazz)) {
if (shouldExclude(descriptor)) {
continue;
}
strategy.resolve(pojo, new AttributeMetaData(descriptor, genericParameters), maxDepth);
}
}
return pojo;
}
Example 14
Project: cointrader-master File: PortfolioServiceException.java View source code |
private static Throwable findRootCause(Throwable th) { if (th != null) { // Reflectively get any exception causes. try { Throwable targetException = null; // java.lang.reflect.InvocationTargetException String exceptionProperty = "targetException"; if (PropertyUtils.isReadable(th, exceptionProperty)) { targetException = (Throwable) PropertyUtils.getProperty(th, exceptionProperty); } else { exceptionProperty = "causedByException"; //javax.ejb.EJBException if (PropertyUtils.isReadable(th, exceptionProperty)) { targetException = (Throwable) PropertyUtils.getProperty(th, exceptionProperty); } } if (targetException != null) { th = targetException; } } catch (Exception ex) { ex.printStackTrace(); } if (th.getCause() != null) { th = th.getCause(); th = findRootCause(th); } } return th; }
Example 15
Project: gisgraphy-mirror-master File: BeanToQueryString.java View source code |
public static String toQueryString(Object object) {
if (object == null) {
throw new AddressParserException("Can not processQueryString for null address query");
}
StringBuilder sb = new StringBuilder(128);
try {
boolean first = true;
String andValue = "&";
for (PropertyDescriptor thisPropertyDescriptor : Introspector.getBeanInfo(object.getClass(), Object.class).getPropertyDescriptors()) {
Object property = PropertyUtils.getProperty(object, thisPropertyDescriptor.getName());
if (property != null) {
sb.append(first ? "?" : andValue);
sb.append(thisPropertyDescriptor.getName());
sb.append("=");
sb.append(URLEncoder.encode(property.toString(), Constants.CHARSET));
first = false;
}
}
} catch (Exception e) {
throw new AddressParserException("can not generate url form addressQuery : " + e.getMessage(), e);
}
return sb.toString();
}
Example 16
Project: helium-master File: CommonRegistreHelper.java View source code |
public void validate(Object command, Errors errors) {
try {
Long registreId = (Long) PropertyUtils.getSimpleProperty(command, "registreId");
Camp camp = dissenyService.getCampById(registreId);
for (CampRegistre campRegistre : camp.getRegistreMembres()) {
if (campRegistre.isObligatori())
ValidationUtils.rejectIfEmpty(errors, campRegistre.getMembre().getCodi(), "not.blank");
}
} catch (Exception ex) {
errors.reject("error.validator");
}
}
Example 17
Project: ismp_manager-master File: OracleMessageListener.java View source code |
@Override
public void onMessage(Message message) {
ObjectMessage msg = (ObjectMessage) message;
logger.info("oraclelistener wait receive remote jms");
try {
Status result = (Status) msg.getObject();
DatabaseResultEntity dbResult = new DatabaseResultEntity();
dbResult.setNodeid(result.getNodeid());
dbResult.setCacheHitRatio(result.getCacheHitRatio());
dbResult.setCpuBusyRatio(result.getCpuBusyRatio());
dbResult.setSessionNum(result.getSessionNum());
dbResult.setTransactionNum(result.getTransactionNum());
dbResult.setType(result.getType());
List<DeadLockEntity> deadLockList = deadLockList(result.getOracleDeadLocks());
List<ProcessMemoryEntity> processMemorykList = processMemoryList(result.getOracleProcessMemories());
List<WorkspaceEntity> workspaceList = workspaceList(result.getWorkspaces());
dbResult.setDeadLocks(deadLockList);
dbResult.setWorkspaces(workspaceList);
dbResult.setProcessMemories(processMemorykList);
dbResult.setNodeid(result.getNodeid());
dbResult.setCreateTime(new Date());
// å˜åº“æ“?作
logger.info("save receive oracle message into database");
m_databaseResultService.saveDatabaseResult(dbResult);
logger.info("put receive oracle message into domain");
// 缓å˜æ•°æ?®ä¾›å‰?å?°è°ƒç”¨
DatabaseResultStatus status = databaseResultStatus(result);
// try {
//// PropertyUtils.copyProperties(status, dbResult);
// } catch (IllegalAccessException e) {
// e.printStackTrace();
// } catch (InvocationTargetException e) {
//
// e.printStackTrace();
// } catch (NoSuchMethodException e) {
// e.printStackTrace();
// }
m_databaseLocator.setDatabaseResult(result.getNodeid(), status);
} catch (JMSException e) {
logger.debug("OracleMessageListener receive jms occured exception", e);
}
}
Example 18
Project: spring-integration-activiti-sandbox-master File: SerializablePayloadAndHeaderRetainingTransformer.java View source code |
@Transformer
public Message<?> keepOnlySerializablObjects(Message<?> in) throws Throwable {
// System.out.println("passing through " +
// SerializablePayloadAndHeaderRetainingTransformer.class.getName());
MessageHeaders headers = in.getHeaders();
Map<String, Object> serializableHeaders = new HashMap<String, Object>();
for (String k : headers.keySet()) {
Object val = headers.get(k);
if (val instanceof Serializable) {
serializableHeaders.put(k, val);
}
}
Class clz = in.getPayload().getClass();
Object id = PropertyUtils.getProperty(in.getPayload(), "id");
// class will always be non-null
Object payload = Collections.singletonMap(clz.getName(), id);
return MessageBuilder.withPayload(payload).copyHeaders(serializableHeaders).build();
}
Example 19
Project: ef-orm-master File: PerformanceTest.java View source code |
// copy测试 @Test public void copyPropertiesTest() throws IllegalAccessException, InvocationTargetException, InterruptedException, ReflectionException, NoSuchMethodException { Map<String, Long> cost = new LinkedHashMap<String, Long>(); PromotionPO source = new PromotionPO(); Timestamp now = new Timestamp(System.currentTimeMillis()); source.setCode("code"); source.setDescription("haha"); source.setDiscount(5.4); source.setEndTime(new Date()); source.setID(39578395L); source.setPriority(1); source.setPromotionType(3); source.setStartTime(now); source.setSupplierID("123245L"); source.setField1("dsds"); source.setField2("fdsfsdfds"); source.setField3("sdff33"); source.setField4("dfsef4344"); source.setField5("cfer4344"); source.setField6("dssfsfdsf"); source.setField7("cdedfewfdsf"); { PromotionPO target = new PromotionPO(); BeanCopier bc = BeanCopier.create(PromotionPO.class, PromotionPO.class, false); long startTime = System.currentTimeMillis(); for (int i = 0; i < LOOP_NUMBER; i++) { bc.copy(source, target, null); } long endTime = System.currentTimeMillis(); cost.put("Spring BeanCopier", endTime - startTime); } // 案例0:CGLib (原生) { PromotionPO po = new PromotionPO(); jef.accelerator.cglib.beans.BeanCopier bc = jef.accelerator.cglib.beans.BeanCopier.create(PromotionPO.class, PromotionPO.class, false); long startTime = System.currentTimeMillis(); for (int i = 0; i < LOOP_NUMBER; i++) { bc.copy(source, po, null); } long endTime = System.currentTimeMillis(); cost.put("CGLib BeanCopier", endTime - startTime); } // 案例1:Apache commons (最慢) { PromotionPO po = new PromotionPO(); long startTime = System.currentTimeMillis(); for (int i = 0; i < LOOP_NUMBER; i++) { // org.apache.commons.beanutils.PropertyUtils.copyProperties(po, source); } long endTime = System.currentTimeMillis(); // (Apache cost.put(// (Apache "Apache PropertyUtils", // (Apache endTime - startTime); // çš„BeanUtils.copyProperties性能差ä¸?多是PropertyUtilsçš„1/2ï¼Œæ—¶é—´å¼€é”€åŠ å€?实在太慢了!) } // 案例2:Springçš„beanutils { // spring PromotionPO po = new PromotionPO(); long startTime = System.currentTimeMillis(); for (int i = 0; i < LOOP_NUMBER; i++) { org.springframework.beans.BeanUtils.copyProperties(source, po); } long endTime = System.currentTimeMillis(); cost.put("Spring BeanUtils", endTime - startTime); } // 案例3:Springçš„BeanWrapper { // spring PromotionPO po = new PromotionPO(); long startTime = System.currentTimeMillis(); for (int i = 0; i < LOOP_NUMBER; i++) { org.springframework.beans.BeanWrapper bws = new org.springframework.beans.BeanWrapperImpl(source); org.springframework.beans.BeanWrapper bwt = new org.springframework.beans.BeanWrapperImpl(po); for (PropertyDescriptor property : bws.getPropertyDescriptors()) { if (bwt.isWritableProperty(property.getName())) { bwt.setPropertyValue(property.getName(), bws.getPropertyValue(property.getName())); } } } long endTime = System.currentTimeMillis(); cost.put("Spring BeanWrapper", endTime - startTime); } // 案例4: jef.tools.reflect.BeanUtils (å?«åŠ¨æ€?类创建时间) { PromotionPO po = new PromotionPO(); long startTime = System.currentTimeMillis(); for (int i = 0; i < LOOP_NUMBER; i++) { jef.tools.reflect.BeanUtils.copyProperties(source, po); } long endTime = System.currentTimeMillis(); cost.put("Jef BeanUtils(include ASM)", endTime - startTime); } // 案例5:jef.tools.reflect.BeanUtils { BeanAccessor ba = FastBeanWrapperImpl.getAccessorFor(PromotionPO.class); PromotionPO po = new PromotionPO(); long startTime = System.currentTimeMillis(); // 动æ€?类生æˆ?时间ä¸?计入å??å°„æ“?作时间 for (int i = 0; i < LOOP_NUMBER; i++) { ba.copy(source, po); } long endTime = System.currentTimeMillis(); cost.put("Jef BeanAccessor", endTime - startTime); } // 案例0:直接get/set { PromotionPO po = new PromotionPO(); long startTime = System.currentTimeMillis(); for (int i = 0; i < LOOP_NUMBER; i++) { po.setCode(source.getCode()); po.setDescription(source.getDescription()); po.setDiscount(source.getDiscount()); po.setEndTime(source.getEndTime()); po.setID(source.getID()); po.setPriority(source.getPriority()); po.setPromotionType(source.getPromotionType()); po.setStartTime(source.getStartTime()); po.setSupplierID(source.getSupplierID()); po.setField1(source.getField1()); po.setField2(source.getField2()); po.setField3(source.getField3()); po.setField4(source.getField4()); po.setField5(source.getField5()); po.setField6(source.getField6()); po.setField7(source.getField7()); } long endTime = System.currentTimeMillis(); cost.put("Hard Coding", endTime - startTime); } LogUtil.show(cost); }
Example 20
Project: beanfuse-master File: PropertyComparator.java View source code |
public int compare(Object arg0, Object arg1) { Object what0 = null; Object what1 = null; // å?–出属性 if (index > -1) { arg0 = ((Object[]) arg0)[index]; arg1 = ((Object[]) arg1)[index]; if (StringUtils.isEmpty(cmpWhat)) { what0 = arg0; what1 = arg1; } } if (StringUtils.isNotEmpty(cmpWhat)) { try { what0 = PropertyUtils.getProperty(arg0, cmpWhat); what1 = PropertyUtils.getProperty(arg1, cmpWhat); } catch (Exception e) { throw new RuntimeException(e); } } if (what0 == null && null == what1) { return 0; } // 进行比较 if (null == comparator) { // 进行å—符串比较 if (what0 instanceof String || what1 instanceof String) { return stringComparator.compare(what0, what1); } else { if (what0 == null && null != what1) { return asc ? -1 : 1; } if (what0 != null && null == what1) { return asc ? 1 : -1; } if (asc) { return ((Comparable) what0).compareTo(what1); } else { return ((Comparable) what1).compareTo(what0); } } } else { return comparator.compare(what0, what1); } }
Example 21
Project: brms-reference-master File: ReflectiveExecutionResultsTransformer.java View source code |
@Override
public <Response> Response transform(ExecutionResults results, Class<Response> responseClazz) {
Response response = null;
try {
response = responseClazz.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
for (Field field : QueryUtils.getAllFields(responseClazz)) {
DroolsQueryInfo queryInfo = field.getAnnotation(DroolsQueryInfo.class);
if (queryInfo != null) {
String queryName = queryInfo.queryName();
String binding = queryInfo.binding();
Class<?> type = field.getType();
if (Collection.class.equals(type)) {
try {
Collection<?> list = QueryUtils.extractCollectionFromExecutionResults(results, queryName, binding);
PropertyUtils.setProperty(response, field.getName(), list);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
} else {
logger.warn("QueryInfo annotation can not be used on " + field.getName() + ". It only be used on fields which are of Type Collection");
}
}
}
return response;
}
Example 22
Project: chronostamp-master File: BasicTest.java View source code |
@Test public void testMagicTimestampFields() throws InvocationTargetException, NoSuchMethodException, IllegalAccessException { Article article = (Article) Article.findAll().get(0); assertNotNull(PropertyUtils.getProperty(article, "created_at")); assertNotNull(PropertyUtils.getProperty(article, "updated_at")); assertNotSame(new Date().getTime(), ((Date) PropertyUtils.getProperty(article, "created_at")).getTime()); assertNotSame(new Date().getTime(), ((Date) PropertyUtils.getProperty(article, "updated_at")).getTime()); assertEquals(((Date) PropertyUtils.getProperty(article, "created_at")).getTime(), ((Date) PropertyUtils.getProperty(article, "updated_at")).getTime()); article.name = "Logitech"; article.save(); assertNotSame(((Date) PropertyUtils.getProperty(article, "created_at")).getTime(), ((Date) PropertyUtils.getProperty(article, "updated_at")).getTime()); }
Example 23
Project: ClearJS-master File: DTOUtil.java View source code |
/** * Converts java bean based DTO to string showing class name and properties * with values. * For example: * UserDTO {id: '123', first_name: 'Alex', ... } * * @param obj - object to convert to String. * @return - object string representation. */ @SuppressWarnings("unchecked") public static String toString(Object obj) { try { Map<String, Object> props = PropertyUtils.describe(obj); StringBuilder b = new StringBuilder(); b.append(obj.getClass().getName()).append(" { "); int count = 0; for (String field : props.keySet()) { if (count++ != 0) { b.append(", "); } b.append(field).append(": '").append(PropertyUtils.getProperty(obj, field)).append("'"); } b.append("}"); return b.toString(); } catch (IllegalAccessException e1) { logger.error(ExceptionUtils.getStackTrace(e1)); } catch (InvocationTargetException e1) { logger.error(ExceptionUtils.getStackTrace(e1)); } catch (NoSuchMethodException e1) { logger.error(ExceptionUtils.getStackTrace(e1)); } return ""; }
Example 24
Project: cnery-master File: FieldsNotEqualValidator.java View source code |
@Override public boolean isValid(final Object value, final ConstraintValidatorContext context) { try { final Object first = PropertyUtils.getProperty(value, firstFieldName); final Object second = PropertyUtils.getProperty(value, secondFieldName); boolean equal = first == null && second == null || first != null && first.equals(second); return !equal; } catch (final Exception ignore) { } return true; }
Example 25
Project: common-java-cookbook-master File: PropertyPredicate.java View source code |
public boolean evaluate(Object object) {
boolean propertyFound = false;
try {
Object value = PropertyUtils.getProperty(object, property);
if (value != null) {
if (matchValue != null) {
propertyFound = matchValue.equals(value);
} else {
propertyFound = true;
}
}
} catch (Exception e) {
}
return propertyFound;
}
Example 26
Project: data-exporter-master File: BeanColumnBuilder.java View source code |
public Column[] build(Object bean) {
if (bean == null) {
throw new IllegalArgumentException("Parameter bean cannot be null");
}
//Read each getters
Field[] fields = bean.getClass().getFields();
for (Field field : fields) {
if (PropertyUtils.isReadable(bean, field.getName())) {
//To still work on
}
}
return null;
}
Example 27
Project: eMonocot-master File: FieldMatchValidator.java View source code |
@Override public boolean isValid(Object value, ConstraintValidatorContext context) { try { final Object firstObj = PropertyUtils.getProperty(value, firstFieldName); final Object secondObj = PropertyUtils.getProperty(value, secondFieldName); return firstObj == null && secondObj == null || firstObj != null && firstObj.equals(secondObj); } catch (final Exception ignore) { } return true; }
Example 28
Project: GitDirStat-master File: BeanPropertySync.java View source code |
private void trySetProperty(PropertyChangeEvent evt) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
String propertyName = evt.getPropertyName();
PropertyDescriptor propertyDescriptor = PropertyUtils.getPropertyDescriptor(targetBean, propertyName);
if (propertyDescriptor == null) {
if (!skipMissingPropertiesEnabled) {
String msg = MessageFormat.format("Can't find write method for property '{0}' of bean '{1}'", propertyName, targetBean.getClass());
throw new RuntimeException(msg);
}
} else {
Method writeMethod = propertyDescriptor.getWriteMethod();
writeMethod.invoke(targetBean, evt.getNewValue());
}
}
Example 29
Project: hecate-master File: PropertyFacetProvider.java View source code |
//----------------------------------------------------------------------------------------------------------------------
// FacetProvider Implementation
//----------------------------------------------------------------------------------------------------------------------
@Override
public List<Facet> getFacets(Class<?> pojoType) {
final PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(pojoType);
final List<Facet> facets = new ArrayList<>(descriptors.length);
for (PropertyDescriptor descriptor : descriptors) {
final Method readMethod = ReflectionUtils.getReadMethod(pojoType, descriptor);
final Method writeMethod = ReflectionUtils.getWriteMethod(pojoType, descriptor);
if (readMethod != null && writeMethod != null && !readMethod.isAnnotationPresent(Transient.class)) {
facets.add(new PropertyFacet(pojoType, descriptor, readMethod, writeMethod));
}
}
return facets;
}
Example 30
Project: infoglue-master File: SiteNodeComparator.java View source code |
private Comparable getProperty(Object o, String property) {
try {
Object propertyObject = PropertyUtils.getProperty(o, sortProperty);
if (propertyObject instanceof String)
return (Comparable) propertyObject.toString().toLowerCase();
else
return (Comparable) propertyObject;
} catch (Exception e) {
logger.info(getClass().getName() + " Error finding property " + property, e);
return null;
}
}
Example 31
Project: jboss-migration-master File: SimpleEvaluator.java View source code |
// BeanUtils
private String resolveProperty2(Object subject, String propPath) {
if (subject == null) {
return "";
}
if (propPath == null || propPath.isEmpty()) {
return subject.toString();
}
try {
return "" + PropertyUtils.getProperty(subject, propPath);
} catch (IllegalAccessExceptionInvocationTargetException | NoSuchMethodException | ex) {
log.warn("Failed resolving '" + propPath + "' on " + subject + ":\n " + ex.getMessage());
if (log.isTraceEnabled()) {
log.trace(" Stacktrace:\n", ex);
}
return "";
}
}
Example 32
Project: JCOOL-master File: Sandbox.java View source code |
/** * Listen for property changes and detect side-effects. If any side-effects * are detected reload the relevant properties. * * @see PropertyChangeListener#propertyChange(java.beans.PropertyChangeEvent) */ public void propertyChange(PropertyChangeEvent evt) { try { for (AbstractProperty defaultProperty : properties) { if (evt.getSource() != defaultProperty) { defaultProperty.setValue(PropertyUtils.getProperty(sandbox, defaultProperty.getFieldName()), false); // if the property has a state associated try updating the property state String fieldName = defaultProperty.getFieldName(); // workaround: PropertyUtils does not property detect the state property for single letter properties if (fieldName.length() == 1) { fieldName = fieldName.toUpperCase(); } if (PropertyUtils.isReadable(sandbox, fieldName + "State")) { defaultProperty.setPropertyState((PropertyState) PropertyUtils.getProperty(sandbox, fieldName + "State")); } } } } catch (IllegalAccessException ex) { Logger.getLogger(Sandbox.class.getName()).log(Level.SEVERE, null, ex); } catch (InvocationTargetException ex) { Logger.getLogger(Sandbox.class.getName()).log(Level.SEVERE, null, ex); } catch (NoSuchMethodException ex) { Logger.getLogger(Sandbox.class.getName()).log(Level.SEVERE, null, ex); } }
Example 33
Project: jrails-master File: SearchInColumnsPredicate.java View source code |
public boolean evaluate(Object bean) {
boolean match = false;
if (this.searchIn != null) {
for (String property : searchIn) {
try {
Object value = PropertyUtils.getProperty(bean, property);
if (value != null) {
String valueOf = String.valueOf(value);
match = this.doSearch(valueOf, searchCondition);
if (match) {
break;
}
}
} catch (IllegalAccessException ex) {
Logger.getLogger(SearchInColumnsPredicate.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvocationTargetException ex) {
Logger.getLogger(SearchInColumnsPredicate.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchMethodException ex) {
Logger.getLogger(SearchInColumnsPredicate.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
return match;
}
Example 34
Project: Json-lib-master File: TestJSONObjectStaticBuilders_PrimitiveBean.java View source code |
protected Object getSource() {
PrimitiveBean bean = new PrimitiveBean();
String[] props = getProperties();
try {
for (int i = 0; i < props.length; i++) {
PropertyUtils.setProperty(bean, props[i], PropertyConstants.getPropertyValue(props[i]));
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return bean;
}
Example 35
Project: kie-wb-common-master File: BackendPropertyValueExtractor.java View source code |
@Override protected Object readValue(Object model, String propertyName) { try { if (PropertyUtils.getPropertyDescriptor(model, propertyName) != null) { return PropertyUtils.getProperty(model, propertyName); } } catch (Exception e) { logger.warn("Error getting property '{}' from object '{}'", propertyName, model); logger.warn("Caused by:", e); } return null; }
Example 36
Project: minnal-master File: BiDirectionalObjectResolver.java View source code |
@Override
protected void setAttribute(Object pojo, AttributeMetaData attribute, Object value) {
super.setAttribute(pojo, attribute, value);
JsonManagedReference managedReference = attribute.getAnnotation(JsonManagedReference.class);
if (managedReference != null && value != null) {
PropertyDescriptor backReference = getManagedBackReference(value.getClass(), managedReference.value());
if (backReference != null) {
try {
PropertyUtils.setProperty(value, backReference.getName(), pojo);
} catch (Exception e) {
logger.info("Failed while setting the property {} on the class {}", backReference.getName(), value.getClass());
}
}
}
}
Example 37
Project: monits-commons-master File: FieldMatchValidator.java View source code |
@Override public boolean isValid(final Object value, final ConstraintValidatorContext context) { try { final Object firstObj = PropertyUtils.getProperty(value, firstFieldName); final Object secondObj = PropertyUtils.getProperty(value, secondFieldName); return type.isValid(firstObj, secondObj); } catch (final Exception ignore) { return false; } }
Example 38
Project: netxilia-master File: DefaultPropertySerializer.java View source code |
@Override
public String serializeProperty(T object, String property) {
Object propertyValue = null;
try {
propertyValue = PropertyUtils.getSimpleProperty(object, property);
return propertyValue != null ? propertyValue.toString() : null;
} catch (Exception e) {
log.error("Cannot get property " + property + ":" + e, e);
return null;
}
}
Example 39
Project: nubes-master File: DefaultParameterAdapter.java View source code |
@Override
public Object adaptParams(MultiMap params, Class<?> parameterClass) {
Object instance;
try {
instance = parameterClass.newInstance();
Field[] fields = parameterClass.getDeclaredFields();
for (Field field : fields) {
String requestValue = params.get(field.getName());
if (requestValue != null) {
Object value = adaptParam(requestValue, field.getType());
PropertyUtils.setProperty(instance, field.getName(), value);
}
}
} catch (InstantiationExceptionIllegalAccessException | NoSuchMethodException | InvocationTargetException | e) {
throw new IllegalArgumentException(e);
}
return instance;
}
Example 40
Project: oddjob-master File: ExecuteActionTest2.java View source code |
public void testClassLoader() throws Exception { ClassLoader startLoader = Thread.currentThread().getContextClassLoader(); String xml = "<oddjob>" + " <job>" + " <bean id='capture'" + " class='" + ClassLoaderCapture.class.getName() + "'/>" + " </job>" + "</oddjob>"; Oddjob oddjob = new Oddjob(); oddjob.setConfiguration(new XMLConfiguration("XML", xml)); MyClassLoader loader = new MyClassLoader(); ExecuteAction test = new ExecuteAction(); ExplorerModelImpl eModel = new ExplorerModelImpl(new StandardArooaSession()); eModel.setThreadManager(new SimpleThreadManager()); eModel.setOddjob(oddjob); ExplorerContextImpl rootContext = new ExplorerContextImpl(eModel); oddjob.setClassLoader(loader); oddjob.run(); assertTrue(startLoader == Thread.currentThread().getContextClassLoader()); Object capture = new OddjobLookup(oddjob).lookup("capture"); ((Resetable) capture).hardReset(); ExplorerContext ourContext = rootContext.addChild(capture); test.setSelectedContext(ourContext); test.action(); ClassLoader result = (ClassLoader) PropertyUtils.getProperty(capture, "result"); assertEquals(loader, result); ClassLoader context = (ClassLoader) PropertyUtils.getProperty(capture, "context"); assertEquals(startLoader, context); }
Example 41
Project: openelisglobal-core-master File: UomCreateAction.java View source code |
@Override protected ActionForward performAction(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ((DynaValidatorForm) form).initialize(mapping); PropertyUtils.setProperty(form, "existingUomList", DisplayListService.getList(DisplayListService.ListType.UNIT_OF_MEASURE)); PropertyUtils.setProperty(form, "inactiveUomList", DisplayListService.getList(DisplayListService.ListType.UNIT_OF_MEASURE_INACTIVE)); List<UnitOfMeasure> uoms = UnitOfMeasureService.getAllUnitOfMeasures(); PropertyUtils.setProperty(form, "existingEnglishNames", getExistingUomNames(uoms, ConfigurationProperties.LOCALE.ENGLISH)); PropertyUtils.setProperty(form, "existingFrenchNames", getExistingUomNames(uoms, ConfigurationProperties.LOCALE.FRENCH)); return mapping.findForward(FWD_SUCCESS); }
Example 42
Project: openmrs-module-reporting-master File: BeanPropertyComparator.java View source code |
/** * @see Comparator#compare(Object, Object) */ @SuppressWarnings({ "unchecked" }) @Override public int compare(Object left, Object right) { try { for (String token : sortSpecification.split(",")) { String[] values = token.trim().split(" "); String property = values[0]; boolean sortAsc = (values.length == 1 || !values[1].equalsIgnoreCase("desc")); Object valueLeft = PropertyUtils.getNestedProperty(left, property); Object valueRight = PropertyUtils.getNestedProperty(right, property); //We put NULLs at the bottom. if (valueLeft == null) return 1; if (valueRight == null) return -1; if (!valueLeft.equals(valueRight)) { int ret = ((Comparable) valueLeft).compareTo(valueRight); if (!sortAsc) { ret = (ret == 1 ? -1 : 1); } return ret; } //else values are equal. Try next sort property } } catch (Exception ex) { throw new IllegalArgumentException("Unable to compare " + left + " and " + right + " using sort specification: " + sortSpecification); } return 0; }
Example 43
Project: openmrs-module-webservices.rest-master File: MainResourceControllerTest.java View source code |
@Test
public void shouldGetRefByUuid() throws Exception {
MockHttpServletRequest request = request(RequestMethod.GET, getURI() + "/" + getUuid());
request.addParameter("v", "ref");
SimpleObject result = deserialize(handle(request));
Assert.assertNotNull(result);
Assert.assertEquals(getUuid(), PropertyUtils.getProperty(result, "uuid"));
}
Example 44
Project: pentaho-kettle-master File: NotNullValidator.java View source code |
public boolean validate(CheckResultSourceInterface source, String propertyName, List<CheckResultInterface> remarks, ValidatorContext context) {
Object value = null;
try {
value = PropertyUtils.getProperty(source, propertyName);
if (null == value) {
JobEntryValidatorUtils.addFailureRemark(source, propertyName, VALIDATOR_NAME, remarks, JobEntryValidatorUtils.getLevelOnFail(context, VALIDATOR_NAME));
return false;
} else {
return true;
}
} catch (IllegalAccessException e) {
JobEntryValidatorUtils.addExceptionRemark(source, propertyName, VALIDATOR_NAME, remarks, e);
} catch (InvocationTargetException e) {
JobEntryValidatorUtils.addExceptionRemark(source, propertyName, VALIDATOR_NAME, remarks, e);
} catch (NoSuchMethodException e) {
JobEntryValidatorUtils.addExceptionRemark(source, propertyName, VALIDATOR_NAME, remarks, e);
}
return false;
}
Example 45
Project: rhq-master File: SimpleConverter.java View source code |
@Override
public Object convert(T object, String propertyName) {
try {
return PropertyUtils.getProperty(object, propertyName);
} catch (IllegalAccessException e) {
throw new CsvWriterException("Unable to get property value " + object.getClass().getName() + "." + propertyName + " for " + object, e);
} catch (InvocationTargetException e) {
throw new CsvWriterException("Unable to get property value " + object.getClass().getName() + "." + propertyName + " for " + object, e);
} catch (NoSuchMethodException e) {
throw new CsvWriterException("Unable to get property value " + object.getClass().getName() + "." + propertyName + " for " + object, e);
}
}
Example 46
Project: RMT-master File: RowCountChecker.java View source code |
private Long rowCount(final IEntity entity, final List<String> attributeNames, final EntityManager em) {
final Class<? extends IEntity> entityClass = entity.getClass();
final CriteriaBuilder cb = em.getCriteriaBuilder();
final CriteriaQuery<Long> query = cb.createQuery(Long.class);
final Root<? extends IEntity> root = query.from(entityClass);
query.select(cb.count(root));
Predicate condition = null;
for (final String attributeName : attributeNames) {
Predicate tmp;
try {
tmp = cb.equal(root.<Object>get(attributeName), PropertyUtils.getProperty(entity, attributeName));
// CHECKSTYLE IGNORE 1 LINES
} catch (final Exception e) {
throw new RuntimeException(e);
}
condition = (condition == null) ? tmp : cb.and(condition, tmp);
}
// update on existing element? exclude the element itself
if (!entity.isNew()) {
condition = cb.and(condition, cb.notEqual(root.<Long>get("id"), "" + entity.getId()));
}
query.where(condition);
return em.createQuery(query).getSingleResult();
}
Example 47
Project: RT-REST-master File: FieldProcessorRegistry.java View source code |
public FieldProcessor getTicketFieldProcessor(RTTicket ticket, String ticketFieldName) {
FieldProcessor fieldProcessor = null;
Matcher m = RTCustomField.PATTERN_CUSTOM_FIELD_NAME.matcher(ticketFieldName);
if (m.matches()) {
fieldProcessor = customFieldProcessors.get(m.group(1));
if (fieldProcessor == null) {
fieldProcessor = DefaultCustomFieldProcessor.getInstance();
}
} else {
fieldProcessor = standardFieldProcessors.get(ticketFieldName);
if (fieldProcessor == null) {
try {
fieldProcessor = typeFieldProcessors.get(PropertyUtils.getPropertyType(ticket, StringUtils.uncapitalize(ticketFieldName)));
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
return (fieldProcessor != null) ? fieldProcessor : DefaultFieldProcessor.getInstance();
}
Example 48
Project: sculptor-master File: IdReflectionUtil.java View source code |
public static Serializable internalGetId(Object domainObject) { if (domainObject instanceof Identifiable) { return ((Identifiable) domainObject).getId(); } if (PropertyUtils.isReadable(domainObject, "id")) { try { return (Serializable) PropertyUtils.getProperty(domainObject, "id"); } catch (Exception e) { throw new IllegalArgumentException("Can't get id property of domainObject: " + domainObject); } } else { // no id property, don't know if it is new throw new IllegalArgumentException("No id property in domainObject: " + domainObject); } }
Example 49
Project: SOAP-master File: TestStepBeanProperty.java View source code |
public String getValue(DefaultTestStepProperty prop) {
try {
Object property = PropertyUtils.getProperty(target, targetName);
return property == null ? null : property.toString();
} catch (Exception e) {
if (target instanceof ModelItem) {
SoapUI.logError(new Exception("Error getting property [" + targetName + "] from modelItem [" + ((ModelItem) target).getName() + "]", e));
} else {
SoapUI.logError(new Exception("Error getting property [" + targetName + "] from bean [" + target + "]", e));
}
return null;
}
}
Example 50
Project: soapui-master File: TestStepBeanProperty.java View source code |
public String getValue(DefaultTestStepProperty prop) {
try {
Object property = PropertyUtils.getProperty(target, targetName);
return property == null ? null : property.toString();
} catch (Exception e) {
if (target instanceof ModelItem) {
SoapUI.logError(new Exception("Error getting property [" + targetName + "] from modelItem [" + ((ModelItem) target).getName() + "]", e));
} else {
SoapUI.logError(new Exception("Error getting property [" + targetName + "] from bean [" + target + "]", e));
}
return null;
}
}
Example 51
Project: struts-master File: FieldMatchValidator.java View source code |
public boolean isValid(final Object value, final ConstraintValidatorContext context) { try { final Object firstObj = PropertyUtils.getProperty(value, this.firstFieldName); final Object secondObj = PropertyUtils.getProperty(value, this.secondFieldName); return firstObj == null && secondObj == null || firstObj != null && firstObj.equals(secondObj); } catch (final Exception ex) { LOG.info("Error while getting values from object", ex); return false; } }
Example 52
Project: tapestry-model-master File: AnnotationHandlerUtils.java View source code |
/**
* For each attribute of annotation, will search for a matching property on
* the target and set it with the value of the attribute unless the attribute
* is set to the "default" value
*
* @param annotation
* @param descriptor
*/
public static void setPropertiesFromAnnotation(Annotation annotation, Object target) {
/**
* !! This is how we get our properties migrated from our
* annotation to our property descriptor !!
*/
for (Method annotationMethod : annotation.getClass().getMethods()) {
try {
if (!isDefault(annotation, annotationMethod)) {
PropertyUtils.setProperty(target, annotationMethod.getName(), annotationMethod.invoke(annotation));
}
} catch (Exception e) {
}
}
}
Example 53
Project: tapestry5-cli-master File: ApplicationConfigurationSourceImplTest.java View source code |
@Test public void injectValues() throws ParseException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { String[] args = new String[] { "-a", "10", "--beta", "7", "-g", "the gamma input", "first-arg", "second-args", "whaterver" }; Options options = new Options(); options.addOption(new Option("a", "alfa", true, "alfa-description")); options.addOption(new Option("b", "beta", true, "beta-description")); options.addOption(new Option("g", "gamma", true, "This is gamma")); CommandLine parsedOptions = (new BasicParser()).parse(options, args); Object bean = new BeanA(); // Fill the matching props of the Bean Map properties = PropertyUtils.describe(bean); for (Option option : parsedOptions.getOptions()) { String propertyName = option.getLongOpt(); System.out.println("propertyName " + propertyName); if (properties.containsKey(propertyName)) { System.out.println("The bean contains the property " + propertyName + ". Set its value "); PropertyDescriptor descriptor = PropertyUtils.getPropertyDescriptor(bean, propertyName); System.out.println("PropertyType " + descriptor.getPropertyType()); PropertyUtils.setProperty(bean, propertyName, option.getValue()); } else { System.out.println("The bean does not contains the property " + propertyName); } // PropertyDescriptor propertyDescriptor = PropertyUtils // .getPropertyDescriptor(aBean, propertyName); // System.out // .println("ApplicationConfigurationSourceImpl.injectValues() " // + propertyName); } // PropertyUtils }
Example 54
Project: unomi-master File: IncrementInterestsValuesAction.java View source code |
@SuppressWarnings("unchecked")
@Override
public int execute(Action action, Event event) {
boolean modified = false;
try {
Map<String, Object> interests = (Map<String, Object>) PropertyUtils.getProperty(event, "target.properties.interests");
if (interests != null) {
for (Map.Entry<String, Object> s : interests.entrySet()) {
int value = (Integer) s.getValue();
HashMap<String, Object> profileInterests = (HashMap<String, Object>) event.getProfile().getProperty("interests");
if (profileInterests != null) {
profileInterests = new HashMap<String, Object>(profileInterests);
int oldValue = (profileInterests.containsKey(s.getKey())) ? (Integer) profileInterests.get(s.getKey()) : 0;
profileInterests.put(s.getKey(), value + oldValue);
} else {
profileInterests = new HashMap<String, Object>();
profileInterests.put(s.getKey(), value);
}
event.getProfile().setProperty("interests", profileInterests);
modified = true;
}
}
} catch (UnsupportedOperationException e) {
throw e;
} catch (Exception e) {
throw new UnsupportedOperationException(e);
}
return modified ? EventService.PROFILE_UPDATED : EventService.NO_CHANGE;
}
Example 55
Project: xtext-master File: IdReflectionUtil.java View source code |
public static Serializable internalGetId(Object domainObject) { if (domainObject instanceof Identifiable) { return ((Identifiable) domainObject).getId(); } if (PropertyUtils.isReadable(domainObject, "id")) { try { return (Serializable) PropertyUtils.getProperty(domainObject, "id"); } catch (Exception e) { throw new IllegalArgumentException("Can't get id property of domainObject: " + domainObject); } } else { // no id property, don't know if it is new throw new IllegalArgumentException("No id property in domainObject: " + domainObject); } }
Example 56
Project: liferay-portal-master File: JavaIllegalImportsCheck.java View source code |
@Override protected String doProcess(String fileName, String absolutePath, String content) { if (fileName.endsWith("JavaIllegalImportsCheck.java")) { return content; } content = StringUtil.replace(content, new String[] { "com.liferay.portal.PortalException", "com.liferay.portal.SystemException", "com.liferay.util.LocalizationUtil" }, new String[] { "com.liferay.portal.kernel.exception.PortalException", "com.liferay.portal.kernel.exception.SystemException", "com.liferay.portal.kernel.util.LocalizationUtil" }); if (!isExcludedPath(RUN_OUTSIDE_PORTAL_EXCLUDES, absolutePath) && !isExcludedPath(_PROXY_EXCLUDES, absolutePath) && content.contains("import java.lang.reflect.Proxy;")) { addMessage(fileName, "Use ProxyUtil instead of java.lang.reflect.Proxy"); } if (content.contains("import edu.emory.mathcs.backport.java")) { addMessage(fileName, "Illegal import: edu.emory.mathcs.backport.java"); } if (content.contains("import jodd.util.StringPool")) { addMessage(fileName, "Illegal import: jodd.util.StringPool"); } if (!isExcludedPath(RUN_OUTSIDE_PORTAL_EXCLUDES, absolutePath) && !isExcludedPath(_SECURE_RANDOM_EXCLUDES, absolutePath) && content.contains("java.security.SecureRandom") && !content.contains("javax.crypto.KeyGenerator")) { addMessage(fileName, "Use SecureRandomUtil or com.liferay.portal.kernel.security." + "SecureRandom instead of java.security.SecureRandom, see " + "LPS-39058"); } if (content.contains("com.liferay.portal.kernel.util.UnmodifiableList")) { addMessage(fileName, "Use java.util.Collections.unmodifiableList instead of " + "com.liferay.portal.kernel.util.UnmodifiableList, see " + "LPS-45027"); } if (isPortalSource() && absolutePath.contains("/portal-kernel/") && content.contains("import javax.servlet.jsp.")) { addMessage(fileName, "Never import javax.servlet.jsp.* from portal-kernel, see " + "LPS-47682"); } if (content.contains("org.testng.Assert")) { addMessage(fileName, "Use org.junit.Assert instead of org.testng.Assert, see " + "LPS-55690"); } if (content.contains(".supportsBatchUpdates()") && !fileName.endsWith("AutoBatchPreparedStatementUtil.java")) { addMessage(fileName, "Use AutoBatchPreparedStatementUtil instead of " + "DatabaseMetaData.supportsBatchUpdates, see LPS-60473"); } if (!fileName.endsWith("TypeConvertorUtil.java") && content.contains("org.apache.commons.beanutils.PropertyUtils")) { addMessage(fileName, "Do not use org.apache.commons.beanutils.PropertyUtils, see " + "LPS-62786"); } if (content.contains("Configurable.createConfigurable(") && !fileName.endsWith("ConfigurableUtil.java")) { addMessage(fileName, "Use ConfigurableUtil.createConfigurable instead of " + "Configurable.createConfigurable, see LPS-64056"); } if (fileName.endsWith("ResourceCommand.java") && content.contains("ServletResponseUtil.sendFile(")) { addMessage(fileName, "Use PortletResponseUtil.sendFile instead of " + "ServletResponseUtil.sendFile, see LPS-65229"); } if (!fileName.endsWith("AbstractExtender.java") && content.contains("org.apache.felix.utils.extender.AbstractExtender")) { StringBundler sb = new StringBundler(4); sb.append("Use com.liferay.osgi.felix.util.AbstractExtender "); sb.append("instead of "); sb.append("org.apache.felix.utils.extender.AbstractExtender, see "); sb.append("LPS-69494"); addMessage(fileName, sb.toString()); } if (content.contains("java.util.WeakHashMap")) { addMessage(fileName, "Do not use java.util.WeakHashMap because it is not " + "thread-safe, see LPS-70963"); } return content; }
Example 57
Project: aperte-workflow-core-master File: JasperReportingUtil.java View source code |
public static Object expandPath(String path, Object o) {
if (o == null)
return null;
try {
return PropertyUtils.getProperty(o, path);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
}
Example 58
Project: BlueSoft-Util-master File: NullUtil.java View source code |
public static boolean hasOnlyNullFields(final Object o) {
for (Field f : getFieldsFromClassAndAncestors(o.getClass())) {
try {
if (PropertyUtils.getProperty(o, f.getName()) != null) {
return false;
}
} catch (Exception e) {
throw new UtilityInvocationException(e);
}
}
return true;
}
Example 59
Project: Broadleaf-eCommerce-master File: BRCVariableExpression.java View source code |
public Object get(String propertyName) {
BroadleafRequestContext brc = BroadleafRequestContext.getBroadleafRequestContext();
if (brc != null) {
try {
return PropertyUtils.getProperty(brc, propertyName);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return null;
}
Example 60
Project: BroadleafCommerce-master File: BRCVariableExpression.java View source code |
public Object get(String propertyName) {
BroadleafRequestContext brc = BroadleafRequestContext.getBroadleafRequestContext();
if (brc != null) {
try {
return PropertyUtils.getProperty(brc, propertyName);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return null;
}
Example 61
Project: clouck-master File: AbstractResource.java View source code |
public String getUniqueId() {
ResourceType rt = ResourceType.find(this);
String uniqueIds = "";
for (String uniqueIdName : rt.getUniqueIdNames()) {
try {
uniqueIds += PropertyUtils.getSimpleProperty(this.getResource(), uniqueIdName);
} catch (Exception e) {
throw new ClouckError(e);
}
}
return uniqueIds;
}
Example 62
Project: commerce-master File: BRCVariableExpression.java View source code |
public Object get(String propertyName) {
BroadleafRequestContext brc = BroadleafRequestContext.getBroadleafRequestContext();
if (brc != null) {
try {
return PropertyUtils.getProperty(brc, propertyName);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return null;
}
Example 63
Project: DDao-master File: DefaultParameter.java View source code |
public Object extractParam(Context context) throws SQLException {
final MethodCallCtx callCtx = CtxHelper.get(context, MethodCallCtx.class);
Object[] args = callCtx.getArgs();
Object param;
if (num != null) {
if (num == RETURN_ARG_IDX) {
param = callCtx.getLastReturn();
} else {
if (args.length <= num) {
throw new SQLException("Query refers to argument #" + num + ", while method has only " + args.length + " arguments");
}
param = args[num];
}
} else {
param = args[0];
}
if (propName == null) {
return param;
}
if (param instanceof Map) {
return ((Map) param).get(propName);
}
try {
return PropertyUtils.getProperty(param, propName);
} catch (Exception e) {
throw new SQLException("Failed to get statement parameter " + name + " from " + param, e);
}
}
Example 64
Project: eXtremecomponents-master File: FilterPredicate.java View source code |
/**
* Use the filter parameters to filter out the table.
*/
public boolean evaluate(Object bean) {
boolean match = false;
try {
for (Iterator<Filter> iter = filters.iterator(); iter.hasNext(); ) {
Filter filter = iter.next();
String filterValue = filter.getValue();
if (StringUtils.isEmpty(filterValue)) {
continue;
}
String property = filter.getProperty();
Object value = PropertyUtils.getProperty(bean, property);
if (value == null) {
continue;
}
if (!isSearchMatch(value.toString(), filterValue)) {
// as soon as fail just short circuit
match = false;
break;
}
match = true;
}
} catch (Exception e) {
logger.error("FilterPredicate.evaluate() had problems", e);
}
return match;
}
Example 65
Project: fenix-ist-master File: TransferDomainObjectProperty.java View source code |
@Atomic public static void run(DomainObject srcObject, DomainObject dstObject, String slotName) throws FenixServiceException { AccessControl.check(RolePredicates.MANAGER_PREDICATE); try { Object srcProperty = PropertyUtils.getSimpleProperty(srcObject, slotName); if (srcProperty != null && srcProperty instanceof Collection) { Collection srcCollection = (Collection) srcProperty; Object dstProperty = PropertyUtils.getSimpleProperty(dstObject, slotName); if (dstProperty instanceof Collection) { Collection dstCollection = (Collection) dstProperty; dstCollection.addAll(srcCollection); } } else { PropertyUtils.setSimpleProperty(dstObject, slotName, srcProperty); } } catch (InvocationTargetException e) { if (e.getTargetException() != null) { if (e.getTargetException() instanceof WriteOnReadError) { throw ((WriteOnReadError) e.getTargetException()); } throw new FenixServiceException(e.getTargetException()); } throw new FenixServiceException(e); } catch (IllegalAccessException e) { throw new FenixServiceException(e); } catch (NoSuchMethodException e) { throw new FenixServiceException(e); } }
Example 66
Project: fenixedu-academic-master File: AbstractSearchObjects.java View source code |
protected Collection<T> process(Collection<T> objects, String value, int limit, Map<String, String> arguments) {
List<T> result;
String slotName = arguments.get("slot");
if (value == null) {
result = (List<T>) objects;
} else {
result = new ArrayList<T>();
String[] values = StringNormalizer.normalize(value).split("\\p{Space}+");
outter: for (T object : objects) {
try {
String objectValue = (String) PropertyUtils.getProperty(object, slotName);
if (objectValue == null) {
continue;
}
String normalizedValue = StringNormalizer.normalize(objectValue);
for (int i = 0; i < values.length; i++) {
String part = values[i];
if (!normalizedValue.contains(part)) {
continue outter;
}
}
result.add(object);
if (result.size() >= limit) {
break;
}
} catch (IllegalAccessException e) {
throw new DomainException("searchObject.type.notFound", e);
} catch (InvocationTargetException e) {
throw new DomainException("searchObject.failed.read", e);
} catch (NoSuchMethodException e) {
throw new DomainException("searchObject.failed.read", e);
}
}
}
Collections.sort(result, new BeanComparator(slotName));
return result;
}
Example 67
Project: gtitool-master File: JToggleButtonBinding.java View source code |
public void put(IValidatable bean) {
try {
// String s = BeanUtils.getProperty(o, _property);
// _checkBox.setSelected("true".equals(s));
Boolean b = (Boolean) PropertyUtils.getProperty(bean, _property);
_button.setSelected(b != null && b.booleanValue());
} catch (Exception e) {
throw new BindingException(e);
}
}
Example 68
Project: HermesJMS-master File: BeanPropertyPanel.java View source code |
protected void onSetProperty(String propertyName, Object propertyValue) {
try {
if (setProperty) {
PropertyUtils.setProperty(bean, propertyName, propertyValue);
}
super.onSetProperty(propertyName, propertyValue);
} catch (Throwable e) {
HermesBrowser.getBrowser().showErrorDialog("Cannot set property " + propertyName, e);
}
}
Example 69
Project: iaf-master File: AttributeCheckingRule.java View source code |
public void begin(String uri, String elementName, Attributes attributes) throws Exception { Object top = digester.peek(); for (int i = 0; i < attributes.getLength(); i++) { String name = attributes.getLocalName(i); if ("".equals(name)) { name = attributes.getQName(i); } if (name != null && !name.equals("className")) { // if (log.isDebugEnabled()) { // log.debug(getObjectName(top)+" checking for setter for attribute ["+name+"]"); // } PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(top, name); Method m = null; if (pd != null) { m = PropertyUtils.getWriteMethod(pd); } if (m == null) { Locator loc = digester.getDocumentLocator(); String msg = "line " + loc.getLineNumber() + ", col " + loc.getColumnNumber() + ": " + getObjectName(top) + " does not have an attribute [" + name + "] to set to value [" + attributes.getValue(name) + "]"; configWarnings.add(log, msg); } } } }
Example 70
Project: IsoMsgActionLib-master File: ISOMsgActionUpdateExecutionContext.java View source code |
/* (non-Javadoc)
* @see org.jpos.jposext.isomsgaction.service.IISOMsgAction#process(org.jpos.iso.ISOMsg[], java.util.Map)
*/
public void process(ISOMsg[] msg, Map<String, Object> ctx) throws ISOException {
// R�cup�ration de la valeur du champ source ...
String attrValue = ISOMsgHelper.getStringValue(msg[getSrcMsgIndex()], getSrcIdPath());
if (null != attrValue) {
if (fixedLength > 0) {
// fixedLength
if (attrValue.length() > fixedLength) {
// On fait un truncate sur la valeur.
attrValue = attrValue.substring(0, fixedLength);
} else {
// on pad � doite avec des blancs
attrValue = padright(attrValue, fixedLength, ' ');
}
}
}
if (null != getValueBeanPath()) {
try {
PropertyUtils.setProperty(new SimpleContextWrapper(ctx), getValueBeanPath(), attrValue);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
Example 71
Project: jcommune-master File: AtLeastOneFieldIsNotNullValidator.java View source code |
/**
* {@inheritDoc}
*/
@Override
public boolean isValid(Object entity, ConstraintValidatorContext constraintValidatorContext) {
try {
for (String field : fields) {
try {
if (PropertyUtils.getProperty(entity, field) != null) {
return true;
}
} catch (NoSuchMethodException e) {
Field fieldObject = entity.getClass().getDeclaredField(field);
fieldObject.setAccessible(true);
if (fieldObject.get(entity) != null) {
return true;
}
}
}
} catch (IllegalAccessExceptionInvocationTargetException | NoSuchFieldException | e) {
throw new ConstraintDeclarationException(e);
}
return false;
}
Example 72
Project: jTalk-master File: AtLeastOneFieldIsNotNullValidator.java View source code |
/**
* {@inheritDoc}
*/
@Override
public boolean isValid(Object entity, ConstraintValidatorContext constraintValidatorContext) {
try {
for (String field : fields) {
try {
if (PropertyUtils.getProperty(entity, field) != null) {
return true;
}
} catch (NoSuchMethodException e) {
Field fieldObject = entity.getClass().getDeclaredField(field);
fieldObject.setAccessible(true);
if (fieldObject.get(entity) != null) {
return true;
}
}
}
} catch (IllegalAccessExceptionInvocationTargetException | NoSuchFieldException | e) {
throw new ConstraintDeclarationException(e);
}
return false;
}
Example 73
Project: kfs-master File: ObjectValueUtils.java View source code |
/**
* This method uses simple getter/setter methods to copy object values from a original object to destination object
*
* @param origin original object
* @param destination destination object
*/
public static void copySimpleProperties(Object origin, Object destination) {
try {
Object[] empty = new Object[] {};
PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(origin.getClass());
for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
if (propertyDescriptor.getReadMethod() != null && propertyDescriptor.getWriteMethod() != null) {
Object value = propertyDescriptor.getReadMethod().invoke(origin, empty);
if (value != null) {
propertyDescriptor.getWriteMethod().invoke(destination, value);
}
}
}
} catch (Exception e) {
throw new RuntimeException("Unexpected error while copying properties.", e);
}
}
Example 74
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 75
Project: milton-master File: ICalDataAnnotationHandler.java View source code |
public String execute(AnnoEventResource eventRes) { Object source = eventRes.getSource(); try { Object value = null; ControllerMethod cm = getBestMethod(source.getClass()); if (cm == null) { // look for an annotation on the source itself java.lang.reflect.Method m = annoResourceFactory.findMethodForAnno(source.getClass(), annoClass); if (m != null) { value = m.invoke(source, (Object) null); } else { for (String nameProp : CTAG_PROP_NAMES) { if (PropertyUtils.isReadable(source, nameProp)) { Object oPropVal = PropertyUtils.getProperty(source, nameProp); value = oPropVal; break; } } } } else { ByteArrayOutputStream bout = new ByteArrayOutputStream(); value = invoke(cm, eventRes, bout); // These methods will often write to output stream, so must provide one as alternative to returning a value if (// probably means void return type, so use outputstream value == null) { byte[] arr = bout.toByteArray(); if (arr.length > 0) { value = arr; } } } if (value != null) { if (value instanceof String) { return (String) value; } else if (value instanceof byte[]) { byte[] bytes = (byte[]) value; return new String(bytes, "UTF-8"); } else if (value instanceof InputStream) { InputStream in = (InputStream) value; ByteArrayOutputStream bout = new ByteArrayOutputStream(); IOUtils.copy(in, bout); return bout.toString("UTF-8"); } else { return value.toString(); } } else { return null; } } catch (Exception e) { throw new RuntimeException("Exception executing " + getClass() + " - " + source.getClass(), e); } }
Example 76
Project: milton2-master File: ICalDataAnnotationHandler.java View source code |
public String execute(AnnoEventResource eventRes) { Object source = eventRes.getSource(); try { Object value = null; ControllerMethod cm = getBestMethod(source.getClass()); if (cm == null) { // look for an annotation on the source itself java.lang.reflect.Method m = annoResourceFactory.findMethodForAnno(source.getClass(), annoClass); if (m != null) { value = m.invoke(source, (Object) null); } else { for (String nameProp : CTAG_PROP_NAMES) { if (PropertyUtils.isReadable(source, nameProp)) { Object oPropVal = PropertyUtils.getProperty(source, nameProp); value = oPropVal; break; } } } } else { ByteArrayOutputStream bout = new ByteArrayOutputStream(); value = invoke(cm, eventRes, bout); // These methods will often write to output stream, so must provide one as alternative to returning a value if (// probably means void return type, so use outputstream value == null) { byte[] arr = bout.toByteArray(); if (arr.length > 0) { value = arr; } } } if (value != null) { if (value instanceof String) { return (String) value; } else if (value instanceof byte[]) { byte[] bytes = (byte[]) value; return new String(bytes, "UTF-8"); } else if (value instanceof InputStream) { InputStream in = (InputStream) value; ByteArrayOutputStream bout = new ByteArrayOutputStream(); IOUtils.copy(in, bout); return bout.toString("UTF-8"); } else { return value.toString(); } } else { return null; } } catch (Exception e) { throw new RuntimeException("Exception executing " + getClass() + " - " + source.getClass(), e); } }
Example 77
Project: model-citizen-master File: JavaBeanTemplate.java View source code |
public <T> T set(T model, String property, Object value) throws BlueprintTemplateException {
try {
PropertyUtils.setProperty(model, property, value);
} catch (IllegalAccessException propertyException) {
throw new BlueprintTemplateException(propertyException);
} catch (InvocationTargetException propertyException) {
throw new BlueprintTemplateException(propertyException);
} catch (NoSuchMethodException propertyException) {
throw new BlueprintTemplateException(propertyException);
}
return model;
}
Example 78
Project: mycar-master File: WashingCostControlller.java View source code |
@Ajax
@RequestMapping(value = "/add", method = RequestMethod.POST)
@ResponseBody
public Object addParkingCost(@Valid WashingCostForm form, BindingResult bindingResult) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
if (bindingResult.hasErrors()) {
LOGGER.debug("数�绑定错误");
LOGGER.debug("{}", bindingResult.getAllErrors());
throw new DataBindingException(messageSource, bindingResult);
}
WashingCost washingCost = new WashingCost();
PropertyUtils.copyProperties(washingCost, form);
washingCostService.addWashingCost(washingCost);
LOGGER.debug("{}", washingCost);
return ControllerSupport.SUCCESS;
}
Example 79
Project: nocket-master File: SortableGenericDataProvider.java View source code |
public int compare(T o1, T o2) { int dir = getSort().isAscending() ? 1 : -1; String sortProperty = getSort().getProperty(); Object prop1 = null; Object prop2 = null; Class propType = null; try { prop1 = PropertyUtils.getProperty(o1, sortProperty); prop2 = PropertyUtils.getProperty(o2, sortProperty); propType = PropertyUtils.getPropertyType(o1, sortProperty); } catch (Exception e) { e.printStackTrace(); return 0; } return dir * compareByProperty(propType, prop1, prop2); }
Example 80
Project: nuxeo-core-master File: Log4jWebFilter.java View source code |
protected void putProperty(Object object, String propertyName) {
try {
if (object != null) {
String name = propertyName.substring(0, 1).toLowerCase() + propertyName.substring(1);
Object prop = PropertyUtils.getProperty(object, name);
if (prop != null) {
MDC.put(propertyName, prop);
}
}
} catch (Exception e) {
log.error(e, e);
}
}
Example 81
Project: nuxeo-master File: Log4jWebFilter.java View source code |
protected void putProperty(Object object, String propertyName) {
try {
if (object != null) {
String name = propertyName.substring(0, 1).toLowerCase() + propertyName.substring(1);
Object prop = PropertyUtils.getProperty(object, name);
if (prop != null) {
MDC.put(propertyName, prop);
}
}
} catch (ReflectiveOperationException e) {
log.error(e, e);
}
}
Example 82
Project: occurrence-master File: FullTextFieldBuilder.java View source code |
/**
* Collects all the values for the full_text field.
*/
public static Set<String> buildFullTextField(Occurrence occurrence) {
Set<String> fullTextField = new HashSet<String>();
try {
for (Map.Entry<String, Object> properties : PropertyUtils.describe(occurrence).entrySet()) {
Object value = properties.getValue();
if (value != null && !nonFullTextTypes(value)) {
fullTextField.add(value.toString());
}
}
for (Map.Entry<Term, String> verbatimField : occurrence.getVerbatimFields().entrySet()) {
if (verbatimField.getValue() != null && !NON_FULL_TEXT_TERMS.contains(verbatimField.getKey())) {
fullTextField.add(verbatimField.getValue());
}
}
if (occurrence.getYear() != null) {
fullTextField.add(occurrence.getYear().toString());
}
if (occurrence.getMonth() != null) {
fullTextField.add(occurrence.getMonth().toString());
}
if (occurrence.getDay() != null) {
fullTextField.add(occurrence.getDay().toString());
}
} catch (Exception ex) {
LOG.error("Error extracting values for the full_text field", ex);
}
return fullTextField;
}
Example 83
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 84
Project: openlegacy-master File: DefaultHtmlTableWriter.java View source code |
public void writeTable(List<? extends Object> records, OutputStream outputStream) {
DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
Document doc;
try {
doc = dfactory.newDocumentBuilder().newDocument();
Element tableTag = (Element) doc.appendChild(doc.createElement(HtmlConstants.TABLE));
if (records.size() == 0) {
return;
}
Object firstRecord = records.get(0);
PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(firstRecord);
// render headers with display name of the fields
Element rowTag = createTag(tableTag, HtmlConstants.TR);
for (PropertyDescriptor propertyDescriptor : descriptors) {
if (TypesUtil.isPrimitive(propertyDescriptor.getPropertyType())) {
Element headerTag = createTag(rowTag, HtmlConstants.TH);
String displayName = StringUtil.toDisplayName(propertyDescriptor.getName());
setCellValue(headerTag, displayName);
}
}
for (Object object : records) {
rowTag = createTag(tableTag, HtmlConstants.TR);
for (PropertyDescriptor propertyDescriptor : descriptors) {
if (TypesUtil.isPrimitive(propertyDescriptor.getPropertyType())) {
Element cellTag = createTag(rowTag, HtmlConstants.TD);
Object value = propertyDescriptor.getReadMethod().invoke(object);
if (value == null) {
value = "";
}
setCellValue(cellTag, String.valueOf(value));
}
}
}
DomUtils.render(doc, outputStream);
} catch (Exception e) {
throw (new GenerationException(e));
}
}
Example 85
Project: openmrs-module-patientmatching-master File: MatchingUtils.java View source code |
/**
* Inspect a class and retrieve all readable and writable properties of
* that class excluding properties defined in the input parameter
* <code>listExcludedProperties</code>. This method call will return only
* simple properties defined in the {@link MatchingIntrospector MatchingIntrospector} class
*
* @param listExcludedProperties list of properties that shouldn't be returned
* @param clazz class that will be introspected for the properties
* @return properties list of the class excluding all properties defined in the <code>listExcludedProperties</code>
* @see MatchingIntrospector
*/
@SuppressWarnings("unchecked")
public static List<String> introspectBean(List<String> listExcludedProperties, Class clazz) {
PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(clazz);
List<String> propertyList = new ArrayList<String>();
for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
if (propertyDescriptor.getReadMethod() != null && propertyDescriptor.getWriteMethod() != null) {
boolean exclude = false;
String propertyName = propertyDescriptor.getName();
if (propertyName != null) {
Iterator<String> exclusions = listExcludedProperties.iterator();
while (!exclude && exclusions.hasNext()) {
String excludedProperty = exclusions.next().trim().toUpperCase();
exclude = StringUtils.isNotBlank(excludedProperty) && propertyName.toUpperCase().contains(excludedProperty);
}
}
if (!exclude) {
if (MatchingIntrospector.isSimpleProperty(propertyDescriptor.getPropertyType())) {
propertyList.add(clazz.getName() + "." + propertyDescriptor.getName());
}
}
}
}
return propertyList;
}
Example 86
Project: park_java-master File: InventorySolrSearchServiceExtensionHandler.java View source code |
/**
* 建分仓索引
*/
@Override
public ExtensionResultStatusType addPropertyValues(Product product, Field field, FieldType fieldType, Map<String, Object> values, String propertyName, List<Locale> locales) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
if (propertyName.contains(INVENTORY_MAP)) {
String propName = propertyName.substring(INVENTORY_MAP.length() + 1);
// 默认sku的库å˜ç›¸å…³
List<Inventory> inventories = inventoryService.listInventories(product.getDefaultSku());
for (Inventory inv : inventories) {
Object val = PropertyUtils.getProperty(inv, propName);
values.put("loc" + val, "1");
}
return ExtensionResultStatusType.HANDLED;
} else {
return ExtensionResultStatusType.NOT_HANDLED;
}
}
Example 87
Project: SOEMPI-master File: ConvertingWrapDynaBean.java View source code |
public Object get(String name) {
Object value = null;
try {
value = PropertyUtils.getNestedProperty(instance, name);
} catch (InvocationTargetException ite) {
Throwable cause = ite.getTargetException();
throw new IllegalArgumentException("Error reading property '" + name + "' nested exception - " + cause);
} catch (Throwable t) {
throw new IllegalArgumentException("Error reading property '" + name + "', exception - " + t);
}
return (value);
}
Example 88
Project: Tank-master File: PropertyComparer.java View source code |
/** * @{inheritDoc */ @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public int compare(T src, T tgt) { int retVal = 0; if (src == null && tgt == null) { retVal = 0; } else if (src != null && tgt == null) { retVal = 1; } else if (src == null && tgt != null) { retVal = -1; } else { try { Object property = PropertyUtils.getProperty(src, propertyName); Object property2 = PropertyUtils.getProperty(tgt, propertyName); if (property == null && property2 == null) { retVal = 0; } else if (property == null && property2 != null) { retVal = -1; } else if (property != null && property2 == null) { retVal = 1; } else if (Comparable.class.isAssignableFrom(property.getClass())) { Comparable c1 = (Comparable) property; Comparable c2 = (Comparable) property2; retVal = c1.compareTo(c2); } else { retVal = property.toString().compareTo(property2.toString()); } } catch (IllegalAccessException e) { throw new RuntimeException("Cannot access the method. Possible error in setting the access type for the getter setters of " + propertyName); } catch (InvocationTargetException e) { throw new RuntimeException(e.getMessage()); } catch (NoSuchMethodException e) { throw new RuntimeException("No getter/setter method found for " + propertyName); } } if (sortOrder == SortOrder.DESCENDING) { retVal = retVal * -1; } return retVal; }
Example 89
Project: asta4d-master File: AbstractDbManager.java View source code |
@SuppressWarnings("unchecked")
public synchronized List<T> find(final String field, final Object v) {
List<T> list = new ArrayList<>(entityList);
CollectionUtils.filter(list, new Predicate() {
@Override
public boolean evaluate(Object object) {
try {
return ObjectUtils.equals(v, PropertyUtils.getProperty(object, field));
} catch (IllegalAccessExceptionInvocationTargetException | NoSuchMethodException | e) {
throw new RuntimeException(e);
}
}
});
return ListConvertUtil.transform(list, new RowConvertor<T, T>() {
@Override
public T convert(int rowIndex, T obj) {
try {
return (T) obj.clone();
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
}
});
}
Example 90
Project: beast-mcmc-master File: JListBinding.java View source code |
public void put(IValidatable bean) {
try {
DefaultListModel model = new DefaultListModel();
List<?> list = (List<?>) PropertyUtils.getProperty(bean, _property);
if (list != null) {
for (Object o : list) {
model.addElement(o);
}
}
_list.setModel(model);
} catch (Exception e) {
throw new BindingException(e);
}
}
Example 91
Project: chipKIT32-MAX-master File: JTextAreaBinding.java View source code |
public void put(IValidatable bean) {
try {
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 92
Project: cloudify-master File: PersistentMachineDetails.java View source code |
/******
* Populates the fields of the current object from the given MachineDetails. Note that all copy operations are
* shallow. Unsafe properties will be replaced.
*
* @param md
* the machine detaions to copy.
*/
public void populateFromMachineDetails(final MachineDetails md) {
try {
PropertyUtils.copyProperties(this, md);
} catch (IllegalAccessException e) {
throw new IllegalStateException("Failed to create persistent machine details: " + e.getMessage(), e);
} catch (InvocationTargetException e) {
throw new IllegalStateException("Failed to create persistent machine details: " + e.getMessage(), e);
} catch (NoSuchMethodException e) {
throw new IllegalStateException("Failed to create persistent machine details: " + e.getMessage(), e);
}
if (this.getKeyFile() != null) {
this.setKeyFileName(this.getKeyFile().getAbsolutePath());
this.setKeyFile(null);
}
}
Example 93
Project: cogtool-master File: JTextAreaBinding.java View source code |
public void put(IValidatable bean) {
try {
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 94
Project: ConcesionariaDB-master File: JRAbstractBeanDataSource.java View source code |
protected static Object getBeanProperty(Object bean, String propertyName) throws JRException {
Object value = null;
if (isCurrentBeanMapping(propertyName)) {
value = bean;
} else if (bean != null) {
try {
value = PropertyUtils.getProperty(bean, propertyName);
} catch (java.lang.IllegalAccessException e) {
throw new JRException("Error retrieving field value from bean : " + propertyName, e);
} catch (java.lang.reflect.InvocationTargetException e) {
throw new JRException("Error retrieving field value from bean : " + propertyName, e);
} catch (java.lang.NoSuchMethodException e) {
throw new JRException("Error retrieving field value from bean : " + propertyName, e);
} catch (IllegalArgumentException e) {
if (!e.getMessage().startsWith("Null property value for ")) {
throw e;
}
}
}
return value;
}
Example 95
Project: Consent2Share-master File: FieldValidatorLoginTroubleSelection.java View source code |
/*
* (non-Javadoc)
*
* @see org.springframework.validation.Validator#validate(java.lang.Object,
* org.springframework.validation.Errors)
*/
@Override
public void validate(Object target, Errors errors) {
String targetDtoName = target.getClass().getName().substring(target.getClass().getName().lastIndexOf('.') + 1, target.getClass().getName().length());
targetDtoName = Character.toLowerCase(targetDtoName.charAt(0)) + targetDtoName.substring(1);
try {
if (target instanceof LoginTroubleDto) {
// Login Trouble Type Id
Integer troubleTypeId = (Integer) PropertyUtils.getProperty(target, "troubleTypeId");
if (troubleTypeId.intValue() == 0) {
errors.rejectValue("troubleTypeId", "NotEmpty." + targetDtoName + ".troubleTypeId");
}
}
} catch (IllegalAccessException e1) {
e1.printStackTrace();
} catch (InvocationTargetException e1) {
e1.printStackTrace();
} catch (NoSuchMethodException e1) {
e1.printStackTrace();
}
}
Example 96
Project: constretto-core-master File: ObjectConfigurationStore.java View source code |
private TaggedPropertySet createPropertySetForObject(Object configurationObject) { String tag = ConfigurationValue.DEFAULT_TAG; String basePath = ""; Map<String, String> properties = new HashMap<String, String>(); if (configurationObject.getClass().isAnnotationPresent(ConfigurationSource.class)) { ConfigurationSource configurationAnnotation = configurationObject.getClass().getAnnotation(ConfigurationSource.class); tag = configurationAnnotation.tag(); if (tag.equals("")) { tag = ConfigurationValue.DEFAULT_TAG; } basePath = configurationAnnotation.basePath(); } for (PropertyDescriptor propertyDescriptor : PropertyUtils.getPropertyDescriptors(configurationObject)) { boolean canRead = propertyDescriptor.getReadMethod() != null; boolean isString = propertyDescriptor.getPropertyType().isAssignableFrom(String.class); if (canRead && isString) { String path = propertyDescriptor.getName(); try { String value = (String) PropertyUtils.getProperty(configurationObject, path); if (!ConstrettoUtils.isEmpty(basePath)) { path = basePath + "." + path; } properties.put(path, value); } catch (Exception e) { throw new ConstrettoException("Could not access data in field", e); } } } return new TaggedPropertySet(tag, properties, getClass()); }
Example 97
Project: datavalve-master File: ReflectionParameterResolver.java View source code |
public Object resolveProperty(Object base, String property) {
try {
return org.apache.commons.beanutils.PropertyUtils.getProperty(base, property);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
return null;
}
Example 98
Project: desktopgradeapp-master File: JTextAreaBinding.java View source code |
public void put(IValidatable bean) {
try {
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 99
Project: droidtowers-master File: JTextAreaBinding.java View source code |
public void put(IValidatable bean) {
try {
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 100
Project: egonet-master File: JTextAreaBinding.java View source code |
public void put(IValidatable bean) {
try {
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 101
Project: egoweb-master File: JComboBoxBinding.java View source code |
public void put(IValidatable bean) {
try {
Integer i = (Integer) PropertyUtils.getProperty(bean, _property);
if (i == null) {
throw new BindingException(Messages.getString("JComboBoxBinding.property.null"));
}
select(i.intValue());
} catch (Exception e) {
throw new BindingException(e);
}
}