List of usage examples for java.beans PropertyDescriptor getPropertyType
public synchronized Class<?> getPropertyType()
From source file:com.hiperf.common.ui.server.storage.impl.PersistenceHelper.java
@Override public String checkExists(String className, String attribute, String value, Locale locale) throws PersistenceException { EntityManager em = null;//from www . j av a 2 s . co m try { em = getEntityManager(); boolean isString; if (value != null) { PropertyDescriptor[] pds = (PropertyDescriptor[]) propertyDescriptorsByClassName.get(className); boolean isNumber = false; isString = false; for (PropertyDescriptor pd : pds) { if (pd.getName().equals(attribute)) { Class propertyType = pd.getPropertyType(); if ((propertyType.isPrimitive()) || (Number.class.isAssignableFrom(propertyType))) { isNumber = true; break; } if (!(String.class.isAssignableFrom(propertyType))) break; isString = true; break; } } StringBuilder q = getCheckExistsQuery(className, attribute, value, isNumber, isString); Query q1 = em.createQuery(q.toString()); if (isString) q1.setParameter(1, value.toLowerCase()); List l = q1.getResultList(); ResourceBundle ressource; if ((l != null) && (l.size() > 0)) { return getUniqueErrorMsg(attribute, value, locale); } return null; } List l = em.createQuery("select 1 from " + className + " o where o." + attribute + " is null") .getResultList(); ResourceBundle ressource; if ((l != null) && (l.size() > 0)) { return getUniqueErrorMsg(attribute, value, locale); } return null; } catch (Exception e) { logger.log(Level.SEVERE, "Exception in checkExists " + e.getMessage(), e); throw new PersistenceException("Exception in checkExists " + e.getMessage(), e); } finally { closeEntityManager(em); } }
From source file:com.hiperf.common.ui.server.storage.impl.PersistenceHelper.java
@Override public String checkExists(String className, com.hiperf.common.ui.shared.util.Id id, String attribute, String value, Locale locale) throws PersistenceException { EntityManager em = null;/*from www . ja va2 s . c o m*/ try { Set<PropertyDescriptor> ids = idsByClassName.get(className); PropertyDescriptor[] idsArr = (PropertyDescriptor[]) ids.toArray(new PropertyDescriptor[0]); em = getEntityManager(); int i; if (value != null) { boolean isNumber = false; boolean isString = false; PropertyDescriptor[] pds = (PropertyDescriptor[]) propertyDescriptorsByClassName.get(className); Class<?> propertyType; for (PropertyDescriptor pd : pds) { if (pd.getName().equals(attribute)) { propertyType = pd.getPropertyType(); if ((propertyType.isPrimitive()) || (Number.class.isAssignableFrom(propertyType))) { isNumber = true; break; } if (!(String.class.isAssignableFrom(propertyType))) break; isString = true; break; } } StringBuilder q = getCheckExistsQuery(className, attribute, value, isNumber, isString); q.append(" and o."); i = 0; for (String att : id.getFieldNames()) { q.append(att); q.append(" != "); if (StorageService.isNumber(att, idsArr)) { q.append(id.getFieldValues().get(i)); } else { q.append(" '").append(StringUtils.replace(id.getFieldValues().get(i).toString(), "'", "''")) .append("'"); } ++i; if (i < id.getFieldNames().size()) q.append(" and o."); } Query q1 = em.createQuery(q.toString()); if (isString) q1.setParameter(1, value.toLowerCase()); List l = q1.getResultList(); if ((l != null) && (l.size() > 0)) { return getUniqueErrorMsg(attribute, value, locale); } return null; } StringBuilder q = new StringBuilder( "select 1 from " + className + " o where o." + attribute + " is null and o."); i = 0; for (String att : id.getFieldNames()) { q.append(att); q.append(" != "); if (StorageService.isNumber(att, idsArr)) { q.append(id.getFieldValues().get(i)); } else { q.append(" '"); q.append(StringUtils.replace(id.getFieldValues().get(i).toString(), "'", "''")); q.append("'"); } ++i; if (i < id.getFieldNames().size()) q.append(" and o."); } List l = em.createQuery(q.toString()).getResultList(); if ((l != null) && (l.size() > 0)) { return getUniqueErrorMsg(attribute, value, locale); } return null; } catch (Exception e) { logger.log(Level.SEVERE, "Exception in checkExists " + e.getMessage(), e); throw new PersistenceException("Exception in checkExists " + e.getMessage(), e); } finally { closeEntityManager(em); } }
From source file:com.hiperf.common.ui.server.storage.impl.PersistenceHelper.java
@Override public Map<String, String> getAll(String rootClassName, String filter, String attPrefix, String childClassName, String childAttribute) throws PersistenceException { EntityManager em = null;/*from ww w . jav a 2 s . c om*/ if (attPrefix != null && !attPrefix.isEmpty()) { String[] s = attPrefix.split("\\."); if (s == null || s.length == 0) s = new String[] { attPrefix }; StringBuilder join = new StringBuilder(); StringBuilder select = new StringBuilder(); String lastClass = rootClassName; String lastJoinPrefix = "o."; int i = 0; for (int j = 0; j < s.length; j++) { String ss = s[j]; PropertyDescriptor[] pds = propertyDescriptorsByClassName.get(lastClass); for (PropertyDescriptor pd : pds) { if (pd.getName().equals(ss)) { Class<?> pt = pd.getPropertyType(); if (Collection.class.isAssignableFrom(pt) || INakedObject.class.isAssignableFrom(pt)) { join.append(" inner join ").append(lastJoinPrefix); if (!lastJoinPrefix.endsWith(".")) { join.append("."); } join.append(ss).append(" y").append(i).append(" "); lastJoinPrefix = "y" + i + "."; i++; if (Collection.class.isAssignableFrom(pt)) { Class<?> clazz; try { clazz = Class.forName(lastClass); ParameterizedType genericType = (ParameterizedType) clazz.getDeclaredField(ss) .getGenericType(); if (genericType != null) { for (Type t : genericType.getActualTypeArguments()) { if (t instanceof Class && INakedObject.class.isAssignableFrom((Class) t)) { lastClass = ((Class) t).getName(); break; } } } } catch (Exception e) { logger.log(Level.SEVERE, "Error", e); } } else { lastClass = pt.getName(); } } else if (childClassName.equals(pt.getName())) { lastJoinPrefix += ss + "."; if (i == s.length - 1) { select.append("select ").append(lastJoinPrefix).append(childAttribute) .append(" from ").append(rootClassName).append(" o "); } lastClass = pt.getName(); } else { lastJoinPrefix += ss + "."; lastClass = pt.getName(); } break; } } } HashMap<String, String> joinMap = null; if (join.length() > 0) { if (filter != null && !filter.isEmpty()) { int idx = filter.indexOf("inner join "); if (idx >= 0) { joinMap = new HashMap<>(); String[] ff = filter.substring(idx + 11, filter.indexOf("where")).trim() .split("inner join "); for (String fj : ff) { fj = fj.trim(); String[] fjj = fj.split(" "); if (fjj.length == 2) { joinMap.put(fjj[0].trim(), fjj[1].trim()); } } } } } if (joinMap != null && !joinMap.isEmpty() && join.length() > 0) { String jj = join.toString(); for (Entry<String, String> e : joinMap.entrySet()) { String tmp = "inner join " + e.getKey(); int k = jj.indexOf(tmp); if (k >= 0) { String ss = join.substring(k + tmp.length()).trim(); int m = ss.indexOf(" "); if (m > 0) { ss = ss.substring(0, m); } jj = jj.replace(ss, e.getValue()); /*lastJoinPrefix = lastJoinPrefix.replaceAll(ss, e.getValue()); join.replace(k, k + tmp.length() + 1 + ss.length(), "");*/ } } } if (select.length() == 0) { select.append("select ").append(lastJoinPrefix).append(childAttribute).append(" from ") .append(rootClassName).append(" o "); } if (join.length() > 0) { select.append(join); } if (filter != null && !filter.isEmpty()) { if (!filter.toLowerCase().contains("where")) select.append(" where "); select.append(filter); } select.append(" order by ").append(lastJoinPrefix).append(childAttribute).append(" asc"); String jpql = select.toString(); List<Date> dtParams = new ArrayList<Date>(); try { em = getEntityManager(); jpql = replaceDateParameters(jpql, dtParams); Query q = em.createQuery(jpql); List<Object> list = getResults(dtParams, q); if (list != null && !list.isEmpty()) { Map<String, String> map = new LinkedHashMap<String, String>(); for (Object o : list) { StorageHelper.fillGetAllMap(map, o); } return map; } else return null; } catch (Exception e) { logger.log(Level.SEVERE, "Exception in getAll " + e.getMessage(), e); throw new PersistenceException("Exception in getAll " + e.getMessage(), e); } finally { closeEntityManager(em); } } else { try { em = getEntityManager(); String jql = "select distinct o."; jql += childAttribute + " from " + rootClassName + " o "; if (filter != null && !filter.isEmpty()) { jql += filter; } jql += " order by o." + childAttribute + " asc"; List<Date> dtParams = new ArrayList<Date>(); jql = replaceDateParameters(jql, dtParams); Query q = em.createQuery(jql); List<Object> list = getResults(dtParams, q); if (list != null && !list.isEmpty()) { Map<String, String> map = new LinkedHashMap<String, String>(); for (Object o : list) { StorageHelper.fillGetAllMap(map, o); } return map; } else return null; } catch (Exception e) { logger.log(Level.SEVERE, "Exception in getAll " + e.getMessage(), e); throw new PersistenceException("Exception in getAll " + e.getMessage(), e); } finally { closeEntityManager(em); } } }
From source file:com.hiperf.common.ui.server.storage.impl.PersistenceHelper.java
private boolean doPersist(ObjectsToPersist toPersist, String userName, Map<com.hiperf.common.ui.shared.util.Id, INakedObject> res, Map<Object, IdHolder> newIdByOldId, EntityManager em, boolean validateBefore, Locale locale, boolean processExceptions) throws ClassNotFoundException, IntrospectionException, PersistenceException, IllegalAccessException, InvocationTargetException, InstantiationException { try {//from w w w .j a va2 s.c om Validator validator = validatorFactory.getValidator(); List<INakedObject> toInsert = toPersist.getInsertedObjects(); if (toInsert != null) { int max = 100 * toInsert.size(); int idx = -1; int k = -1; int s = toInsert.size(); int prevSize = s; while (!toInsert.isEmpty()) { if (s == toInsert.size()) { k++; } else k = 0; if (k == 1) { logger.log(Level.FINE, "Impossible to persist data : one linked object not found in toInsert list"); return false; } if (prevSize == toInsert.size()) { idx++; } else { idx = 0; prevSize = toInsert.size(); } if (idx > max) { logger.log(Level.FINE, "Impossible to persist data : one linked object not found in toInsert list..."); return false; } Iterator<INakedObject> it = toInsert.iterator(); while (it.hasNext()) { INakedObject o = (INakedObject) it.next(); String className = o.getClass().getName(); if (o instanceof IAuditable) { IAuditable aud = (IAuditable) o; aud.setCreateUser(userName); aud.setCreateDate(new Date()); } Set<PropertyDescriptor> ids = idsByClassName.get(className); processLinkedCollectionsBeforePersist(o, collectionsByClassName.get(className)); if (!processLinkedObjectsBeforePersist(newIdByOldId, o, lazysByClassName.get(className), toPersist)) continue; if (!processLinkedObjectsBeforePersist(newIdByOldId, o, eagerObjectsByClassName.get(className), toPersist)) continue; if (generatedIdClasses.contains(className)) { PropertyDescriptor idPd = ids.iterator().next(); Object oldId = idPd.getReadMethod().invoke(o, StorageService.emptyArg); Object[] args = new Object[1]; if (!idPd.getPropertyType().isPrimitive()) args[0] = null; else args[0] = 0L; idPd.getWriteMethod().invoke(o, args); if (validateBefore) { Set<ConstraintViolation<INakedObject>> errors = validator.validate(o); if (errors != null && !errors.isEmpty()) { it.remove(); continue; } try { em.persist(o); } catch (Exception e) { it.remove(); continue; } } else em.persist(o); Object newId = idPd.getReadMethod().invoke(o, StorageService.emptyArg); newIdByOldId.put(oldId, new IdHolder(newId, className)); List<Object> idVals = new ArrayList<Object>(1); idVals.add(oldId); List<String> idFields = new ArrayList<String>(1); idFields.add(idPd.getName()); res.put(new com.hiperf.common.ui.shared.util.Id(idFields, idVals), o); it.remove(); } else { com.hiperf.common.ui.shared.util.Id id = getId(o, ids); int i = 0; boolean toProcess = true; for (Object idVal : id.getFieldValues()) { if ((idVal instanceof Long && ((Long) idVal).longValue() < 0) || (idVal instanceof String && ((String) idVal).startsWith(PersistenceManager.SEQ_PREFIX))) { IdHolder newIds = newIdByOldId.get(idVal); if (newIds != null) { String att = id.getFieldNames().get(i); for (PropertyDescriptor idPd : ids) { if (idPd.getName().equals(att)) { Object[] args = new Object[1]; args[0] = newIds.getId(); idPd.getWriteMethod().invoke(o, args); break; } } } else { toProcess = false; break; } } i++; } if (toProcess) { if (validateBefore) { Set<ConstraintViolation<INakedObject>> errors = validator.validate(o); if (errors != null && !errors.isEmpty()) { it.remove(); continue; } try { refreshManyToOneLinkedWithId(o, id, em); em.persist(o); } catch (Exception e) { it.remove(); continue; } } else { refreshManyToOneLinkedWithId(o, id, em); em.persist(o); } id = getId(o, ids); res.put(id, o); it.remove(); } } } } } Map<String, Set<com.hiperf.common.ui.shared.util.Id>> toDelete = toPersist .getRemovedObjectsIdsByClassName(); if (toDelete != null) { for (String className : toDelete.keySet()) { Set<com.hiperf.common.ui.shared.util.Id> ids = toDelete.get(className); Class<?> clazz = Class.forName(className); Map<Field, Field> toRemove = null; if (ids != null && !ids.isEmpty()) { com.hiperf.common.ui.shared.util.Id id = ids.iterator().next(); if (id.getFieldValues().size() > 1) { toRemove = new HashMap<Field, Field>(); Field[] fields = clazz.getDeclaredFields(); for (Field f : fields) { if (f.isAnnotationPresent(ManyToOne.class)) { Field[] ff = f.getType().getDeclaredFields(); for (Field lf : ff) { OneToMany ann = lf.getAnnotation(OneToMany.class); if (ann != null && ann.targetEntity() != null && ann.targetEntity().equals(clazz)) { toRemove.put(f, lf); } } } } // TODO : manage annotations on the getters... } } for (com.hiperf.common.ui.shared.util.Id id : ids) { INakedObject no = getObject(clazz, id, em); if (no != null) { if (toRemove != null && !toRemove.isEmpty()) { for (Entry<Field, Field> e : toRemove.entrySet()) { Field f = e.getKey(); Field ff = e.getValue(); boolean b1 = false; boolean b2 = false; if (!f.isAccessible()) { f.setAccessible(true); b1 = true; } if (!ff.isAccessible()) { ff.setAccessible(true); b2 = true; } ((Collection) ff.get(f.get(no))).remove(no); if (b1) f.setAccessible(false); if (b2) ff.setAccessible(false); } } else { // TODO : manage annotations on the getters... } em.remove(no); } } } } Map<String, Map<com.hiperf.common.ui.shared.util.Id, Map<String, Serializable>>> toUpdate = toPersist .getUpdatedObjects(); if (toUpdate != null) { for (String className : toUpdate.keySet()) { Map<com.hiperf.common.ui.shared.util.Id, Map<String, Serializable>> map = toUpdate .get(className); Class<?> clazz = Class.forName(className); Iterator<Entry<com.hiperf.common.ui.shared.util.Id, Map<String, Serializable>>> iterator = map .entrySet().iterator(); while (iterator.hasNext()) { Entry<com.hiperf.common.ui.shared.util.Id, Map<String, Serializable>> entry = iterator .next(); com.hiperf.common.ui.shared.util.Id id = entry.getKey(); INakedObject original = getObject(clazz, id, em); Map<String, Serializable> updateMap = entry.getValue(); for (String att : updateMap.keySet()) { Object object = updateMap.get(att); if (object != null && object instanceof NakedObjectHandler) { NakedObjectHandler oo = (NakedObjectHandler) object; com.hiperf.common.ui.shared.util.Id objId = oo.getId(); if (generatedIdClasses.contains(oo.getClassName()) && newIdByOldId.containsKey(objId.getFieldValues().get(0))) { IdHolder newIds = newIdByOldId.get(objId.getFieldValues().get(0)); List<Object> idVals = new ArrayList<Object>(1); idVals.add(newIds.getId()); List<String> idFields = new ArrayList<String>(1); idFields.add(idsByClassName.get(oo.getClassName()).iterator().next().getName()); com.hiperf.common.ui.shared.util.Id newObjId = new com.hiperf.common.ui.shared.util.Id( idFields, idVals); object = getObject(Class.forName(oo.getClassName()), newObjId, em); } else { object = getObject(Class.forName(oo.getClassName()), oo.getId(), em); } } updateAttributeValue(className, original, att, object); } if (original instanceof IAuditable) { IAuditable aud = (IAuditable) original; aud.setModifyUser(userName); aud.setModifyDate(new Date()); } INakedObject o = null; if (validateBefore) { Set<ConstraintViolation<INakedObject>> errors = validator.validate(original); if (errors != null && !errors.isEmpty()) { iterator.remove(); continue; } try { o = em.merge(original); em.flush(); } catch (Exception e) { iterator.remove(); continue; } } else o = em.merge(original); res.put(id, o); } } } processAddedManyToMany(toPersist, res, newIdByOldId, em); processRemovedManyToMany(toPersist, res, newIdByOldId, em); em.flush(); return true; } catch (Exception e) { logger.log(Level.WARNING, "Exception", e); if (processExceptions) { processDbExceptions(locale, e); return false; } else throw new PersistenceException(e); } }
From source file:com.hiperf.common.ui.server.storage.impl.PersistenceHelper.java
private void processAddedManyToMany(ObjectsToPersist toPersist, Map<com.hiperf.common.ui.shared.util.Id, INakedObject> res, Map<Object, IdHolder> newIdByOldId, EntityManager em) throws ClassNotFoundException, IntrospectionException, PersistenceException, IllegalAccessException, InvocationTargetException, NoSuchFieldException { Map<String, Map<com.hiperf.common.ui.shared.util.Id, Map<String, List<com.hiperf.common.ui.shared.util.Id>>>> manyToManyAdded = toPersist .getManyToManyAddedByClassName(); if (manyToManyAdded != null && !manyToManyAdded.isEmpty()) { for (Entry<String, Map<com.hiperf.common.ui.shared.util.Id, Map<String, List<com.hiperf.common.ui.shared.util.Id>>>> e : manyToManyAdded .entrySet()) {/*from w w w . j av a 2 s . co m*/ String className = e.getKey(); Map<com.hiperf.common.ui.shared.util.Id, Map<String, List<com.hiperf.common.ui.shared.util.Id>>> map = e .getValue(); if (map != null && !map.isEmpty()) { Class<?> clazz = Class.forName(className); for (Entry<com.hiperf.common.ui.shared.util.Id, Map<String, List<com.hiperf.common.ui.shared.util.Id>>> entry : map .entrySet()) { com.hiperf.common.ui.shared.util.Id id = entry.getKey(); Map<String, List<com.hiperf.common.ui.shared.util.Id>> m = entry.getValue(); if (m != null && !m.isEmpty()) { Object objId = id.getFieldValues().get(0); if (newIdByOldId.containsKey(objId)) objId = newIdByOldId.get(objId).getId(); Object o = em.find(clazz, objId); if (o != null) { PropertyDescriptor[] pds = propertyDescriptorsByClassName.get(className); for (Entry<String, List<com.hiperf.common.ui.shared.util.Id>> ee : m.entrySet()) { String attr = ee.getKey(); List<com.hiperf.common.ui.shared.util.Id> ll = ee.getValue(); if (ll != null && !ll.isEmpty()) { Collection coll = null; Class classInColl = null; PropertyDescriptor myPd = null; String mappedBy = null; for (PropertyDescriptor pd : pds) { if (pd.getName().equals(attr)) { myPd = pd; coll = (Collection) pd.getReadMethod().invoke(o, StorageService.emptyArg); if (coll == null) { if (List.class.isAssignableFrom(pd.getPropertyType())) coll = new ArrayList(); else coll = new HashSet(); pd.getWriteMethod().invoke(o, coll); } ManyToMany ann = pd.getReadMethod().getAnnotation(ManyToMany.class); if (ann == null) { ann = clazz.getDeclaredField(pd.getName()) .getAnnotation(ManyToMany.class); } if (ann != null) { mappedBy = ann.mappedBy(); } break; } } if (coll != null) { ParameterizedType genericType = (ParameterizedType) clazz .getDeclaredField(myPd.getName()).getGenericType(); if (genericType != null) { for (Type t : genericType.getActualTypeArguments()) { if (t instanceof Class && INakedObject.class.isAssignableFrom((Class) t)) { classInColl = (Class) t; break; } } } for (com.hiperf.common.ui.shared.util.Id i : ll) { Object idObj = i.getFieldValues().get(0); if (newIdByOldId.containsKey(idObj)) idObj = newIdByOldId.get(idObj).getId(); Object linkedObj = em.find(classInColl, idObj); if (mappedBy == null || mappedBy.length() == 0) coll.add(linkedObj); else { PropertyDescriptor[] pds2 = propertyDescriptorsByClassName .get(classInColl.getName()); if (pds2 == null) { pds2 = propertyDescriptorsByClassName .get(classInColl.getName()); } for (PropertyDescriptor pd : collectionsByClassName .get(classInColl.getName())) { if (pd.getName().equals(mappedBy)) { Collection coll2 = (Collection) pd.getReadMethod() .invoke(linkedObj, StorageService.emptyArg); if (coll2 == null) { if (List.class .isAssignableFrom(pd.getPropertyType())) coll2 = new ArrayList(); else coll2 = new HashSet(); pd.getWriteMethod().invoke(linkedObj, coll2); } coll2.add(o); } } em.merge(linkedObj); } if (linkedObj instanceof INakedObject) res.put(i, (INakedObject) linkedObj); } } } } res.put(id, (INakedObject) em.merge(o)); } } } } } } }
From source file:edu.ku.brc.af.ui.forms.FormViewObj.java
@Override public void getDataFromUI() { if (isEditing) { // This should only happen when the user created a new object // in a form in a dialog and then they pressed Cancel without it being saved. /*if (isNewlyCreatedDataObj) {/*from w w w . jav a2 s . c om*/ if (parentDataObj instanceof FormDataObjIFace) { ((FormDataObjIFace)parentDataObj).addReference((FormDataObjIFace)dataObj, cellName); } else { FormHelper.addToParent(parentDataObj, dataObj); } isNewlyCreatedDataObj = false; }*/ if (formValidator != null && formValidator.getState() != UIValidatable.ErrorType.Valid) { if (isNewlyCreatedDataObj) { if (list != null) { list.remove(dataObj); } if (origDataSet != null) { origDataSet.remove(dataObj); } formValidator.setFormValidationState(UIValidatable.ErrorType.Valid); formValidator.reset(true); formValidator.validateRoot(); } return; } DataObjectSettable ds = formViewDef.getDataSettable(); DataObjectGettable dg = formViewDef.getDataGettable(); if (ds != null) { // Get Data From Selector if (selectorCBX != null) { String selectorName = altView.getSelectorName(); if (StringUtils.isNotEmpty(selectorName)) { try { PropertyDescriptor descr = PropertyUtils.getPropertyDescriptor(dataObj, selectorName); Object selectorValObj = UIHelper.convertDataFromString(altView.getSelectorValue(), descr.getPropertyType()); FormHelper.setFieldValue(selectorName, dataObj, selectorValObj, dg, ds); } catch (Exception ex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(FormViewObj.class, ex); log.error(ex); // XXX TODO Show error dialog here } } } for (FVOFieldInfo fieldInfo : controlsById.values()) { //String nm = fieldInfo.getFormCell().getName(); //System.out.println(nm); FormCellIFace fc = fieldInfo.getFormCell(); boolean isInoreGetSet = fc.isIgnoreSetGet(); boolean isReadOnly; boolean useThisData; // meaning the control is using the same data object as what is in the form // so we don't need to go get the data (skip it) if (fc instanceof FormCellField) { FormCellFieldIFace fcf = (FormCellFieldIFace) fc; isReadOnly = fcf.isReadOnly();// || fcf.isEditOnCreate(); useThisData = fcf.useThisData(); } else { useThisData = false; isReadOnly = false; } String id = fieldInfo.getFormCell().getIdent(); boolean hasFormControlChanged = hasFormControlChanged(id); //log.debug(fieldInfo.getName()+"\t"+fieldInfo.getFormCell().getName()+"\t hasChanged: "+(!isReadOnly && hasFormControlChanged)); if (!isReadOnly && !isInoreGetSet && (hasFormControlChanged || isAlwaysGetDataFromUI)) { // this ends up calling the getData on the GetSetValueIFace // which enables the control to set data into the data object if (useThisData) { getDataFromUIComp(id); continue; } boolean isSubView = fieldInfo.getFormCell() instanceof FormCellSubViewIFace; if (isSubView && fieldInfo.getComp() instanceof MultiView) { MultiView mv = (MultiView) fieldInfo.getComp(); mv.getDataFromUI(); } //log.debug(fieldInfo.getName()+" "+fieldInfo.getFormCell().getName() +" HAS CHANGED!"); Object uiData = getDataFromUIComp(id); // if ID is null then we have huge problems // if (uiData != null && dataObj != null) Changed for Bug 4994 if (dataObj != null) { if (isSubView) { log.debug(fieldInfo.getFormCell().getName()); if (uiData != null) { FormHelper.setFieldValue(fieldInfo.getFormCell().getName(), dataObj, uiData, dg, ds); } } else { //log.info(fieldInfo.getFormCell().getName()+" "+(dataObj != null ? dataObj.getClass().getSimpleName() : "dataObj was null")); FormHelper.setFieldValue(fieldInfo.getFormCell().getName(), dataObj, uiData, dg, ds); } } } } } else { throw new RuntimeException( "Calling getDataFromUI when the DataObjectSettable is null for the form."); } } }
From source file:com.hiperf.common.ui.server.storage.impl.PersistenceHelper.java
private INakedObject deproxyNakedObject(boolean root, Set<PropertyDescriptor> collections, Set<PropertyDescriptor> lazys, Set<PropertyDescriptor> eagers, Set<LinkFileInfo> linkedFiles, INakedObject no, Set<PropertyDescriptor> idPds, Map<String, Map<Object, Object>> oldIdByNewId, EntityManager em, Map<String, Map<com.hiperf.common.ui.shared.util.Id, INakedObject>> deproxyContext) throws IllegalAccessException, InvocationTargetException, InstantiationException, IntrospectionException, ClassNotFoundException, PersistenceException { String name = getClassName(no); if (isProxy(no, name)) no = clone(no, name);/*from w ww. ja v a 2 s . c om*/ Map<com.hiperf.common.ui.shared.util.Id, INakedObject> map = deproxyContext.get(name); if (map == null) { map = new HashMap<com.hiperf.common.ui.shared.util.Id, INakedObject>(); deproxyContext.put(name, map); } com.hiperf.common.ui.shared.util.Id noId = getId(no, idsByClassName.get(name)); if (map.containsKey(noId)) return no; map.put(noId, no); if (root && linkedFiles != null && !linkedFiles.isEmpty()) { for (LinkFileInfo a : linkedFiles) { Object fileId = a.getLocalFileIdGetter().invoke(no, new Object[0]); if (fileId != null) a.getLocalFileNameSetter().invoke(no, getFileName(a.getFileClassName(), a.getFileNameField(), fileId, getEntityManager())); } } if (collections != null) { for (PropertyDescriptor pd : collections) { Method readMethod = pd.getReadMethod(); Method writeMethod = pd.getWriteMethod(); Object o = readMethod.invoke(no, new Object[0]); if (o != null) { if (root) { Collection orig = (Collection) o; boolean processed = false; Type type = readMethod.getGenericReturnType(); Class classInCollection = null; if (type instanceof ParameterizedType) { classInCollection = (Class) ((ParameterizedType) type).getActualTypeArguments()[0]; } if (classInCollection != null) { if (Number.class.isAssignableFrom(classInCollection) || String.class.equals(classInCollection) || Boolean.class.equals(classInCollection)) { Collection targetColl; int size = orig.size(); if (List.class.isAssignableFrom(readMethod.getReturnType())) { targetColl = new ArrayList(size); } else { targetColl = new HashSet(size); } if (size > 0) targetColl.addAll(orig); writeMethod.invoke(no, targetColl); processed = true; } } if (!processed) { //deproxyCollection(no, readMethod, writeMethod, orig, oldIdByNewId, em, deproxyContext); com.hiperf.common.ui.shared.util.Id id = getId(no, idPds); CollectionInfo ci = null; if (!id.isLocal()) { String className = getClassName(no); String attName = pd.getName(); ci = getCollectionInfo(em, id, className, attName); } if (List.class.isAssignableFrom(readMethod.getReturnType())) { if (ci != null) writeMethod.invoke(no, new LazyList<INakedObject>(ci.getSize(), ci.getDescription())); else writeMethod.invoke(no, new LazyList<INakedObject>()); } else { if (ci != null) writeMethod.invoke(no, new LazySet<INakedObject>(ci.getSize(), ci.getDescription())); else writeMethod.invoke(no, new LazySet<INakedObject>()); } } } else { if (List.class.isAssignableFrom(readMethod.getReturnType())) { writeMethod.invoke(no, new LazyList<INakedObject>()); } else { writeMethod.invoke(no, new LazySet<INakedObject>()); } } } } } if (lazys != null) { for (PropertyDescriptor pd : lazys) { Method readMethod = pd.getReadMethod(); Object o = readMethod.invoke(no, new Object[0]); if (o != null) { Class<?> targetClass = pd.getPropertyType(); if (root) { String targetClassName = targetClass.getName(); if (isProxy(o, targetClassName)) { o = deproxyObject(targetClass, o); } Set<PropertyDescriptor> ids = idsByClassName.get(targetClassName); o = deproxyNakedObject(root, collectionsByClassName.get(targetClassName), lazysByClassName.get(targetClassName), eagerObjectsByClassName.get(targetClassName), linkedFilesByClassName.get(targetClassName), (INakedObject) o, ids, oldIdByNewId, em, deproxyContext); pd.getWriteMethod().invoke(no, o); } else { Object lazyObj = newLazyObject(targetClass); pd.getWriteMethod().invoke(no, lazyObj); } } } } if (eagers != null) { for (PropertyDescriptor pd : eagers) { String targetClassName = pd.getPropertyType().getName(); Method readMethod = pd.getReadMethod(); Object o = readMethod.invoke(no, new Object[0]); if (o != null) { Set<PropertyDescriptor> ids = idsByClassName.get(targetClassName); deproxyNakedObject(root, collectionsByClassName.get(targetClassName), lazysByClassName.get(targetClassName), eagerObjectsByClassName.get(targetClassName), linkedFilesByClassName.get(targetClassName), (INakedObject) o, ids, oldIdByNewId, em, deproxyContext); } } } if (oldIdByNewId != null && idPds != null) { Map<Object, Object> map2 = oldIdByNewId.get(no.getClass().getName()); if (map2 != null && !map2.isEmpty()) { for (PropertyDescriptor pd : idPds) { Object id = pd.getReadMethod().invoke(no, StorageService.emptyArg); Object oldId = map2.get(id); if (oldId != null) { pd.getWriteMethod().invoke(no, new Object[] { oldId }); } } } } try { em.remove(no); } catch (Exception e) { } return no; }
From source file:net.yasion.common.core.bean.wrapper.impl.ExtendedBeanWrapperImpl.java
@SuppressWarnings("unchecked") private void setPropertyValue(PropertyTokenHolder tokens, PropertyValue pv2) throws BeansException { net.yasion.common.core.bean.wrapper.PropertyValue pv = new net.yasion.common.core.bean.wrapper.PropertyValue( "", null); AfxBeanUtils.copySamePropertyValue(pv2, pv); String propertyName = tokens.canonicalName; String actualName = tokens.actualName; if (tokens.keys != null) { // Apply indexes and map keys: fetch value for all keys but the last one. PropertyTokenHolder getterTokens = new PropertyTokenHolder(); getterTokens.canonicalName = tokens.canonicalName; getterTokens.actualName = tokens.actualName; getterTokens.keys = new String[tokens.keys.length - 1]; System.arraycopy(tokens.keys, 0, getterTokens.keys, 0, tokens.keys.length - 1); Object propValue;//from w w w .j a v a 2 s .c o m try { propValue = getPropertyValue(getterTokens); } catch (NotReadablePropertyException ex) { throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName, "Cannot access indexed value in property referenced " + "in indexed property path '" + propertyName + "'", ex); } // Set value for last key. String key = tokens.keys[tokens.keys.length - 1]; if (propValue == null) { // null map value case if (isAutoGrowNestedPaths()) { // #TO#DO#: cleanup, this is pretty hacky int lastKeyIndex = tokens.canonicalName.lastIndexOf('['); getterTokens.canonicalName = tokens.canonicalName.substring(0, lastKeyIndex); propValue = setDefaultValue(getterTokens); } else { throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + propertyName, "Cannot access indexed value in property referenced " + "in indexed property path '" + propertyName + "': returned null"); } } if (propValue.getClass().isArray()) { PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName); Class<?> requiredType = propValue.getClass().getComponentType(); int arrayIndex = Integer.parseInt(key); Object oldValue = null; try { if (isExtractOldValueForEditor() && arrayIndex < Array.getLength(propValue)) { oldValue = Array.get(propValue, arrayIndex); } Object convertedValue = convertIfNecessary(propertyName, oldValue, pv.getValue(), requiredType, TypeDescriptor.nested(property(pd), tokens.keys.length)); Array.set(propValue, arrayIndex, convertedValue); } catch (IndexOutOfBoundsException ex) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Invalid array index in property path '" + propertyName + "'", ex); } } else if (propValue instanceof List) { PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName); Class<?> requiredType = GenericCollectionTypeResolver.getCollectionReturnType(pd.getReadMethod(), tokens.keys.length); List<Object> list = (List<Object>) propValue; int index = Integer.parseInt(key); Object oldValue = null; if (isExtractOldValueForEditor() && index < list.size()) { oldValue = list.get(index); } Object convertedValue = convertIfNecessary(propertyName, oldValue, pv.getValue(), requiredType, TypeDescriptor.nested(property(pd), tokens.keys.length)); int size = list.size(); if (index >= size && index < this.autoGrowCollectionLimit) { for (int i = size; i < index; i++) { try { list.add(null); } catch (NullPointerException ex) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Cannot set element with index " + index + " in List of size " + size + ", accessed using property path '" + propertyName + "': List does not support filling up gaps with null elements"); } } list.add(convertedValue); } else { try { list.set(index, convertedValue); } catch (IndexOutOfBoundsException ex) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Invalid list index in property path '" + propertyName + "'", ex); } } } else if (propValue instanceof Map) { PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName); Class<?> mapKeyType = GenericCollectionTypeResolver.getMapKeyReturnType(pd.getReadMethod(), tokens.keys.length); Class<?> mapValueType = GenericCollectionTypeResolver.getMapValueReturnType(pd.getReadMethod(), tokens.keys.length); Map<Object, Object> map = (Map<Object, Object>) propValue; // IMPORTANT: Do not pass full property name in here - property editors // must not kick in for map keys but rather only for map values. TypeDescriptor typeDescriptor = TypeDescriptor.valueOf(mapKeyType); Object convertedMapKey = convertIfNecessary(null, null, key, mapKeyType, typeDescriptor); Object oldValue = null; if (isExtractOldValueForEditor()) { oldValue = map.get(convertedMapKey); } // Pass full property name and old value in here, since we want full // conversion ability for map values. Object convertedMapValue = convertIfNecessary(propertyName, oldValue, pv.getValue(), mapValueType, TypeDescriptor.nested(property(pd), tokens.keys.length)); map.put(convertedMapKey, convertedMapValue); } else { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Property referenced in indexed property path '" + propertyName + "' is neither an array nor a List nor a Map; returned value was [" + pv.getValue() + "]"); } } else { PropertyDescriptor pd = pv.getResolvedDescriptor(); if (pd == null || !pd.getWriteMethod().getDeclaringClass().isInstance(this.object)) { pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName); if (pd == null || pd.getWriteMethod() == null) { if (pv.isOptional()) { logger.debug("Ignoring optional value for property '" + actualName + "' - property not found on bean class [" + getRootClass().getName() + "]"); return; } else { PropertyMatches matches = PropertyMatches.forProperty(propertyName, getRootClass()); throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName, matches.buildErrorMessage(), matches.getPossibleMatches()); } } pv.getOriginalPropertyValue().setResolvedDescriptor(pd); } Object oldValue = null; try { Object originalValue = pv.getValue(); Object valueToApply = originalValue; if (!Boolean.FALSE.equals(pv.getConversionNecessary())) { if (pv.isConverted()) { valueToApply = pv.getConvertedValue(); } else { if (isExtractOldValueForEditor() && pd.getReadMethod() != null) { final Method readMethod = pd.getReadMethod(); if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers()) && !readMethod.isAccessible()) { if (System.getSecurityManager() != null) { AccessController.doPrivileged(new PrivilegedAction<Object>() { @Override public Object run() { readMethod.setAccessible(true); return null; } }); } else { readMethod.setAccessible(true); } } try { if (System.getSecurityManager() != null) { oldValue = AccessController .doPrivileged(new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { return readMethod.invoke(object); } }, acc); } else { oldValue = readMethod.invoke(object); } } catch (Exception ex) { if (ex instanceof PrivilegedActionException) { ex = ((PrivilegedActionException) ex).getException(); } if (logger.isDebugEnabled()) { logger.debug("Could not read previous value of property '" + this.nestedPath + propertyName + "'", ex); } } } valueToApply = convertForProperty(propertyName, oldValue, originalValue, new TypeDescriptor(property(pd))); } pv.getOriginalPropertyValue().setConversionNecessary(valueToApply != originalValue); } final Method writeMethod = (pd instanceof GenericTypeAwarePropertyDescriptor ? ((GenericTypeAwarePropertyDescriptor) pd).getWriteMethodForActualAccess() : pd.getWriteMethod()); if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers()) && !writeMethod.isAccessible()) { if (System.getSecurityManager() != null) { AccessController.doPrivileged(new PrivilegedAction<Object>() { @Override public Object run() { writeMethod.setAccessible(true); return null; } }); } else { writeMethod.setAccessible(true); } } final Object value = valueToApply; if (System.getSecurityManager() != null) { try { AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { writeMethod.invoke(object, value); return null; } }, acc); } catch (PrivilegedActionException ex) { throw ex.getException(); } } else { writeMethod.invoke(this.object, value); } } catch (TypeMismatchException ex) { throw ex; } catch (InvocationTargetException ex) { PropertyChangeEvent propertyChangeEvent = new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName, oldValue, pv.getValue()); if (ex.getTargetException() instanceof ClassCastException) { throw new TypeMismatchException(propertyChangeEvent, pd.getPropertyType(), ex.getTargetException()); } else { throw new MethodInvocationException(propertyChangeEvent, ex.getTargetException()); } } catch (Exception ex) { PropertyChangeEvent pce = new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName, oldValue, pv.getValue()); throw new MethodInvocationException(pce, ex); } } }
From source file:pt.ist.maidSyncher.domain.SynchableObject.java
public void copyPropertiesTo(Object dest) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException, TaskNotVisibleException { Set<PropertyDescriptor> propertyDescriptorsThatChanged = new HashSet<PropertyDescriptor>(); Object orig = this; checkNotNull(dest);//from ww w . jav a 2 s. c o m PropertyDescriptor origDescriptors[] = PropertyUtils.getPropertyDescriptors(orig); for (PropertyDescriptor origDescriptor : origDescriptors) { String name = origDescriptor.getName(); if (PropertyUtils.isReadable(orig, name)) { PropertyDescriptor destDescriptor = PropertyUtils.getPropertyDescriptor(dest, origDescriptor.getName()); if (PropertyUtils.isWriteable(dest, name) || (destDescriptor != null && MiscUtils.getWriteMethodIncludingFlowStyle(destDescriptor, dest.getClass()) != null)) { Object valueDest = PropertyUtils.getSimpleProperty(dest, name); Object valueOrigin = PropertyUtils.getSimpleProperty(orig, name); LOGGER.debug("OrigDescriptor PropertyType: " + origDescriptor.getPropertyType().getName()); // System.out.println("OrigDescriptor PropertyType: " + origDescriptor.getPropertyType().getName()); //let's ignore the properties were the values are our domain packages if (valueOrigin != null && (SynchableObject.class.isAssignableFrom(valueOrigin.getClass()))) { // System.out.println("Skipping"); continue; //let's skip these properties } if (SynchableObject.class.isAssignableFrom(origDescriptor.getPropertyType())) { // System.out.println("Skipping"); continue; } if (origDescriptor instanceof IndexedPropertyDescriptor) { IndexedPropertyDescriptor indexedPropertyDescriptor = (IndexedPropertyDescriptor) origDescriptor; // System.out.println("OrigDescriptor IndexedPropertyDescriptor: " + indexedPropertyDescriptor.getName()); if (SynchableObject.class .isAssignableFrom(indexedPropertyDescriptor.getIndexedPropertyType())) { // System.out.println("Skipping"); continue; } } //let's ignore all of the dates - as they should be filled by //the system if (valueOrigin instanceof LocalTime) continue; if (Objects.equal(valueDest, valueOrigin) == false) propertyDescriptorsThatChanged.add(origDescriptor); try { if (PropertyUtils.isWriteable(dest, name) == false) { //let's use the flow version Class<?> origPropertyType = origDescriptor.getPropertyType(); Method writeMethodIncludingFlowStyle = MiscUtils .getWriteMethodIncludingFlowStyle(destDescriptor, dest.getClass()); if (Arrays.asList(writeMethodIncludingFlowStyle.getParameterTypes()) .contains(origPropertyType)) { writeMethodIncludingFlowStyle.invoke(dest, valueOrigin); } else { continue; } } else { PropertyUtils.setSimpleProperty(dest, name, valueOrigin); } } catch (IllegalArgumentException ex) { throw new Error("setSimpleProperty returned an exception, dest: " + dest.getClass().getName() + " name : " + name + " valueOrig: " + valueOrigin, ex); } LOGGER.trace("Copied property " + name + " from " + orig.getClass().getName() + " object to a " + dest.getClass().getName() + " oid: " + getExternalId()); } // System.out.println("--"); } } }