List of usage examples for java.lang.reflect Field isAccessible
@Deprecated(since = "9") public boolean isAccessible()
From source file:com.dotweblabs.twirl.gae.GaeMarshaller.java
/** * * Create entity objects that can be persisted into the GAE Datastore, * including its Parent-Child relationships (if necessary). * * @param parent parent of the generated entity or Entities * @param instance to marshall//from ww w. ja v a 2 s. c om * @return */ @Override public IdentityHashMap marshall(Key parent, Object instance) { if (instance == null) { throw new RuntimeException("Object cannot be null"); } Entity e = null; // Its possible that a Entity to be saved without id and just a parent key if (parent != null && hasNoIdField(instance)) { String kind = getKindOf(instance); e = new Entity(kind, parent); } else { Key key = createKeyFrom(parent, instance); // inspect kind and create key e = new Entity(key); } boolean indexed = !AnnotationUtil.isClassAnnotated(GaeObjectStore.unIndexed(), instance); Map<String, Object> props = new LinkedHashMap<String, Object>(); List<Entity> target = null; // Marshall java.util.Map if (instance instanceof Map) { Map map = (Map) instance; if (String.class.getName().equals(MapHelper.getKeyType(map))) { Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, Object> entry = it.next(); String entryKey = entry.getKey(); Object entryVal = entry.getValue(); if (!entryKey.equals(GaeObjectStore.KEY_RESERVED_PROPERTY) && !entryKey.equals(GaeObjectStore.KIND_RESERVED_PROPERTY) && !entryKey.equals(GaeObjectStore.NAMESPACE_RESERVED_PROPERTY)) { if (entryVal instanceof Map) { setProperty(e, entryKey, createEmbeddedEntityFromMap((Map) entryVal), indexed); } else if (entryVal instanceof List) { setProperty(e, entryKey, createEmbeddedEntityFromList((List) entryVal), indexed); } else { setProperty(e, entryKey, entryVal, indexed); } } } } else { throw new RuntimeException( String.class.getName() + " is the only supported " + Map.class.getName() + " key"); } } else { // Marshall all other object types Field[] fields = instance.getClass().getDeclaredFields(); GeoPt geoPt = null; for (Field field : fields) { if (target == null) { target = new LinkedList<Entity>(); } if ((field.getModifiers() & java.lang.reflect.Modifier.FINAL) == java.lang.reflect.Modifier.FINAL) { // do nothing for a final field // usually static UID fields continue; } String fieldName = field.getName(); if (field.isAnnotationPresent(GaeObjectStore.key())) { // skip continue; } else if (field.isAnnotationPresent(GaeObjectStore.objectId())) { // skip continue; } else if (field.isAnnotationPresent(GaeObjectStore.kind())) { // skip continue; } else if (field.isAnnotationPresent(Volatile.class)) { // skip continue; } try { boolean isAccessible = field.isAccessible(); field.setAccessible(true); Class<?> fieldType = field.getType(); Object fieldValue = field.get(instance); if (fieldValue == null) { e.setProperty(fieldName, null); } else if (fieldValue instanceof String) { setProperty(e, fieldName, fieldValue, indexed); } else if (fieldValue instanceof Number || fieldValue instanceof Long || fieldValue instanceof Integer || fieldValue instanceof Short) { setProperty(e, fieldName, fieldValue, indexed); } else if (fieldValue instanceof Boolean) { setProperty(e, fieldName, fieldValue, indexed); } else if (fieldValue instanceof Date) { setProperty(e, fieldName, fieldValue, indexed); } else if (fieldValue instanceof User) { // GAE support this type setProperty(e, fieldName, fieldValue, indexed); } else if (fieldValue instanceof Blob) { setProperty(e, fieldName, fieldValue, indexed); } else if (fieldValue instanceof List) { LOG.debug("Processing List valueType"); if (field.isAnnotationPresent(Embedded.class)) { setProperty(e, fieldName, createEmbeddedEntityFromList((List) fieldValue), indexed); } else { boolean supported = true; List list = (List) fieldValue; for (Object item : list) { if (!GAE_SUPPORTED_TYPES.contains(item.getClass())) { supported = false; } } if (supported) { setProperty(e, fieldName, fieldValue, indexed); } else { throw new RuntimeException("List should only include GAE supported types " + GAE_SUPPORTED_TYPES + " otherwise annotate the List with @Embedded"); } } } else if (fieldValue instanceof GeoPt) { setProperty(e, fieldName, fieldValue, indexed); } else if (fieldValue instanceof Enum) { String enumValue = fieldValue.toString(); LOG.info("Enum marshalled as \"" + enumValue + "\""); setProperty(e, fieldName, enumValue, indexed); } else if (fieldValue instanceof Map) { LOG.debug("Processing Map valueType"); if (field.isAnnotationPresent(Embedded.class)) { setProperty(e, fieldName, createEmbeddedEntityFromMap((Map) fieldValue), indexed); } else if (field.isAnnotationPresent(Flat.class)) { Map<String, Object> flat = (Map) fieldValue; Iterator<Map.Entry<String, Object>> it = flat.entrySet().iterator(); if (!it.hasNext()) { LOG.debug("Iterator is empty"); } while (it.hasNext()) { Object entry = it.next(); try { Map.Entry<Object, Object> mapEntry = (Map.Entry<Object, Object>) entry; Object entryKey = mapEntry.getKey(); Object entryVal = mapEntry.getValue(); if (entryVal == null) { setProperty(e, (String) entryKey, null, indexed); } else if (entryVal instanceof Map) { setProperty(e, (String) entryKey, createEmbeddedEntityFromMap((Map) entryVal), indexed); } else if (entryVal instanceof List) { throw new RuntimeException("List values are not yet supported"); } else if (entryVal instanceof String || entryVal instanceof Number || entryVal instanceof Boolean || entryVal instanceof Date || entryVal instanceof User || entryVal instanceof EmbeddedEntity) { setProperty(e, (String) entryKey, entryVal, indexed); } else { throw new RuntimeException( "Unsupported GAE property type: " + entryVal.getClass().getName()); } if (e == null) { throw new RuntimeException("Entity is null"); } } catch (ClassCastException ex) { // Something is wrong here ex.printStackTrace(); } catch (Exception ex) { ex.printStackTrace(); } } } else { throw new TwirlException("Map type should be annotated with @Embedded or @Flat"); } } else { // For primitives if (fieldType.equals(int.class)) { int i = (Integer) fieldValue; setProperty(e, fieldName, i, indexed); } else if (fieldType.equals(boolean.class)) { boolean i = (Boolean) fieldValue; setProperty(e, fieldName, i, indexed); } else if (fieldType.equals(byte.class)) { byte i = (Byte) fieldValue; setProperty(e, fieldName, i, indexed); } else if (fieldType.equals(short.class)) { short i = (Short) fieldValue; setProperty(e, fieldName, i, indexed); } else if (fieldType.equals(long.class)) { long i = (Long) fieldValue; setProperty(e, fieldName, i, indexed); } else if (fieldType.equals(float.class)) { float i = (Float) fieldValue; setProperty(e, fieldName, i, indexed); } else if (fieldType.equals(double.class)) { double i = (Double) fieldValue; setProperty(e, fieldName, i, indexed); } else if (fieldType.equals(byte.class)) { byte b = (byte) fieldValue; Blob blob = new Blob(new byte[b]); setProperty(e, fieldName, blob, indexed); } else if (fieldType.equals(byte[].class)) { byte[] bytes = (byte[]) fieldValue; Blob blob = new Blob(bytes); setProperty(e, fieldName, blob, indexed); } else if (fieldType.equals(Enum.class)) { throw new RuntimeException("Enum primitive type not yet implemented"); } else { // POJO if (field.isAnnotationPresent(Embedded.class)) { Map<String, Object> map = createMapFrom(fieldValue); EmbeddedEntity ee = createEmbeddedEntityFromMap(map); setProperty(e, fieldName, ee, indexed); } else if (field.isAnnotationPresent(GaeObjectStore.parent())) { // @Parent first before @Child, don't switch. @Child needs parent Key. if (field.getType().equals(Key.class)) { // skip it continue; } else { if (parent != null) { // Case where a Parent entity is marshalled then during the // iteration process, a @Child entity is found Entity _target = new Entity(createKeyFrom(parent, instance)); _target.setPropertiesFrom(e); e = _target; } else { // Case where a Child entity is first marshalled // at this point this child is not yet in the stack // and the Parent entity is not yet also in the stack // so we will create a Key from the "not yet marshalled" parent instance // or is it not? Let's check. Object parentField = field.get(instance); Entity parentEntity = stack.get(parentField); if (parentEntity != null) { Entity _target = new Entity( createKeyFrom(parentEntity.getKey(), instance)); _target.setPropertiesFrom(e); e = _target; } else { Key generatedParentKey = createKeyFrom(null, parentField); Entity _target = new Entity( createKeyFrom(generatedParentKey, instance)); _target.setPropertiesFrom(e); e = _target; marshall(null, parentField); } } } } else if (field.isAnnotationPresent(GaeObjectStore.child())) { Object childField = field.get(instance); marshall(e.getKey(), childField); Entity childEntity = stack.get(childField); Key childEntityKey = childEntity.getKey(); setProperty(e, fieldName, childEntityKey, indexed); } else if (field.isAnnotationPresent(GaeObjectStore.ancestor())) { // already processed above, skip it } else { throw new RuntimeException( "POJO's must be annotated with @Embedded, @Parent or @Child annotations for field " + fieldName); } } } field.setAccessible(isAccessible); } catch (IllegalAccessException ex) { ex.printStackTrace(); } } } stack.put(instance, e); return stack; }
From source file:org.j2free.admin.ReflectionMarshaller.java
/** * /*w ww . j a v a2 s . c om*/ * @param entity * @param parameterMap * @param controller * @return * @throws MarshallingException */ public Object marshallIn(Object entity, Map<String, String[]> parameterMap, Controller controller) throws MarshallingException { Field field; Converter converter; Method setter; String[] newValues; log.debug("Marshalling in instance of " + entity.getClass().getSimpleName()); boolean error = false, success = false, isEntity = false, isCollection = false; Class collectionType; Class fieldType; for (Map.Entry<Field, Converter> ent : instructions.entrySet()) { // reset flags error = success = isEntity = isCollection = false; field = ent.getKey(); converter = ent.getValue(); if (converter.isReadOnly()) { log.debug("Skipping read-only field " + field.getName()); continue; } newValues = parameterMap.get(field.getName()); if (newValues == null || newValues.length == 0) { log.debug("Skipping field " + field.getName() + ", no new value set."); continue; } isEntity = converter.isEntity(); isCollection = converter.isCollection(); fieldType = field.getType(); collectionType = isCollection ? converter.getType() : null; log.debug("Marshalling in field " + field.getName()); // try to get the original value try { if (!field.isAccessible()) { field.setAccessible(true); } if (field.isAccessible()) { log.debug(field.getName() + " is accessible"); if (!isEntity && !isCollection) { log.debug("!isEntity && !isCollection"); // if it's an array, it needs special treatment if (fieldType.isArray()) { log.debug(field.getName() + " is an Array"); Class arrayType = fieldType.getComponentType(); // If we can, just convert with a cast() if (arrayType.isAssignableFrom(String.class)) { log.debug(arrayType.getName() + " is assignable from String.class"); Object[] newArray = new Object[newValues.length]; for (int i = 0; i < newValues.length; i++) { newArray[i] = arrayType.cast(newValues[i]); } field.set(entity, newArray); } else { if (isInteger(fieldType)) { Integer[] newArray = new Integer[newValues.length]; for (int i = 0; i < newValues.length; i++) { newArray[i] = Integer.valueOf(newValues[i]); } field.set(entity, newArray); } else if (isFloat(fieldType)) { Float[] newArray = new Float[newValues.length]; for (int i = 0; i < newValues.length; i++) { newArray[i] = Float.valueOf(newValues[i]); } field.set(entity, newArray); } else if (isDouble(fieldType)) { Double[] newArray = new Double[newValues.length]; for (int i = 0; i < newValues.length; i++) { newArray[i] = Double.valueOf(newValues[i]); } field.set(entity, newArray); } else if (isShort(fieldType)) { Short[] newArray = new Short[newValues.length]; for (int i = 0; i < newValues.length; i++) { newArray[i] = Short.valueOf(newValues[i]); } field.set(entity, newArray); } else if (isChar(fieldType)) { field.set(entity, ServletUtils.join(newValues, "").toCharArray()); } else if (isLong(fieldType)) { Long[] newArray = new Long[newValues.length]; for (int i = 0; i < newValues.length; i++) { newArray[i] = Long.valueOf(newValues[i]); } field.set(entity, newArray); } else if (isBoolean(fieldType)) { Boolean[] newArray = new Boolean[newValues.length]; for (int i = 0; i < newValues.length; i++) { newArray[i] = Boolean.valueOf(newValues[i]); } field.set(entity, newArray); } else if (isByte(fieldType)) { Byte[] newArray = new Byte[newValues.length]; for (int i = 0; i < newValues.length; i++) { newArray[i] = Byte.valueOf(newValues[i]); } field.set(entity, newArray); } else { throw new MarshallingException( "Don't know how to marshall an array of a non-primitive, and non-assignable type! field = " + field.getName()); } } } else { // Check out if it's assignable via a straight cast, // that could save time if (fieldType.isAssignableFrom(String.class)) { log.debug(fieldType.getName() + " is assignable from String.class"); // this might throw an exception, but we're going // to ignore it because there are other ways of // setting the value if this doesn't work. try { field.set(entity, fieldType.cast(newValues[0])); log.debug("Assigned via cast"); } catch (Exception e) { log.debug("Error setting field by cast", e); } success = true; } // if it wasn't assignable via a straight cast, try // working around it. if (!success) { if (isInteger(fieldType) && !newValues[0].equals("")) { field.setInt(entity, Integer.valueOf(newValues[0])); } else if (isFloat(fieldType) && !newValues[0].equals("")) { field.setFloat(entity, Float.valueOf(newValues[0])); } else if (isDouble(fieldType) && !newValues[0].equals("")) { field.setDouble(entity, Double.valueOf(newValues[0])); } else if (isShort(fieldType) && !newValues[0].equals("")) { field.setShort(entity, Short.valueOf(newValues[0])); } else if (isChar(fieldType)) { field.setChar(entity, newValues[0].charAt(0)); } else if (isLong(fieldType) && !newValues[0].equals("")) { field.setLong(entity, Long.valueOf(newValues[0])); } else if (isBoolean(fieldType) && !newValues[0].equals("")) { field.setBoolean(entity, Boolean.valueOf(newValues[0])); } else if (isByte(fieldType) && !newValues[0].equals("")) { field.setByte(entity, Byte.valueOf(newValues[0])); } else if (isDate(fieldType)) { if (newValues[0].equals("")) { field.set(entity, null); } else { try { field.set(entity, asDate(newValues[0])); } catch (ParseException pe) { log.warn("Error parsing date: " + newValues[0], pe); } } } else if (!newValues[0].equals("")) { log.debug("Not sure how to set " + field.getName() + " of type " + fieldType.getName() + ", attemping cast."); field.set(entity, fieldType.cast(newValues[0])); } else if (newValues[0].equals("")) { log.debug("Skipping field " + field.getName() + ", empty string value passed in."); } } } } else if (isEntity && !isCollection) { log.debug("isEntity && !isCollection"); ReflectionMarshaller innerMarshaller = ReflectionMarshaller.getForClass(fieldType); field.set(entity, controller.proxy(fieldType, innerMarshaller.asIdType(newValues[0]))); } else if (!isEntity && isCollection) { log.debug("!isEntity && isCollection"); throw new MarshallingException("Error, collections of non-entities are not yet supported."); } else if (isEntity && isCollection) { log.debug("isEntity && isCollection"); // for now, this is going to expect the parameter to be a // comma-delimited string of entity ids String[] idsString = newValues[0].toString().split(","); Collection collection = (Collection) field.get(entity); log.debug("newValues.length = " + newValues.length); log.debug("newValues[0] = " + newValues[0]); log.debug("idsString.length = " + idsString.length); if (collection == null) collection = new LinkedList(); collection.clear(); if (idsString.length > 0) { ReflectionMarshaller collectionMarshaller = ReflectionMarshaller .getForClass(collectionType); log.debug("CollectionType = " + collectionType.getName()); for (String idString : idsString) { if (idString.equals("")) { log.debug("Skipping empty idString"); continue; } collection.add( controller.proxy(collectionType, collectionMarshaller.asIdType(idString))); } } field.set(entity, collection); } } else { error = true; } } catch (IllegalAccessException iae) { log.error("Unable to set " + field.getName() + " directly.", iae); error = true; } catch (ClassCastException cce) { log.error("Error setting " + field.getName() + ".", cce); error = true; } // if we hit an error getting it directly, try via the getter if (error) { error = false; try { setter = converter.getSetter(); if (setter != null) { if (!setter.isAccessible()) { setter.setAccessible(true); } if (setter.isAccessible()) { if (!isEntity && !isCollection) { // if it's an array, it needs special treatment if (fieldType.isArray()) { log.debug(field.getName() + " is an Array"); Class arrayType = fieldType.getComponentType(); // If we can, just convert with a cast() if (arrayType.isAssignableFrom(String.class)) { log.debug(arrayType.getName() + " is assignable from String.class"); Object[] newArray = new Object[newValues.length]; for (int i = 0; i < newValues.length; i++) { newArray[i] = arrayType.cast(newValues[i]); } setter.invoke(entity, newArray); } else { if (isInteger(fieldType)) { Integer[] newArray = new Integer[newValues.length]; for (int i = 0; i < newValues.length; i++) { newArray[i] = Integer.valueOf(newValues[i]); } setter.invoke(entity, (Object[]) newArray); } else if (isFloat(fieldType)) { Float[] newArray = new Float[newValues.length]; for (int i = 0; i < newValues.length; i++) { newArray[i] = Float.valueOf(newValues[i]); } setter.invoke(entity, (Object[]) newArray); } else if (isDouble(fieldType)) { Double[] newArray = new Double[newValues.length]; for (int i = 0; i < newValues.length; i++) { newArray[i] = Double.valueOf(newValues[i]); } setter.invoke(entity, (Object[]) newArray); } else if (isShort(fieldType)) { Short[] newArray = new Short[newValues.length]; for (int i = 0; i < newValues.length; i++) { newArray[i] = Short.valueOf(newValues[i]); } setter.invoke(entity, (Object[]) newArray); } else if (isChar(fieldType)) { setter.invoke(entity, ServletUtils.join(newValues, "").toCharArray()); } else if (isLong(fieldType)) { Long[] newArray = new Long[newValues.length]; for (int i = 0; i < newValues.length; i++) { newArray[i] = Long.valueOf(newValues[i]); } field.set(entity, (Object[]) newArray); } else if (isBoolean(fieldType)) { Boolean[] newArray = new Boolean[newValues.length]; for (int i = 0; i < newValues.length; i++) { newArray[i] = Boolean.valueOf(newValues[i]); } setter.invoke(entity, (Object[]) newArray); } else if (isByte(fieldType)) { Byte[] newArray = new Byte[newValues.length]; for (int i = 0; i < newValues.length; i++) { newArray[i] = Byte.valueOf(newValues[i]); } setter.invoke(entity, (Object[]) newArray); } else { throw new MarshallingException( "Don't know how to marshall an array of a non-primitive, and non-assignable type! field = " + field.getName()); } } } else { // Check out if it's assignable via a straight cast, // that could save time if (fieldType.isAssignableFrom(String.class)) { log.debug(fieldType.getName() + " is assignable from String.class"); // this might throw an exception, but we're going // to ignore it because there are other ways of // setting the value if this doesn't work. try { setter.invoke(entity, fieldType.cast(newValues[0])); } catch (Exception e) { log.debug("Error setting field by cast", e); } success = true; } // if it wasn't assignable via a straight cast, try // working around it. if (!success) { if (isInteger(fieldType)) { setter.invoke(entity, Integer.valueOf(newValues[0])); } else if (isFloat(fieldType)) { setter.invoke(entity, Float.valueOf(newValues[0])); } else if (isDouble(fieldType)) { setter.invoke(entity, Double.valueOf(newValues[0])); } else if (isShort(fieldType)) { setter.invoke(entity, Short.valueOf(newValues[0])); } else if (isChar(fieldType)) { setter.invoke(entity, newValues[0].charAt(0)); } else if (isLong(fieldType)) { setter.invoke(entity, Long.valueOf(newValues[0])); } else if (isBoolean(fieldType)) { setter.invoke(entity, Boolean.valueOf(newValues[0])); } else if (isByte(fieldType)) { setter.invoke(entity, Byte.valueOf(newValues[0])); } else if (isDate(fieldType)) { if (newValues[0].equals("")) { field.set(entity, null); } else { try { setter.invoke(entity, asDate(newValues[0])); } catch (ParseException pe) { log.warn("Error parsing date: " + newValues[0], pe); } } } else { log.debug("Not sure how to set " + field.getName() + " of type " + fieldType.getName() + ", attemping cast."); setter.invoke(entity, fieldType.cast(newValues[0])); } } } } else if (isEntity && !isCollection) { ReflectionMarshaller innerMarshaller = ReflectionMarshaller.getForClass(fieldType); setter.invoke(entity, controller.proxy(fieldType, innerMarshaller.asIdType(newValues[0]))); } else if (!isEntity && isCollection) { throw new MarshallingException( "Error, collections of non-entities are not yet supported."); } else if (isEntity && isCollection) { // for now, this is going to expect the parameter to be a // comma-delimited string of entity ids String[] idsString = newValues[0].toString().split(","); Collection collection = (Collection) field.get(entity); if (collection == null) collection = new LinkedList(); if (idsString.length == 0 && collection.isEmpty()) continue; collection.clear(); if (idsString.length > 0) { ReflectionMarshaller collectionMarshaller = ReflectionMarshaller .getForClass(collectionType); for (String idString : idsString) { if (idString.equals("")) { log.debug("Skipping empty idString"); continue; } collection.add(controller.proxy(collectionType, collectionMarshaller.asIdType(idString))); } } setter.invoke(entity, collection); } } else { error = true; } } else { error = true; } } catch (IllegalAccessException iae) { log.error("Error accessing setter", iae); error = true; } catch (InvocationTargetException ite) { log.error("Error invoking setter", ite); error = true; } } if (error) { throw new MarshallingException("Unable to marshall in field " + field.getName() + "."); } } return entity; }
From source file:com.hiperf.common.ui.server.storage.impl.PersistenceHelper.java
@Override public Object getCompositeId(Class<?> c, List<String> idFieldNames, List myId) throws InstantiationException, IllegalAccessException { IdClass idClass = c.getAnnotation(IdClass.class); Class clazz = idClass.value(); Object pk = clazz.newInstance(); for (Field f : clazz.getDeclaredFields()) { int idx = idFieldNames.indexOf(f.getName()); if (idx >= 0) { boolean b = false; if (!f.isAccessible()) { f.setAccessible(true);/*from w w w .ja va2 s . com*/ b = true; } f.set(pk, myId.get(idx)); if (b) f.setAccessible(false); } } return pk; }
From source file:com.hiperf.common.ui.server.storage.impl.PersistenceHelper.java
public List<INakedObject> fillResultList(String className, EntityManager em, Set<PropertyDescriptor> ids, List<String> idFieldNames, Query q, boolean hasOrder) throws ClassNotFoundException, InstantiationException, IllegalAccessException { q.setHint("org.hibernate.readOnly", Boolean.TRUE); List<Object[]> ll = q.getResultList(); if (ll != null && !ll.isEmpty()) { boolean single = ids.size() == 1; Object pk = null;/* ww w .j a va 2 s . com*/ Class<?> c = Class.forName(className); Class clazz = null; if (!single) { IdClass idClass = c.getAnnotation(IdClass.class); clazz = idClass.value(); pk = clazz.newInstance(); } List<INakedObject> list = new ArrayList<>(ll.size()); for (Object o : ll) { if (single) { list.add((INakedObject) em.find(c, hasOrder ? ((Object[]) o)[0] : o)); } else { for (Field f : clazz.getDeclaredFields()) { int idx = idFieldNames.indexOf(f.getName()); if (idx >= 0) { boolean b = false; if (!f.isAccessible()) { f.setAccessible(true); b = true; } f.set(pk, ((Object[]) o)[idx]); if (b) f.setAccessible(false); } } list.add((INakedObject) em.find(c, pk)); } } return list; } return null; }
From source file:com.hiperf.common.ui.server.storage.impl.PersistenceHelper.java
private void refreshManyToOneLinkedWithId(INakedObject o, com.hiperf.common.ui.shared.util.Id id, EntityManager em)/* ww w .jav a 2 s.co m*/ throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { Class<? extends INakedObject> clazz = o.getClass(); Field f = clazz.getDeclaredField(id.getFieldNames().get(0)); if (f.isAnnotationPresent(Id.class)) { int i = 0; for (String name : id.getFieldNames()) { f = clazz.getDeclaredField(id.getFieldNames().get(i)); String columnName = name; if (f.isAnnotationPresent(Column.class)) { columnName = f.getAnnotation(Column.class).name(); } for (Field field : clazz.getDeclaredFields()) { if (field.isAnnotationPresent(ManyToOne.class) && field.isAnnotationPresent(JoinColumn.class) && field.getAnnotation(JoinColumn.class).name().equalsIgnoreCase(columnName)) { boolean acc = field.isAccessible(); try { if (!acc) field.setAccessible(true); Object pk = id.getFieldValues().get(i); if (PersistenceManager.isLocal(pk)) { boolean acc2 = f.isAccessible(); try { if (!acc2) { f.setAccessible(true); } pk = f.get(o); } finally { if (!acc2) { f.setAccessible(false); } } if (!PersistenceManager.isLocal(pk)) field.set(o, em.find(field.getType(), pk)); } else field.set(o, em.find(field.getType(), pk)); } finally { field.setAccessible(acc); } break; } } i++; } } else { //TODO } }
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 . jav a2s .c o m*/ 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.clark.func.Functions.java
/** * Read a Field.//w w w . j a va2 s. co m * * @param field * the field to use * @param target * the object to call on, may be null for static fields * @param forceAccess * whether to break scope restrictions using the * <code>setAccessible</code> method. * @return the field value * @throws IllegalArgumentException * if the field is null * @throws IllegalAccessException * if the field is not made accessible */ public static Object readField(Field field, Object target, boolean forceAccess) throws IllegalAccessException { if (field == null) { throw new IllegalArgumentException("The field must not be null"); } if (forceAccess && !field.isAccessible()) { field.setAccessible(true); } else { setAccessibleWorkaround(field); } return field.get(target); }
From source file:com.clark.func.Functions.java
/** * Write a field./*from w w w. j a v a 2 s. c o m*/ * * @param field * to write * @param target * the object to call on, may be null for static fields * @param value * to set * @param forceAccess * whether to break scope restrictions using the * <code>setAccessible</code> method. <code>False</code> will * only match public fields. * @throws IllegalArgumentException * if the field is null * @throws IllegalAccessException * if the field is not made accessible or is final */ public static void writeField(Field field, Object target, Object value, boolean forceAccess) throws IllegalAccessException { if (field == null) { throw new IllegalArgumentException("The field must not be null"); } if (forceAccess && !field.isAccessible()) { field.setAccessible(true); } else { setAccessibleWorkaround(field); } field.set(target, value); }