List of usage examples for java.lang Class isAnnotationPresent
@Override public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass)
From source file:com.zenesis.qx.remote.ProxyTypeImpl.java
/** * Constructor, used for defining interfaces which are to be proxied * @param className//w w w. ja v a2s .co m * @param methods */ public ProxyTypeImpl(ProxyType superType, Class clazz, Set<ProxyType> interfaces) { super(); if (interfaces == null) interfaces = Collections.EMPTY_SET; this.superType = superType; this.interfaces = interfaces; this.clazz = clazz; MethodsCompiler methodsCompiler = new MethodsCompiler(); // Get a complete list of methods from the interfaces that the new class has to // implement; we include methods marked as DoNotProxy so that we can check for // conflicting instructions if (!clazz.isInterface()) { // Get a full list of the interfaces which our class has to implement HashSet<ProxyType> allInterfaces = new HashSet<ProxyType>(); getAllInterfaces(allInterfaces, interfaces); for (ProxyType ifcType : allInterfaces) { try { methodsCompiler.addMethods(Class.forName(ifcType.getClassName()), true); } catch (ClassNotFoundException e) { throw new IllegalStateException("Cannot find class " + ifcType.getClassName()); } } } boolean defaultProxy = false; if (clazz.isInterface()) defaultProxy = true; else { for (Class tmp = clazz; tmp != null; tmp = tmp.getSuperclass()) { if (factoryMethod == null) { for (Method method : tmp.getDeclaredMethods()) { if (method.isAnnotationPresent(FactoryMethod.class)) { if (!Modifier.isStatic(method.getModifiers())) throw new IllegalStateException("Cannot use method " + method + " as FactoryMethod because it is not static"); factoryMethod = method; method.setAccessible(true); break; } } } if (tmp.isAnnotationPresent(AlwaysProxy.class)) { defaultProxy = true; break; } else if (tmp.isAnnotationPresent(ExplicitProxyOnly.class)) { break; } } } // If the class does not have any proxied interfaces or the class is marked with // the AlwaysProxy annotation, then we take methods from the class definition methodsCompiler.addMethods(clazz, defaultProxy); methodsCompiler.checkValid(); methodsCompiler.removeSuperTypeMethods(); // Load properties HashMap<String, ProxyEvent> events = new HashMap<String, ProxyEvent>(); HashMap<String, ProxyProperty> properties = new HashMap<String, ProxyProperty>(); Properties annoProperties = (Properties) clazz.getAnnotation(Properties.class); if (annoProperties != null) { for (Property anno : annoProperties.value()) { ProxyProperty property = new ProxyPropertyImpl(clazz, anno.value(), anno, annoProperties); properties.put(property.getName(), property); ProxyEvent event = property.getEvent(); if (event != null) events.put(event.getName(), event); } } for (Field field : clazz.getDeclaredFields()) { Property anno = field.getAnnotation(Property.class); if (anno != null) { ProxyProperty property = new ProxyPropertyImpl(clazz, anno.value().length() > 0 ? anno.value() : field.getName(), anno, annoProperties); properties.put(property.getName(), property); ProxyEvent event = property.getEvent(); if (event != null) events.put(event.getName(), event); } } for (Method method : clazz.getDeclaredMethods()) { String name = method.getName(); if (name.length() < 4 || !name.startsWith("get") || !Character.isUpperCase(name.charAt(3))) continue; Property anno = method.getAnnotation(Property.class); if (anno == null) continue; name = Character.toLowerCase(name.charAt(3)) + name.substring(4); if (properties.containsKey(name)) continue; ProxyProperty property = new ProxyPropertyImpl(clazz, anno.value().length() > 0 ? anno.value() : name, anno, annoProperties); properties.put(property.getName(), property); ProxyEvent event = property.getEvent(); if (event != null) events.put(event.getName(), event); } // Classes need to have all inherited properties added if (!clazz.isInterface()) { for (ProxyType ifc : interfaces) addProperties((ProxyTypeImpl) ifc, properties); } // Remove property accessors for (ProxyProperty prop : properties.values()) methodsCompiler.removePropertyAccessors((ProxyPropertyImpl) prop); // Load events if (clazz.isAnnotationPresent(Events.class)) { Events annoEvents = (Events) clazz.getAnnotation(Events.class); for (Event annoEvent : annoEvents.value()) { if (!events.containsKey(annoEvent.value())) events.put(annoEvent.value(), new ProxyEvent(annoEvent)); } } // Classes need to have all inherited events added if (!clazz.isInterface()) { for (ProxyType type : interfaces) addEvents((ProxyTypeImpl) type, events); } // Save this.properties = properties.isEmpty() ? null : properties; this.events = events.isEmpty() ? null : events; this.methods = methodsCompiler.toArray(); }
From source file:org.ms123.common.data.MultiOperations.java
public static void populate(SessionContext sessionContext, Map sourceMap, Object destinationObj, Map hintsMap) { PersistenceManager pm = sessionContext.getPM(); if (hintsMap == null) { hintsMap = new HashMap(); }//from w ww . j av a 2s . c o m boolean noUpdate = Utils.getBoolean(hintsMap, "noUpdate", false); BeanMap destinationMap = new BeanMap(destinationObj); String entityName = m_inflector.getEntityName(destinationObj.getClass().getSimpleName()); debug("populate.sourceMap:" + sourceMap + ",destinationObj:" + destinationObj + ",destinationMap:" + destinationMap + "/hintsMap:" + hintsMap + "/entityName:" + entityName); if (sourceMap == null) { return; } debug("populate(" + entityName + ") is a persistObject:" + javax.jdo.JDOHelper.isPersistent(destinationObj) + "/" + javax.jdo.JDOHelper.isNew(destinationObj)); if (sourceMap.get("id") != null) { debug("populate(" + entityName + ") has id:" + sourceMap.get("id")); return; } Map permittedFields = sessionContext.getPermittedFields(entityName, "write"); Iterator<String> it = sourceMap.keySet().iterator(); while (it.hasNext()) { String propertyName = it.next(); boolean permitted = sessionContext.getPermissionService().hasAdminRole() || "team".equals(entityName) || sessionContext.isFieldPermitted(propertyName, entityName, "write"); if (!propertyName.startsWith("_") && !permitted) { debug("---->populate:field(" + propertyName + ") no write permission"); continue; } else { debug("++++>populate:field(" + propertyName + ") write permitted"); } String datatype = null; String edittype = null; if (!propertyName.startsWith("_")) { Map config = (Map) permittedFields.get(propertyName); if (config != null) { datatype = (String) config.get("datatype"); edittype = (String) config.get("edittype"); } } if (propertyName.equals(STATE_FIELD) && !sessionContext.getPermissionService().hasAdminRole()) { continue; } if ("auto".equals(edittype)) continue; String mode = null; Map hm = (Map) hintsMap.get(propertyName); if (hm != null) { Object m = hm.get("mode"); if (m != null && m instanceof String) { mode = (String) m; } if (mode == null) { m = hm.get("useit"); if (m != null && m instanceof String) { mode = (String) m; } } } if (mode == null) { mode = "replace"; } Class propertyClass = destinationMap.getType(propertyName); debug("\ttype:" + propertyClass + "(" + propertyName + "=" + sourceMap.get(propertyName) + ")"); if ("_ignore_".equals(sourceMap.get(propertyName))) { continue; } if (propertyClass == null) { debug("\t--- Warning property not found:" + propertyName); } else if (propertyClass.equals(java.util.Date.class)) { String value = Utils.getString(sourceMap.get(propertyName), destinationMap.get(propertyName), mode); debug("\tDate found:" + propertyName + "=>" + value); Date date = null; if (value != null) { try { Long val = Long.valueOf(value); date = (Date) ConvertUtils.convert(val, Date.class); debug("\tdate1:" + date); } catch (Exception e) { try { DateTime dt = new DateTime(value); date = new Date(dt.getMillis()); debug("\tdate2:" + date); } catch (Exception e1) { try { int space = value.indexOf(" "); if (space != -1) { value = value.substring(0, space) + "T" + value.substring(space + 1); DateTime dt = new DateTime(value); date = new Date(dt.getMillis()); } debug("\tdate3:" + date); } catch (Exception e2) { debug("\terror setting date:" + e); } } } } debug("\tsetting date:" + date); destinationMap.put(propertyName, date); } else if (propertyClass.equals(java.util.Map.class)) { info("!!!!!!!!!!!!!!!!!!!Map not implemented"); } else if (propertyClass.equals(java.util.List.class) || propertyClass.equals(java.util.Set.class)) { boolean isList = propertyClass.equals(java.util.List.class); boolean isSimple = false; if (datatype != null && datatype.startsWith("list_")) { isSimple = true; } try { Class propertyType = TypeUtils.getTypeForField(destinationObj, propertyName); debug("propertyType:" + propertyType + " fill with: " + sourceMap.get(propertyName) + ",list:" + destinationMap.get(propertyName) + "/mode:" + mode); Collection sourceList = isList ? new ArrayList() : new HashSet(); Object fromVal = sourceMap.get(propertyName); if (fromVal instanceof String && ((String) fromVal).length() > 0) { info("FromVal is StringSchrott, ignore"); continue; } if (sourceMap.get(propertyName) instanceof Collection) { sourceList = (Collection) sourceMap.get(propertyName); } if (sourceList == null) { sourceList = isList ? new ArrayList() : new HashSet(); } Collection destinationList = (Collection) PropertyUtils.getProperty(destinationObj, propertyName); debug("destinationList:" + destinationList); debug("sourceList:" + sourceList); if (destinationList == null) { destinationList = isList ? new ArrayList() : new HashSet(); PropertyUtils.setProperty(destinationObj, propertyName, destinationList); } if ("replace".equals(mode)) { boolean isEqual = false; if (isSimple) { isEqual = Utils.isCollectionEqual(destinationList, sourceList); if (!isEqual) { destinationList.clear(); } debug("\tisEqual:" + isEqual); } else { List deleteList = new ArrayList(); String namespace = sessionContext.getStoreDesc().getNamespace(); for (Object o : destinationList) { if (propertyType.getName().endsWith(".Team")) { int status = sessionContext.getTeamService().getTeamStatus(namespace, new BeanMap(o), null, sessionContext.getUserName()); debug("populate.replace.teamStatus:" + status + "/" + new HashMap(new BeanMap(o))); if (status != -1) { pm.deletePersistent(o); deleteList.add(o); } } else { pm.deletePersistent(o); deleteList.add(o); } } for (Object o : deleteList) { destinationList.remove(o); } } debug("populate.replace.destinationList:" + destinationList + "/" + propertyType.getName()); if (isSimple) { if (!isEqual) { for (Object o : sourceList) { destinationList.add(o); } } } else { for (Object o : sourceList) { Map childSourceMap = (Map) o; Object childDestinationObj = propertyType.newInstance(); if (propertyType.getName().endsWith(".Team")) { childSourceMap.remove("id"); Object desc = childSourceMap.get("description"); Object name = childSourceMap.get("name"); Object dis = childSourceMap.get("disabled"); String teamid = (String) childSourceMap.get("teamid"); Object ti = Utils.getTeamintern(sessionContext, teamid); if (desc == null) { childSourceMap.put("description", PropertyUtils.getProperty(ti, "description")); } if (name == null) { childSourceMap.put("name", PropertyUtils.getProperty(ti, "name")); } if (dis == null) { childSourceMap.put("disabled", false); } pm.makePersistent(childDestinationObj); populate(sessionContext, childSourceMap, childDestinationObj, hintsMap); PropertyUtils.setProperty(childDestinationObj, "teamintern", ti); } else { pm.makePersistent(childDestinationObj); populate(sessionContext, childSourceMap, childDestinationObj, hintsMap); } debug("populated.add:" + new HashMap(new BeanMap(childDestinationObj))); destinationList.add(childDestinationObj); } } } else if ("remove".equals(mode)) { if (isSimple) { for (Object o : sourceList) { if (destinationList.contains(o)) { destinationList.remove(o); } } } else { for (Object ol : sourceList) { Map childSourceMap = (Map) ol; Object o = Utils.listContainsId(destinationList, childSourceMap, "teamid"); if (o != null) { destinationList.remove(o); pm.deletePersistent(o); } } } } else if ("add".equals(mode)) { if (isSimple) { for (Object o : sourceList) { destinationList.add(o); } } else { for (Object ol : sourceList) { Map childSourceMap = (Map) ol; Object childDestinationObj = Utils.listContainsId(destinationList, childSourceMap, "teamid"); if (childDestinationObj != null) { populate(sessionContext, childSourceMap, childDestinationObj, hintsMap); } else { childDestinationObj = propertyType.newInstance(); if (propertyType.getName().endsWith(".Team")) { Object desc = childSourceMap.get("description"); Object name = childSourceMap.get("name"); Object dis = childSourceMap.get("disabled"); String teamid = (String) childSourceMap.get("teamid"); Object ti = Utils.getTeamintern(sessionContext, teamid); if (desc == null) { childSourceMap.put("description", PropertyUtils.getProperty(ti, "description")); } if (name == null) { childSourceMap.put("name", PropertyUtils.getProperty(ti, "name")); } if (dis == null) { childSourceMap.put("disabled", false); } pm.makePersistent(childDestinationObj); populate(sessionContext, childSourceMap, childDestinationObj, hintsMap); PropertyUtils.setProperty(childDestinationObj, "teamintern", ti); } else { pm.makePersistent(childDestinationObj); populate(sessionContext, childSourceMap, childDestinationObj, hintsMap); } destinationList.add(childDestinationObj); } } } } else if ("assign".equals(mode)) { if (!isSimple) { for (Object ol : sourceList) { Map childSourceMap = (Map) ol; Object childDestinationObj = Utils.listContainsId(destinationList, childSourceMap); if (childDestinationObj != null) { debug("id:" + childSourceMap + " already assigned"); } else { Object id = childSourceMap.get("id"); Boolean assign = Utils.getBoolean(childSourceMap.get("assign")); Object obj = pm.getObjectById(propertyType, id); if (assign) { destinationList.add(obj); } else { destinationList.remove(obj); } } } } } } catch (Exception e) { e.printStackTrace(); debug("populate.list.failed:" + propertyName + "=>" + sourceMap.get(propertyName) + ";" + e); } } else if (propertyClass.equals(java.lang.Boolean.class)) { try { destinationMap.put(propertyName, ConvertUtils.convert(sourceMap.get(propertyName), Boolean.class)); } catch (Exception e) { debug("populate.boolean.failed:" + propertyName + "=>" + sourceMap.get(propertyName) + ";" + e); } } else if (propertyClass.equals(java.lang.Double.class)) { String value = Utils.getString(sourceMap.get(propertyName), destinationMap.get(propertyName), mode); try { destinationMap.put(propertyName, Double.valueOf(value)); } catch (Exception e) { debug("populate.double.failed:" + propertyName + "=>" + value + ";" + e); } } else if (propertyClass.equals(java.lang.Long.class)) { try { destinationMap.put(propertyName, ConvertUtils.convert(sourceMap.get(propertyName), Long.class)); } catch (Exception e) { debug("populate.long.failed:" + propertyName + "=>" + sourceMap.get(propertyName) + ";" + e); } } else if (propertyClass.equals(java.lang.Integer.class)) { debug("Integer:" + ConvertUtils.convert(sourceMap.get(propertyName), Integer.class)); try { destinationMap.put(propertyName, ConvertUtils.convert(sourceMap.get(propertyName), Integer.class)); } catch (Exception e) { debug("populate.integer.failed:" + propertyName + "=>" + sourceMap.get(propertyName) + ";" + e); } } else if ("binary".equals(datatype) || propertyClass.equals(byte[].class)) { InputStream is = null; InputStream is2 = null; try { if (sourceMap.get(propertyName) instanceof FileItem) { FileItem fi = (FileItem) sourceMap.get(propertyName); String name = fi.getName(); byte[] bytes = IOUtils.toByteArray(fi.getInputStream()); if (bytes != null) { debug("bytes:" + bytes.length); } destinationMap.put(propertyName, bytes); is = fi.getInputStream(); is2 = fi.getInputStream(); } else if (sourceMap.get(propertyName) instanceof Map) { Map map = (Map) sourceMap.get(propertyName); String storeLocation = (String) map.get("storeLocation"); is = new FileInputStream(new File(storeLocation)); is2 = new FileInputStream(new File(storeLocation)); byte[] bytes = IOUtils.toByteArray(is); if (bytes != null) { debug("bytes2:" + bytes.length); } is.close(); destinationMap.put(propertyName, bytes); is = new FileInputStream(new File(storeLocation)); } else if (sourceMap.get(propertyName) instanceof String) { String value = (String) sourceMap.get(propertyName); if (value.startsWith("data:")) { int ind = value.indexOf(";base64,"); byte b[] = Base64.decode(value.substring(ind + 8)); destinationMap.put(propertyName, b); is = new ByteArrayInputStream(b); is2 = new ByteArrayInputStream(b); } else { } } else { debug("populate.byte[].no a FileItem:" + propertyName + "=>" + sourceMap.get(propertyName)); continue; } Tika tika = new Tika(); TikaInputStream stream = TikaInputStream.get(is); TikaInputStream stream2 = TikaInputStream.get(is2); String text = tika.parseToString(is); debug("Text:" + text); try { destinationMap.put("text", text); } catch (Exception e) { destinationMap.put("text", text.getBytes()); } //@@@MS Hardcoded try { Detector detector = new DefaultDetector(); MediaType mime = detector.detect(stream2, new Metadata()); debug("Mime:" + mime.getType() + "|" + mime.getSubtype() + "|" + mime.toString()); destinationMap.put("type", mime.toString()); sourceMap.put("type", mime.toString()); } catch (Exception e) { e.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); debug("populate.byte[].failed:" + propertyName + "=>" + sourceMap.get(propertyName) + ";" + e); } finally { try { is.close(); is2.close(); } catch (Exception e) { } } } else { boolean ok = false; try { Class propertyType = TypeUtils.getTypeForField(destinationObj, propertyName); debug("propertyType:" + propertyType + "/" + propertyName); if (propertyType != null) { boolean hasAnn = propertyType.isAnnotationPresent(PersistenceCapable.class); debug("hasAnnotation:" + hasAnn); if (propertyType.newInstance() instanceof javax.jdo.spi.PersistenceCapable || hasAnn) { handleRelatedTo(sessionContext, sourceMap, propertyName, destinationMap, destinationObj, propertyType); Object obj = sourceMap.get(propertyName); if (obj != null && obj instanceof Map) { Map childSourceMap = (Map) obj; Object childDestinationObj = destinationMap.get(propertyName); if (childDestinationObj == null) { childDestinationObj = propertyType.newInstance(); destinationMap.put(propertyName, childDestinationObj); } populate(sessionContext, childSourceMap, childDestinationObj, hintsMap); } else { if (obj == null) { destinationMap.put(propertyName, null); } } ok = true; } } } catch (Exception e) { e.printStackTrace(); } if (!ok) { String value = Utils.getString(sourceMap.get(propertyName), destinationMap.get(propertyName), mode); try { if (noUpdate) { if (Utils.isEmptyObj(destinationMap.get(propertyName))) { destinationMap.put(propertyName, value); } } else { destinationMap.put(propertyName, value); } } catch (Exception e) { debug("populate.failed:" + propertyName + "=>" + value + ";" + e); } } } } }
From source file:org.ms123.common.data.JdoLayerImpl.java
public void populate(SessionContext sessionContext, Map from, Object to, Map hintsMap) { PersistenceManager pm = sessionContext.getPM(); if (hintsMap == null) { hintsMap = new HashMap(); }//from ww w .ja va2s .com Map<String, String> expressions = (Map) hintsMap.get("__expressions"); if (expressions == null) expressions = new HashMap(); BeanMap beanMap = new BeanMap(to); String entityName = m_inflector.getEntityName(to.getClass().getSimpleName()); debug("populate.from:" + from + ",to:" + to + ",BeanMap:" + beanMap + "/hintsMap:" + hintsMap + "/entityName:" + entityName); if (from == null) { return; } Map permittedFields = sessionContext.getPermittedFields(entityName, "write"); Iterator<String> it = from.keySet().iterator(); while (it.hasNext()) { String key = it.next(); Object oldValue = beanMap.get(key); boolean permitted = m_permissionService.hasAdminRole() || "team".equals(entityName) || sessionContext.isFieldPermitted(key, entityName, "write"); if (!key.startsWith("_") && !permitted) { debug("---->populate:field(" + key + ") no write permission"); continue; } else { debug("++++>populate:field(" + key + ") write permitted"); } String datatype = null; String edittype = null; if (!key.startsWith("_")) { Map config = (Map) permittedFields.get(key); if (config != null) { datatype = (String) config.get("datatype"); edittype = (String) config.get("edittype"); } } if (key.equals(STATE_FIELD) && !m_permissionService.hasAdminRole()) { continue; } if ("auto".equals(edittype)) continue; String mode = null; Map hm = (Map) hintsMap.get(key); if (hm != null) { Object m = hm.get("mode"); if (m != null && m instanceof String) { mode = (String) m; } if (mode == null) { m = hm.get("useit"); if (m != null && m instanceof String) { mode = (String) m; } } } if (mode == null) { mode = "replace"; } Class clazz = beanMap.getType(key); debug("\ttype:" + clazz + "(" + key + "=" + from.get(key) + ")"); if ("_ignore_".equals(from.get(key))) { continue; } if (clazz == null) { debug("\t--- Warning property not found:" + key); } else if (clazz.equals(java.util.Date.class)) { String value = Utils.getString(from.get(key), beanMap.get(key), mode); debug("\tDate found:" + key + "=>" + value); Date date = null; if (value != null) { try { Long val = Long.valueOf(value); date = (Date) ConvertUtils.convert(val, Date.class); debug("\tdate1:" + date); } catch (Exception e) { try { DateTime dt = new DateTime(value); date = new Date(dt.getMillis()); debug("\tdate2:" + date); } catch (Exception e1) { try { int space = value.indexOf(" "); if (space != -1) { value = value.substring(0, space) + "T" + value.substring(space + 1); DateTime dt = new DateTime(value); date = new Date(dt.getMillis()); } debug("\tdate3:" + date); } catch (Exception e2) { debug("\terror setting date:" + e); } } } } debug("\tsetting date:" + date); beanMap.put(key, date); } else if (clazz.equals(java.util.Map.class)) { info("!!!!!!!!!!!!!!!!!!!Map not implemented"); } else if (clazz.equals(java.util.List.class) || clazz.equals(java.util.Set.class)) { boolean isList = clazz.equals(java.util.List.class); boolean isSimple = false; if (datatype != null && datatype.startsWith("list_")) { isSimple = true; } try { Class type = TypeUtils.getTypeForField(to, key); debug("type:" + type + " fill with: " + from.get(key) + ",list:" + beanMap.get(key) + "/mode:" + mode); Collection valList = isList ? new ArrayList() : new HashSet(); Object fromVal = from.get(key); if (fromVal instanceof String && ((String) fromVal).length() > 0) { info("FromVal is StringSchrott, ignore"); continue; } if (from.get(key) instanceof Collection) { valList = (Collection) from.get(key); } if (valList == null) { valList = isList ? new ArrayList() : new HashSet(); } Collection toList = (Collection) PropertyUtils.getProperty(to, key); debug("toList:" + toList); debug("valList:" + valList); if (toList == null) { toList = isList ? new ArrayList() : new HashSet(); PropertyUtils.setProperty(to, key, toList); } if ("replace".equals(mode)) { boolean isEqual = false; if (isSimple) { isEqual = Utils.isCollectionEqual(toList, valList); if (!isEqual) { toList.clear(); } debug("\tisEqual:" + isEqual); } else { List deleteList = new ArrayList(); String namespace = sessionContext.getStoreDesc().getNamespace(); for (Object o : toList) { if (type.getName().endsWith(".Team")) { int status = m_teamService.getTeamStatus(namespace, new BeanMap(o), null, sessionContext.getUserName()); debug("populate.replace.teamStatus:" + status + "/" + new HashMap(new BeanMap(o))); if (status != -1) { pm.deletePersistent(o); deleteList.add(o); } } else { pm.deletePersistent(o); deleteList.add(o); } } for (Object o : deleteList) { toList.remove(o); } } debug("populate.replace.toList:" + toList + "/" + type.getName()); if (isSimple) { if (!isEqual) { for (Object o : valList) { toList.add(o); } } } else { for (Object o : valList) { Map valMap = (Map) o; Object n = type.newInstance(); if (type.getName().endsWith(".Team")) { valMap.remove("id"); Object desc = valMap.get("description"); Object name = valMap.get("name"); Object dis = valMap.get("disabled"); String teamid = (String) valMap.get("teamid"); Object ti = Utils.getTeamintern(sessionContext, teamid); if (desc == null) { valMap.put("description", PropertyUtils.getProperty(ti, "description")); } if (name == null) { valMap.put("name", PropertyUtils.getProperty(ti, "name")); } if (dis == null) { valMap.put("disabled", false); } pm.makePersistent(n); populate(sessionContext, valMap, n, null); PropertyUtils.setProperty(n, "teamintern", ti); } else { pm.makePersistent(n); populate(sessionContext, valMap, n, null); } debug("populated.add:" + new HashMap(new BeanMap(n))); toList.add(n); } } } else if ("remove".equals(mode)) { if (isSimple) { for (Object o : valList) { if (toList.contains(o)) { toList.remove(o); } } } else { for (Object ol : valList) { Map map = (Map) ol; Object o = Utils.listContainsId(toList, map, "teamid"); if (o != null) { toList.remove(o); pm.deletePersistent(o); } } } } else if ("add".equals(mode)) { if (isSimple) { for (Object o : valList) { toList.add(o); } } else { for (Object ol : valList) { Map map = (Map) ol; Object o = Utils.listContainsId(toList, map, "teamid"); if (o != null) { populate(sessionContext, map, o, null); } else { o = type.newInstance(); if (type.getName().endsWith(".Team")) { Object desc = map.get("description"); Object name = map.get("name"); Object dis = map.get("disabled"); String teamid = (String) map.get("teamid"); Object ti = Utils.getTeamintern(sessionContext, teamid); if (desc == null) { map.put("description", PropertyUtils.getProperty(ti, "description")); } if (name == null) { map.put("name", PropertyUtils.getProperty(ti, "name")); } if (dis == null) { map.put("disabled", false); } pm.makePersistent(o); populate(sessionContext, map, o, null); PropertyUtils.setProperty(o, "teamintern", ti); } else { pm.makePersistent(o); populate(sessionContext, map, o, null); } toList.add(o); } } } } else if ("assign".equals(mode)) { if (!isSimple) { for (Object ol : valList) { Map map = (Map) ol; Object o = Utils.listContainsId(toList, map); if (o != null) { debug("id:" + map + " already assigned"); } else { Object id = map.get("id"); Boolean assign = Utils.getBoolean(map.get("assign")); Object obj = pm.getObjectById(type, id); if (assign) { toList.add(obj); } else { toList.remove(obj); } } } } } } catch (Exception e) { e.printStackTrace(); debug("populate.list.failed:" + key + "=>" + from.get(key) + ";" + e); } } else if (clazz.equals(java.lang.Boolean.class)) { try { beanMap.put(key, ConvertUtils.convert(from.get(key), Boolean.class)); } catch (Exception e) { debug("populate.boolean.failed:" + key + "=>" + from.get(key) + ";" + e); } } else if (clazz.equals(java.lang.Double.class)) { String value = Utils.getString(from.get(key), beanMap.get(key), mode); try { beanMap.put(key, Double.valueOf(value)); } catch (Exception e) { debug("populate.double.failed:" + key + "=>" + value + ";" + e); } } else if (clazz.equals(java.lang.Long.class)) { try { beanMap.put(key, ConvertUtils.convert(from.get(key), Long.class)); } catch (Exception e) { debug("populate.long.failed:" + key + "=>" + from.get(key) + ";" + e); } } else if (clazz.equals(java.lang.Integer.class)) { debug("Integer:" + ConvertUtils.convert(from.get(key), Integer.class)); try { beanMap.put(key, ConvertUtils.convert(from.get(key), Integer.class)); } catch (Exception e) { debug("populate.integer.failed:" + key + "=>" + from.get(key) + ";" + e); } } else if ("binary".equals(datatype) || clazz.equals(byte[].class)) { InputStream is = null; InputStream is2 = null; try { if (from.get(key) instanceof FileItem) { FileItem fi = (FileItem) from.get(key); String name = fi.getName(); byte[] bytes = IOUtils.toByteArray(fi.getInputStream()); if (bytes != null) { debug("bytes:" + bytes.length); } beanMap.put(key, bytes); is = fi.getInputStream(); is2 = fi.getInputStream(); } else if (from.get(key) instanceof Map) { Map map = (Map) from.get(key); String storeLocation = (String) map.get("storeLocation"); is = new FileInputStream(new File(storeLocation)); is2 = new FileInputStream(new File(storeLocation)); byte[] bytes = IOUtils.toByteArray(is); if (bytes != null) { debug("bytes2:" + bytes.length); } is.close(); beanMap.put(key, bytes); is = new FileInputStream(new File(storeLocation)); } else if (from.get(key) instanceof String) { String value = (String) from.get(key); if ("ignore".equals(value)) { debug("ignore:"); return; } if (value.startsWith("data:")) { int ind = value.indexOf(";base64,"); byte b[] = Base64.decode(value.substring(ind + 8)); beanMap.put(key, b); is = new ByteArrayInputStream(b); is2 = new ByteArrayInputStream(b); } else { byte b[] = value.getBytes(); beanMap.put(key, b); is = new ByteArrayInputStream(b); is2 = new ByteArrayInputStream(b); } } else { debug("populate.byte[].no a FileItem:" + key + "=>" + from.get(key)); continue; } Tika tika = new Tika(); TikaInputStream stream = TikaInputStream.get(is); TikaInputStream stream2 = TikaInputStream.get(is2); String text = tika.parseToString(is); debug("Text:" + text); try { beanMap.put("text", text); } catch (Exception e) { beanMap.put("text", text.getBytes()); } //@@@MS Hardcoded try { Detector detector = new DefaultDetector(); MediaType mime = detector.detect(stream2, new Metadata()); debug("Mime:" + mime.getType() + "|" + mime.getSubtype() + "|" + mime.toString()); beanMap.put("type", mime.toString()); from.put("type", mime.toString()); } catch (Exception e) { e.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); debug("populate.byte[].failed:" + key + "=>" + from.get(key) + ";" + e); } finally { try { is.close(); is2.close(); } catch (Exception e) { } } } else { boolean ok = false; try { Class type = TypeUtils.getTypeForField(to, key); if (type != null) { Object o = type.newInstance(); boolean hasAnn = type.isAnnotationPresent(PersistenceCapable.class); debug("hasAnnotation:" + hasAnn); if (o instanceof javax.jdo.spi.PersistenceCapable || hasAnn) { Object id = null; try { Object _id = from.get(key); if (_id != null) { if (_id instanceof Map) { id = ((Map) _id).get("id"); } else { String s = String.valueOf(_id); if (s.indexOf("/") >= 0) { _id = Utils.extractId(s); } Class idClass = PropertyUtils.getPropertyType(o, "id"); id = (idClass.equals(Long.class)) ? Long.valueOf(_id + "") : _id; } } } catch (Exception e) { } if (id != null && !"".equals(id) && !"null".equals(id)) { debug("\tId2:" + id); Object relatedObject = pm.getObjectById(type, id); List<Collection> candidates = TypeUtils.getCandidateLists(relatedObject, to, null); if (candidates.size() == 1) { Collection l = candidates.get(0); debug("list.contains:" + l.contains(to)); if (!l.contains(to)) { l.add(to); } } beanMap.put(key, relatedObject); } else { Object relatedObject = beanMap.get(key); debug("\trelatedObject:" + relatedObject); if (relatedObject != null) { List<Collection> candidates = TypeUtils.getCandidateLists(relatedObject, to, null); if (candidates.size() == 1) { Collection l = candidates.get(0); debug("list.contains:" + l.contains(to)); if (l.contains(to)) { l.remove(to); } } } beanMap.put(key, null); } ok = true; } } } catch (Exception e) { e.printStackTrace(); } if (!ok) { String value = Utils.getString(from.get(key), beanMap.get(key), mode); // debug("populate:" + key + "=>" + value); // debug("String:" + ConvertUtils.convert(from.get(key), String.class)); try { beanMap.put(key, value); } catch (Exception e) { debug("populate.failed:" + key + "=>" + value + ";" + e); } } } String expression = expressions.get(key); if (!isEmpty(expression)) { beanMap.put(key, oldValue); Map scriptCache = (Map) sessionContext.getProperty("scriptCache"); if (scriptCache == null) { scriptCache = new HashMap(); sessionContext.setProperty("scriptCache", scriptCache); } Object result = Utils.eval(expression, beanMap, scriptCache); try { if ("string".equals(datatype) && !(result instanceof String)) { beanMap.put(key, ConvertUtils.convert(result, String.class)); } else { beanMap.put(key, result); } } catch (Exception e) { info("Cannot set value for(" + key + "):" + result + "/" + e.getMessage()); } } } }
From source file:ca.oson.json.Oson.java
<T> T deserialize2Object(FieldData objectDTO) { Object valueToProcess = objectDTO.valueToProcess; Map<String, Object> map = null; if (valueToProcess != null && Map.class.isAssignableFrom(valueToProcess.getClass())) { map = (Map) valueToProcess; } else {// w ww. jav a2 s . c o m map = new HashMap<>(); } Class<T> valueType = objectDTO.returnType; T obj = (T) objectDTO.returnObj; Set<String> nameKeys = new HashSet(map.keySet()); if (valueType == null) { valueType = (Class<T>) obj.getClass(); } // first build up the class-level processing rules ClassMapper classMapper = objectDTO.classMapper; //if (classMapper == null) { // 1. Create a blank class mapper instance classMapper = new ClassMapper(valueType); // 2. Globalize it classMapper = globalize(classMapper); objectDTO.classMapper = classMapper; //} if (objectDTO.fieldMapper != null && isInheritMapping()) { classMapper = overwriteBy(classMapper, objectDTO.fieldMapper); } objectDTO.incrLevel(); try { boolean annotationSupport = getAnnotationSupport(); Annotation[] annotations = null; if (annotationSupport) { ca.oson.json.annotation.ClassMapper classMapperAnnotation = null; // 3. Apply annotations from other sources annotations = valueType.getAnnotations(); for (Annotation annotation : annotations) { if (ignoreClass(annotation)) { return null; } switch (annotation.annotationType().getName()) { case "ca.oson.json.annotation.ClassMapper": classMapperAnnotation = (ca.oson.json.annotation.ClassMapper) annotation; if (!(classMapperAnnotation.serialize() == BOOLEAN.BOTH || classMapperAnnotation.serialize() == BOOLEAN.FALSE)) { classMapperAnnotation = null; } break; case "ca.oson.json.annotation.ClassMappers": ca.oson.json.annotation.ClassMappers classMapperAnnotations = (ca.oson.json.annotation.ClassMappers) annotation; for (ca.oson.json.annotation.ClassMapper ann : classMapperAnnotations.value()) { if (ann.serialize() == BOOLEAN.BOTH || ann.serialize() == BOOLEAN.FALSE) { classMapperAnnotation = ann; // break; } } break; case "com.google.gson.annotations.Since": Since since = (Since) annotation; classMapper.since = since.value(); break; case "com.google.gson.annotations.Until": Until until = (Until) annotation; classMapper.until = until.value(); break; case "com.fasterxml.jackson.annotation.JsonIgnoreProperties": JsonIgnoreProperties jsonIgnoreProperties = (JsonIgnoreProperties) annotation; String[] jsonnames = jsonIgnoreProperties.value(); if (jsonnames != null && jsonnames.length > 0) { if (classMapper.jsonIgnoreProperties == null) { classMapper.jsonIgnoreProperties = new HashSet(); } classMapper.jsonIgnoreProperties.addAll(Arrays.asList(jsonnames)); } break; case "org.codehaus.jackson.annotate.JsonIgnoreProperties": org.codehaus.jackson.annotate.JsonIgnoreProperties jsonIgnoreProperties2 = (org.codehaus.jackson.annotate.JsonIgnoreProperties) annotation; String[] jsonnames2 = jsonIgnoreProperties2.value(); if (jsonnames2 != null && jsonnames2.length > 0) { if (classMapper.jsonIgnoreProperties == null) { classMapper.jsonIgnoreProperties = new HashSet(); } classMapper.jsonIgnoreProperties.addAll(Arrays.asList(jsonnames2)); } break; case "com.fasterxml.jackson.annotation.JsonPropertyOrder": // first come first serve if (classMapper.propertyOrders == null) { classMapper.propertyOrders = ((JsonPropertyOrder) annotation).value(); } break; case "org.codehaus.jackson.annotate.JsonPropertyOrder": // first come first serve if (classMapper.propertyOrders == null) { classMapper.propertyOrders = ((org.codehaus.jackson.annotate.JsonPropertyOrder) annotation) .value(); } break; case "com.fasterxml.jackson.annotation.JsonInclude": if (classMapper.defaultType == JSON_INCLUDE.NONE) { JsonInclude jsonInclude = (JsonInclude) annotation; switch (jsonInclude.content()) { case ALWAYS: classMapper.defaultType = JSON_INCLUDE.ALWAYS; break; case NON_NULL: classMapper.defaultType = JSON_INCLUDE.NON_NULL; break; case NON_ABSENT: classMapper.defaultType = JSON_INCLUDE.NON_NULL; break; case NON_EMPTY: classMapper.defaultType = JSON_INCLUDE.NON_EMPTY; break; case NON_DEFAULT: classMapper.defaultType = JSON_INCLUDE.NON_DEFAULT; break; case USE_DEFAULTS: classMapper.defaultType = JSON_INCLUDE.DEFAULT; break; } } break; case "com.fasterxml.jackson.annotation.JsonAutoDetect": JsonAutoDetect jsonAutoDetect = (JsonAutoDetect) annotation; if (jsonAutoDetect.fieldVisibility() == Visibility.NONE) { classMapper.useField = false; } else if (jsonAutoDetect.fieldVisibility() != Visibility.DEFAULT) { classMapper.useField = true; } if (jsonAutoDetect.setterVisibility() == Visibility.NONE) { classMapper.useAttribute = false; } else if (jsonAutoDetect.setterVisibility() != Visibility.DEFAULT) { classMapper.useAttribute = true; } break; case "org.codehaus.jackson.annotate.JsonAutoDetect": org.codehaus.jackson.annotate.JsonAutoDetect jsonAutoDetect2 = (org.codehaus.jackson.annotate.JsonAutoDetect) annotation; if (jsonAutoDetect2 .fieldVisibility() == org.codehaus.jackson.annotate.JsonAutoDetect.Visibility.NONE) { classMapper.useField = false; } if (jsonAutoDetect2 .getterVisibility() == org.codehaus.jackson.annotate.JsonAutoDetect.Visibility.NONE) { classMapper.useAttribute = false; } break; case "org.junit.Ignore": classMapper.ignore = true; break; } } // 4. Apply annotations from Oson if (classMapperAnnotation != null) { classMapper = overwriteBy(classMapper, classMapperAnnotation); } } // 5. Apply Java configuration for this particular class ClassMapper javaClassMapper = getClassMapper(valueType); if (javaClassMapper != null) { classMapper = overwriteBy(classMapper, javaClassMapper); } // now processing at the class level if (classMapper.ignore()) { return null; } if (classMapper.since != null && classMapper.since > getVersion()) { return null; } else if (classMapper.until != null && classMapper.until <= getVersion()) { return null; } Function function = classMapper.deserializer; // = getDeserializer(valueType); if (function == null) { function = DeSerializerUtil.getDeserializer(valueType.getName()); } if (function != null) { try { Object returnedValue = null; if (function instanceof Json2DataMapperFunction) { DataMapper classData = new DataMapper(valueToProcess, valueType, obj, classMapper, objectDTO.level, getPrettyIndentation()); Json2DataMapperFunction f = (Json2DataMapperFunction) function; return (T) f.apply(classData); } else if (function instanceof Json2FieldDataFunction) { Json2FieldDataFunction f = (Json2FieldDataFunction) function; FieldData fieldData = objectDTO.clone(); returnedValue = f.apply(fieldData); } else { returnedValue = function.apply(obj); } if (returnedValue instanceof Optional) { Optional opt = (Optional) returnedValue; returnedValue = opt.orElse(null); } if (returnedValue == null) { return null; } else if (valueType.isAssignableFrom(returnedValue.getClass())) { return (T) returnedValue; } else { // not the correct returned object type, do nothing } } catch (Exception e) { e.printStackTrace(); } } Map<String, Method> getters = getGetters(valueType); Map<String, Method> setters = getSetters(valueType); Map<String, Method> otherMethods = getOtherMethods(valueType); Set<String> processedNameSet = new HashSet<>(); Method jsonAnySetterMethod = null; Field[] fields = getFields(valueType); // getFields(obj); FIELD_NAMING format = getFieldNaming(); // @Expose boolean exposed = false; if (isUseGsonExpose()) { // check if @exposed is used any where if (valueType.isAnnotationPresent(com.google.gson.annotations.Expose.class)) { exposed = true; } if (!exposed) { for (Field f : fields) { if (f.isAnnotationPresent(com.google.gson.annotations.Expose.class)) { exposed = true; break; } } } } for (Field f : fields) { String name = f.getName(); String fieldName = name; String lcfieldName = name.toLowerCase(); Class<?> returnType = f.getType(); // value.getClass(); if (Modifier.isFinal(f.getModifiers()) && Modifier.isStatic(f.getModifiers())) { setters.remove(lcfieldName); nameKeys.remove(name); continue; } f.setAccessible(true); // getter and setter methods Method getter = null; Method setter = null; if (getters != null) { getter = getters.get(lcfieldName); } if (setters != null) { setter = setters.get(lcfieldName); } if (ignoreModifiers(f.getModifiers(), classMapper.includeFieldsWithModifiers)) { if (setter != null) { if (ignoreModifiers(setter.getModifiers(), classMapper.includeFieldsWithModifiers)) { setters.remove(lcfieldName); nameKeys.remove(name); continue; } } else { continue; } } // 6. Create a blank field mapper instance // using valueType of enclosing obj FieldMapper fieldMapper = new FieldMapper(name, name, valueType); // 7. get the class mapper of returnType ClassMapper fieldClassMapper = getClassMapper(returnType); // 8. Classify this field mapper with returnType fieldMapper = classifyFieldMapper(fieldMapper, fieldClassMapper); // 9. Classify this field mapper with enclosing class type fieldMapper = classifyFieldMapper(fieldMapper, classMapper); FieldMapper javaFieldMapper = getFieldMapper(name, null, valueType); boolean ignored = false; if (setter != null) { setter.setAccessible(true); } Set<String> names = new HashSet<>(); if (annotationSupport) { annotations = f.getAnnotations(); if (setter != null && ((javaFieldMapper == null || javaFieldMapper.useAttribute == null) && (fieldMapper.useAttribute == null || fieldMapper.useAttribute)) || (javaFieldMapper != null && javaFieldMapper.isDeserializing() && javaFieldMapper.useAttribute != null && javaFieldMapper.useAttribute)) { annotations = Stream .concat(Arrays.stream(annotations), Arrays.stream(setter.getDeclaredAnnotations())) .toArray(Annotation[]::new); } // no annotations, then try get method if ((annotations == null || annotations.length == 0) && getter != null) { annotations = getter.getDeclaredAnnotations(); } ca.oson.json.annotation.FieldMapper fieldMapperAnnotation = null; boolean exposexists = false; for (Annotation annotation : annotations) { if (ignoreField(annotation, classMapper.ignoreFieldsWithAnnotations)) { ignored = true; break; } else if (annotation instanceof ca.oson.json.annotation.FieldMapper) { fieldMapperAnnotation = (ca.oson.json.annotation.FieldMapper) annotation; if (!(fieldMapperAnnotation.serialize() == BOOLEAN.BOTH || fieldMapperAnnotation.serialize() == BOOLEAN.FALSE)) { fieldMapperAnnotation = null; } } else if (annotation instanceof ca.oson.json.annotation.FieldMappers) { ca.oson.json.annotation.FieldMappers fieldMapperAnnotations = (ca.oson.json.annotation.FieldMappers) annotation; for (ca.oson.json.annotation.FieldMapper ann : fieldMapperAnnotations.value()) { if (ann.serialize() == BOOLEAN.BOTH || ann.serialize() == BOOLEAN.FALSE) { fieldMapperAnnotation = ann; //break; to enable the last one wins } } } else { switch (annotation.annotationType().getName()) { case "com.fasterxml.jackson.annotation.JsonAnySetter": case "org.codehaus.jackson.annotate.JsonAnySetter": fieldMapper.jsonAnySetter = true; break; case "javax.persistence.Transient": fieldMapper.ignore = true; break; case "com.fasterxml.jackson.annotation.JsonIgnore": case "org.codehaus.jackson.annotate.JsonIgnore": fieldMapper.ignore = true; break; case "com.fasterxml.jackson.annotation.JsonIgnoreProperties": JsonIgnoreProperties jsonIgnoreProperties = (JsonIgnoreProperties) annotation; if (!jsonIgnoreProperties.allowSetters()) { fieldMapper.ignore = true; } else { fieldMapper.ignore = false; classMapper.jsonIgnoreProperties.remove(name); } break; case "com.google.gson.annotations.Expose": Expose expose = (Expose) annotation; if (!expose.deserialize()) { fieldMapper.ignore = true; } exposexists = true; break; case "com.google.gson.annotations.Since": Since since = (Since) annotation; fieldMapper.since = since.value(); break; case "com.google.gson.annotations.Until": Until until = (Until) annotation; fieldMapper.until = until.value(); break; case "com.google.gson.annotations.SerializedName": SerializedName serializedName = (SerializedName) annotation; String[] alternates = serializedName.alternate(); if (alternates != null && alternates.length > 0) { for (String alternate : alternates) { names.add(alternate); } } break; case "com.fasterxml.jackson.annotation.JsonInclude": if (fieldMapper.defaultType == JSON_INCLUDE.NONE) { JsonInclude jsonInclude = (JsonInclude) annotation; switch (jsonInclude.content()) { case ALWAYS: fieldMapper.defaultType = JSON_INCLUDE.ALWAYS; break; case NON_NULL: fieldMapper.defaultType = JSON_INCLUDE.NON_NULL; break; case NON_ABSENT: fieldMapper.defaultType = JSON_INCLUDE.NON_NULL; break; case NON_EMPTY: fieldMapper.defaultType = JSON_INCLUDE.NON_EMPTY; break; case NON_DEFAULT: fieldMapper.defaultType = JSON_INCLUDE.NON_DEFAULT; break; case USE_DEFAULTS: fieldMapper.defaultType = JSON_INCLUDE.DEFAULT; break; } } break; case "com.fasterxml.jackson.annotation.JsonRawValue": if (((JsonRawValue) annotation).value()) { fieldMapper.jsonRawValue = true; } break; case "org.codehaus.jackson.annotate.JsonRawValue": if (((org.codehaus.jackson.annotate.JsonRawValue) annotation).value()) { fieldMapper.jsonRawValue = true; } break; case "org.junit.Ignore": fieldMapper.ignore = true; break; case "javax.persistence.Enumerated": fieldMapper.enumType = ((Enumerated) annotation).value(); break; case "javax.validation.constraints.NotNull": fieldMapper.required = true; break; case "com.fasterxml.jackson.annotation.JsonProperty": JsonProperty jsonProperty = (JsonProperty) annotation; Access access = jsonProperty.access(); if (access == Access.READ_ONLY) { fieldMapper.ignore = true; } if (jsonProperty.required()) { fieldMapper.required = true; } if (fieldMapper.defaultValue == null) { fieldMapper.defaultValue = jsonProperty.defaultValue(); } break; case "javax.validation.constraints.Size": Size size = (Size) annotation; if (size.min() > 0) { fieldMapper.min = (long) size.min(); } if (size.max() < Integer.MAX_VALUE) { fieldMapper.max = (long) size.max(); } break; case "javax.persistence.Column": Column column = (Column) annotation; if (column.length() != 255) { fieldMapper.length = column.length(); } if (column.scale() > 0) { fieldMapper.scale = column.scale(); } if (column.precision() > 0) { fieldMapper.precision = column.precision(); } if (!column.nullable()) { fieldMapper.required = true; } break; } String fname = ObjectUtil.getName(annotation); if (!StringUtil.isEmpty(fname)) { names.add(fname); } } } if (exposed && !exposexists) { fieldMapper.ignore = true; } // 10. Apply annotations from Oson if (fieldMapperAnnotation != null) { fieldMapper = overwriteBy(fieldMapper, fieldMapperAnnotation, classMapper); } } if (ignored) { nameKeys.remove(name); nameKeys.remove(fieldMapper.json); setters.remove(lcfieldName); if (exposed) { setNull(f, obj); } continue; } // 11. Apply Java configuration for this particular field if (javaFieldMapper != null && javaFieldMapper.isDeserializing()) { fieldMapper = overwriteBy(fieldMapper, javaFieldMapper); } if (fieldMapper.ignore != null && fieldMapper.ignore) { if (setter != null) { setters.remove(lcfieldName); } nameKeys.remove(name); nameKeys.remove(fieldMapper.json); if (exposed) { setNull(f, obj); } continue; } // in the ignored list if (ObjectUtil.inSet(name, classMapper.jsonIgnoreProperties)) { setters.remove(lcfieldName); nameKeys.remove(name); continue; } if (fieldMapper.jsonAnySetter != null && fieldMapper.jsonAnySetter && setter != null) { setters.remove(lcfieldName); otherMethods.put(lcfieldName, setter); continue; } if (fieldMapper.useField != null && !fieldMapper.useField) { // both should not be used, just like ignore if (fieldMapper.useAttribute != null && !fieldMapper.useAttribute) { getters.remove(lcfieldName); } continue; } if (fieldMapper.since != null && fieldMapper.since > getVersion()) { if (setter != null) { setters.remove(lcfieldName); } continue; } else if (fieldMapper.until != null && fieldMapper.until <= getVersion()) { if (setter != null) { setters.remove(lcfieldName); } continue; } // get value for name in map Object value = null; boolean jnameFixed = false; String json = fieldMapper.json; int size = nameKeys.size(); if (json == null) { if (setter != null) { setters.remove(lcfieldName); } continue; } else if (!json.equals(name)) { name = json; value = getMapValue(map, name, nameKeys); jnameFixed = true; } if (!jnameFixed) { for (String jsoname : names) { if (!name.equals(jsoname) && !StringUtil.isEmpty(jsoname)) { name = jsoname; value = getMapValue(map, name, nameKeys); if (value != null) { jnameFixed = true; break; } } } } if (!jnameFixed) { value = getMapValue(map, name, nameKeys); jnameFixed = true; } fieldMapper.java = fieldName; fieldMapper.json = name; // either not null, or a null value exists in the value map if (value != null || size == nameKeys.size() + 1) { Object oldValue = value; FieldData fieldData = new FieldData(obj, f, value, returnType, true, fieldMapper, objectDTO.level, objectDTO.set); fieldData.setter = setter; Class fieldType = guessComponentType(fieldData); value = json2Object(fieldData); if (StringUtil.isNull(value)) { if (classMapper.defaultType == JSON_INCLUDE.NON_NULL || classMapper.defaultType == JSON_INCLUDE.NON_EMPTY || classMapper.defaultType == JSON_INCLUDE.NON_DEFAULT) { continue; } } else if (StringUtil.isEmpty(value)) { if (classMapper.defaultType == JSON_INCLUDE.NON_EMPTY || classMapper.defaultType == JSON_INCLUDE.NON_DEFAULT) { continue; } } else if (DefaultValue.isDefault(value, returnType)) { if (classMapper.defaultType == JSON_INCLUDE.NON_DEFAULT) { continue; } } try { if (value == null && oldValue != null && oldValue.equals(f.get(obj) + "")) { // keep original value } else { f.set(obj, value); } } catch (IllegalAccessException | IllegalArgumentException ex) { //ex.printStackTrace(); if (setter != null) { ObjectUtil.setMethodValue(obj, setter, value); } } } setters.remove(lcfieldName); nameKeys.remove(name); } for (Entry<String, Method> entry : setters.entrySet()) { String lcfieldName = entry.getKey(); Method setter = entry.getValue(); setter.setAccessible(true); String name = setter.getName(); if (name != null && name.length() > 3 && name.substring(0, 3).equals("set") && name.substring(3).equalsIgnoreCase(lcfieldName)) { name = StringUtil.uncapitalize(name.substring(3)); } // just use field name, even it might not be a field String fieldName = name; if (ignoreModifiers(setter.getModifiers(), classMapper.includeFieldsWithModifiers)) { nameKeys.remove(name); continue; } if (Modifier.isFinal(setter.getModifiers()) && Modifier.isStatic(setter.getModifiers())) { nameKeys.remove(name); continue; } // 6. Create a blank field mapper instance FieldMapper fieldMapper = new FieldMapper(name, name, valueType); Class returnType = null; Class[] types = setter.getParameterTypes(); if (types != null && types.length > 0) { returnType = types[0]; } // not a proper setter if (returnType == null) { continue; } // 7. get the class mapper of returnType ClassMapper fieldClassMapper = getClassMapper(returnType); // 8. Classify this field mapper with returnType fieldMapper = classifyFieldMapper(fieldMapper, fieldClassMapper); // 9. Classify this field mapper with enclosing class type fieldMapper = classifyFieldMapper(fieldMapper, classMapper); FieldMapper javaFieldMapper = getFieldMapper(name, null, valueType); boolean ignored = false; Method getter = getters.get(lcfieldName); Set<String> names = new HashSet<>(); if (annotationSupport) { annotations = setter.getDeclaredAnnotations(); // no annotations, then try get method if ((annotations == null || annotations.length == 0) && getter != null) { annotations = getter.getDeclaredAnnotations(); } ca.oson.json.annotation.FieldMapper fieldMapperAnnotation = null; for (Annotation annotation : annotations) { if (ignoreField(annotation, classMapper.ignoreFieldsWithAnnotations)) { ignored = true; break; } else if (annotation instanceof ca.oson.json.annotation.FieldMapper) { fieldMapperAnnotation = (ca.oson.json.annotation.FieldMapper) annotation; if (!(fieldMapperAnnotation.serialize() == BOOLEAN.BOTH || fieldMapperAnnotation.serialize() == BOOLEAN.FALSE)) { fieldMapperAnnotation = null; } } else if (annotation instanceof ca.oson.json.annotation.FieldMappers) { ca.oson.json.annotation.FieldMappers fieldMapperAnnotations = (ca.oson.json.annotation.FieldMappers) annotation; for (ca.oson.json.annotation.FieldMapper ann : fieldMapperAnnotations.value()) { if (ann.serialize() == BOOLEAN.BOTH || ann.serialize() == BOOLEAN.FALSE) { fieldMapperAnnotation = ann; // break; } } } else { // to improve performance, using swith on string switch (annotation.annotationType().getName()) { case "com.fasterxml.jackson.annotation.JsonAnySetter": case "org.codehaus.jackson.annotate.JsonAnySetter": fieldMapper.jsonAnySetter = true; break; case "javax.persistence.Transient": fieldMapper.ignore = true; break; case "com.fasterxml.jackson.annotation.JsonIgnore": case "org.codehaus.jackson.annotate.JsonIgnore": fieldMapper.ignore = true; break; case "com.fasterxml.jackson.annotation.JsonIgnoreProperties": JsonIgnoreProperties jsonIgnoreProperties = (JsonIgnoreProperties) annotation; if (!jsonIgnoreProperties.allowSetters()) { fieldMapper.ignore = true; } else { fieldMapper.ignore = false; classMapper.jsonIgnoreProperties.remove(name); } break; case "com.google.gson.annotations.Expose": Expose expose = (Expose) annotation; if (!expose.deserialize()) { fieldMapper.ignore = true; } break; case "com.google.gson.annotations.Since": Since since = (Since) annotation; fieldMapper.since = since.value(); break; case "com.google.gson.annotations.Until": Until until = (Until) annotation; fieldMapper.until = until.value(); break; case "com.fasterxml.jackson.annotation.JsonInclude": if (fieldMapper.defaultType == JSON_INCLUDE.NONE) { JsonInclude jsonInclude = (JsonInclude) annotation; switch (jsonInclude.content()) { case ALWAYS: fieldMapper.defaultType = JSON_INCLUDE.ALWAYS; break; case NON_NULL: fieldMapper.defaultType = JSON_INCLUDE.NON_NULL; break; case NON_ABSENT: fieldMapper.defaultType = JSON_INCLUDE.NON_NULL; break; case NON_EMPTY: fieldMapper.defaultType = JSON_INCLUDE.NON_EMPTY; break; case NON_DEFAULT: fieldMapper.defaultType = JSON_INCLUDE.NON_DEFAULT; break; case USE_DEFAULTS: fieldMapper.defaultType = JSON_INCLUDE.DEFAULT; break; } } break; case "com.fasterxml.jackson.annotation.JsonRawValue": if (((JsonRawValue) annotation).value()) { fieldMapper.jsonRawValue = true; } break; case "org.codehaus.jackson.annotate.JsonRawValue": if (((org.codehaus.jackson.annotate.JsonRawValue) annotation).value()) { fieldMapper.jsonRawValue = true; } break; case "org.junit.Ignore": fieldMapper.ignore = true; break; case "javax.persistence.Enumerated": fieldMapper.enumType = ((Enumerated) annotation).value(); break; case "javax.validation.constraints.NotNull": fieldMapper.required = true; break; case "com.fasterxml.jackson.annotation.JsonProperty": JsonProperty jsonProperty = (JsonProperty) annotation; Access access = jsonProperty.access(); if (access == Access.READ_ONLY) { fieldMapper.ignore = true; } if (jsonProperty.required()) { fieldMapper.required = true; } if (fieldMapper.defaultValue == null) { fieldMapper.defaultValue = jsonProperty.defaultValue(); } break; case "javax.validation.constraints.Size": Size size = (Size) annotation; if (size.min() > 0) { fieldMapper.min = (long) size.min(); } if (size.max() < Integer.MAX_VALUE) { fieldMapper.max = (long) size.max(); } break; case "javax.persistence.Column": Column column = (Column) annotation; if (column.length() != 255) { fieldMapper.length = column.length(); } if (column.scale() > 0) { fieldMapper.scale = column.scale(); } if (column.precision() > 0) { fieldMapper.precision = column.precision(); } if (!column.nullable()) { fieldMapper.required = true; } break; } String fname = ObjectUtil.getName(annotation); if (fname != null) { names.add(fname); } } } // 10. Apply annotations from Oson if (fieldMapperAnnotation != null) { fieldMapper = overwriteBy(fieldMapper, fieldMapperAnnotation, classMapper); } } if (ignored) { nameKeys.remove(name); nameKeys.remove(fieldMapper.json); continue; } // 11. Apply Java configuration for this particular field if (javaFieldMapper != null && javaFieldMapper.isDeserializing()) { fieldMapper = overwriteBy(fieldMapper, javaFieldMapper); } if (fieldMapper.ignore != null && fieldMapper.ignore) { nameKeys.remove(name); nameKeys.remove(fieldMapper.json); continue; } // in the ignored list if (ObjectUtil.inSet(name, classMapper.jsonIgnoreProperties)) { nameKeys.remove(name); continue; } if (fieldMapper.useAttribute != null && !fieldMapper.useAttribute) { nameKeys.remove(name); nameKeys.remove(fieldMapper.json); continue; } if (fieldMapper.jsonAnySetter != null && fieldMapper.jsonAnySetter && setter != null) { setters.remove(lcfieldName); otherMethods.put(lcfieldName, setter); continue; } if (fieldMapper.since != null && fieldMapper.since > getVersion()) { nameKeys.remove(name); nameKeys.remove(fieldMapper.json); continue; } else if (fieldMapper.until != null && fieldMapper.until <= getVersion()) { nameKeys.remove(name); nameKeys.remove(fieldMapper.json); continue; } // get value for name in map Object value = null; boolean jnameFixed = false; String json = fieldMapper.json; if (json == null) { continue; } else if (!json.equals(name)) { name = json; value = getMapValue(map, name, nameKeys); jnameFixed = true; } if (!jnameFixed) { for (String jsoname : names) { if (!name.equals(jsoname) && !StringUtil.isEmpty(jsoname)) { name = jsoname; value = getMapValue(map, name, nameKeys); jnameFixed = true; break; } } } if (!jnameFixed) { value = getMapValue(map, name, nameKeys); jnameFixed = true; } fieldMapper.java = fieldName; fieldMapper.json = name; if (value != null) { FieldData fieldData = new FieldData(obj, null, value, returnType, true, fieldMapper, objectDTO.level, objectDTO.set); fieldData.setter = setter; Class fieldType = guessComponentType(fieldData); value = json2Object(fieldData); if (StringUtil.isNull(value)) { if (classMapper.defaultType == JSON_INCLUDE.NON_NULL || classMapper.defaultType == JSON_INCLUDE.NON_EMPTY || classMapper.defaultType == JSON_INCLUDE.NON_DEFAULT) { continue; } } else if (StringUtil.isEmpty(value)) { if (classMapper.defaultType == JSON_INCLUDE.NON_EMPTY || classMapper.defaultType == JSON_INCLUDE.NON_DEFAULT) { continue; } } else if (DefaultValue.isDefault(value, returnType)) { if (classMapper.defaultType == JSON_INCLUDE.NON_DEFAULT) { continue; } } ObjectUtil.setMethodValue(obj, setter, value); nameKeys.remove(name); } } if (annotationSupport) { //@JsonAnySetter if (nameKeys.size() > 0) { for (Entry<String, Method> entry : otherMethods.entrySet()) { Method method = entry.getValue(); if (ignoreModifiers(method.getModifiers(), classMapper.includeFieldsWithModifiers)) { continue; } if (method.isAnnotationPresent(JsonAnySetter.class)) { if (ignoreField(JsonAnySetter.class, classMapper.ignoreFieldsWithAnnotations)) { continue; } jsonAnySetterMethod = method; } else if (method.isAnnotationPresent(org.codehaus.jackson.annotate.JsonAnySetter.class)) { if (ignoreField(org.codehaus.jackson.annotate.JsonAnySetter.class, classMapper.ignoreFieldsWithAnnotations)) { continue; } jsonAnySetterMethod = method; } else if (method.isAnnotationPresent(ca.oson.json.annotation.FieldMapper.class)) { ca.oson.json.annotation.FieldMapper annotation = (ca.oson.json.annotation.FieldMapper) method .getAnnotation(ca.oson.json.annotation.FieldMapper.class); if (annotation.jsonAnySetter() == BOOLEAN.TRUE) { jsonAnySetterMethod = method; break; } } } } } if (jsonAnySetterMethod != null) { Parameter[] parameters = jsonAnySetterMethod.getParameters(); if (parameters != null && parameters.length == 2) { for (String name : nameKeys) { Object value = map.get(name); // json to java, check if this name is allowed or changed String java = json2Java(name); if (value != null && !StringUtil.isEmpty(java)) { ObjectUtil.setMethodValue(obj, jsonAnySetterMethod, java, value); } } } } return obj; // | InvocationTargetException } catch (IllegalArgumentException e) { e.printStackTrace(); } return null; }