List of usage examples for java.lang Class getModifiers
@HotSpotIntrinsicCandidate public native int getModifiers();
From source file:org.apache.openjpa.kernel.BrokerImpl.java
public Object newObjectId(Class<?> cls, Object val) { if (val == null) return null; beginOperation(false);//w w w. j av a2s . com try { ClassMetaData meta = _repo.getMetaData(cls, _loader, true); switch (meta.getIdentityType()) { case ClassMetaData.ID_DATASTORE: // delegate to store manager for datastore ids if (val instanceof String && ((String) val).startsWith(StateManagerId.STRING_PREFIX)) return new StateManagerId((String) val); return _store.newDataStoreId(val, meta); case ClassMetaData.ID_APPLICATION: if (ImplHelper.isAssignable(meta.getObjectIdType(), val.getClass())) { if (!meta.isOpenJPAIdentity() && meta.isObjectIdTypeShared()) return new ObjectId(cls, val); return val; } // stringified app id? if (val instanceof String && !_conf.getCompatibilityInstance().getStrictIdentityValues() && !Modifier.isAbstract(cls.getModifiers())) return PCRegistry.newObjectId(cls, (String) val); Object[] arr = (val instanceof Object[]) ? (Object[]) val : new Object[] { val }; return ApplicationIds.fromPKValues(arr, meta); default: throw new UserException(_loc.get("meta-unknownid", cls)); } } catch (IllegalArgumentException iae) { // OPENJPA-365 throw new UserException(_loc.get("bad-id-value", val, val.getClass().getName(), cls)).setCause(iae); } catch (OpenJPAException ke) { throw ke; } catch (ClassCastException cce) { throw new UserException(_loc.get("bad-id-value", val, val.getClass().getName(), cls)).setCause(cce); } catch (RuntimeException re) { throw new GeneralException(re); } finally { endOperation(); } }
From source file:org.openTwoFactor.client.util.TwoFactorClientCommonUtils.java
/** * Construct a class//from www . jav a 2s . c o m * @param <T> template type * @param theClass * @return the instance */ public static <T> T newInstance(Class<T> theClass) { try { return theClass.newInstance(); } catch (Throwable e) { if (theClass != null && Modifier.isAbstract(theClass.getModifiers())) { throw new RuntimeException("Problem with class: " + theClass + ", maybe because it is abstract!", e); } throw new RuntimeException("Problem with class: " + theClass, e); } }
From source file:org.openTwoFactor.client.util.TwoFactorClientCommonUtils.java
/** * Construct a class/* w w w.j a v a2s . c om*/ * @param <T> template type * @param theClass * @param allowPrivateConstructor true if should allow private constructors * @return the instance */ public static <T> T newInstance(Class<T> theClass, boolean allowPrivateConstructor) { if (!allowPrivateConstructor) { return newInstance(theClass); } try { Constructor<?>[] constructorArray = theClass.getDeclaredConstructors(); for (Constructor<?> constructor : constructorArray) { if (constructor.getGenericParameterTypes().length == 0) { if (allowPrivateConstructor) { constructor.setAccessible(true); } return (T) constructor.newInstance(); } } //why cant we find a constructor??? throw new RuntimeException("Why cant we find a constructor for class: " + theClass); } catch (Throwable e) { if (theClass != null && Modifier.isAbstract(theClass.getModifiers())) { throw new RuntimeException("Problem with class: " + theClass + ", maybe because it is abstract!", e); } throw new RuntimeException("Problem with class: " + theClass, e); } }
From source file:ca.oson.json.Oson.java
private <E, R> Class guessComponentType(FieldData newFieldData) { boolean json2Java = newFieldData.json2Java; if (!json2Java) { return newFieldData.returnType; } else {/*from w ww . j a va 2 s. c o m*/ E obj = (E) newFieldData.valueToProcess; Class returnType = newFieldData.returnType; Class itemType = null; if (obj != null) { itemType = obj.getClass(); } if (newFieldData.componentType != null) { Class classType = newFieldData.componentType.getClassType(); Class cls = newFieldData.componentType.getMainComponentType(); if (cls != null && (ObjectUtil.isBasicDataType(cls) || ObjectUtil.isSameDataType(classType, returnType))) { return cls; } } String returnTypeName = null; if (returnType != null) { returnTypeName = returnType.getName(); } String itemTypeName = null; if (itemType != null) { itemTypeName = itemType.getName(); } int returnTypeCount = 0; int itemTypeCount = 0; String toGenericString = null; Class fieldType = null; if (newFieldData.field != null) { toGenericString = newFieldData.field.toGenericString(); Class[] fieldTypes = ObjectUtil.getComponentTypes(toGenericString); if (fieldTypes != null && fieldTypes.length > 0) { if (fieldTypes.length == 1) { fieldType = fieldTypes[0]; } else { fieldType = fieldTypes[0]; if (newFieldData.isMapValue) { fieldType = fieldTypes[1]; } else { fieldType = fieldTypes[0]; } } } if (returnTypeName != null && toGenericString.indexOf(returnTypeName) > -1) { returnTypeCount++; } if (itemTypeName != null && toGenericString.indexOf(itemTypeName) > -1) { itemTypeCount++; } } if (fieldType == null && returnType != null) { toGenericString = returnType.toGenericString(); fieldType = ObjectUtil.getComponentType(toGenericString); if (returnTypeName != null && toGenericString.indexOf(returnTypeName) > -1) { returnTypeCount++; } if (itemTypeName != null && toGenericString.indexOf(itemTypeName) > -1) { itemTypeCount++; } } if (fieldType == null && newFieldData.setter != null) { toGenericString = newFieldData.setter.toGenericString(); fieldType = ObjectUtil.getComponentType(toGenericString); if (returnTypeName != null && toGenericString.indexOf(returnTypeName) > -1) { returnTypeCount++; } if (itemTypeName != null && toGenericString.indexOf(itemTypeName) > -1) { itemTypeCount++; } if (fieldType == null) { Class[] types = newFieldData.setter.getParameterTypes(); if (types != null && types.length > 0) { toGenericString = types[0].toGenericString(); fieldType = ObjectUtil.getComponentType(toGenericString); if (returnTypeName != null && toGenericString.indexOf(returnTypeName) > -1) { returnTypeCount++; } if (itemTypeName != null && toGenericString.indexOf(itemTypeName) > -1) { itemTypeCount++; } } } } ComponentType type = getComponentType(); if (type == null) { Class enclosingtype = newFieldData.getEnclosingtype(); if (enclosingtype != null) { type = cachedComponentTypes(enclosingtype); } } int level = newFieldData.level; if (fieldType != null) { if (returnTypeCount < itemTypeCount) { newFieldData.returnType = itemType; } if (type == null) { type = new ComponentType(newFieldData.returnType, fieldType); type = cachedComponentTypes(type); } else { type.add(fieldType); } if (newFieldData.returnType == Object.class) { newFieldData.returnType = fieldType; } return fieldType; } if (returnType != null) { Class comptype = returnType.getComponentType(); if (comptype != null && !comptype.isInterface() && !Modifier.isAbstract(comptype.getModifiers())) { return comptype; } } if ((returnType != null && Map.class.isAssignableFrom(returnType)) || (itemType != null && Map.class.isAssignableFrom(itemType))) { String className = ((Map<String, String>) obj).get(getJsonClassType()); if (className != null && className.length() > 0) { try { // figure out obj's class fieldType = Class.forName(className); if (type == null) { if (newFieldData.returnType != fieldType) { type = new ComponentType(newFieldData.returnType, fieldType); type = cachedComponentTypes(type); } } else { type.add(fieldType); } newFieldData.returnType = fieldType; return fieldType; } catch (ClassNotFoundException e) { // e.printStackTrace(); } } if (returnTypeCount > 0 && !Map.class.isAssignableFrom(returnType) && !Collection.class.isAssignableFrom(returnType) && returnType != Optional.class && returnType != Object.class && !returnType.isArray()) { if (type != null) { type.add(returnType); } return returnType; } if (type != null) { ComponentType componentType = type.getComponentType(); while (componentType != null && componentType.getComponentType() != null && level > 1) { componentType = componentType.getComponentType(); level--; } if (level == 1 && componentType != null && componentType.getClassType() != null) { return componentType.getClassType(); } Class[] ctypes = type.getComponentClassType(); float MIN_MAX_COUNT = 20.0f; if (ctypes != null && ctypes.length > 0) { int length = ctypes.length; Map<String, R> map = (Map) obj; Map<String, Class> lnames = new HashMap<>(); //names.stream().map(name -> name.toLowerCase()).collect(Collectors.toSet()); for (String name : map.keySet()) { Object value = map.get(name); if (value != null) { lnames.put(name.toLowerCase(), map.get(name).getClass()); } } int maxIdx = -1; float maxCount = 0.0f; for (int i = 0; i < length; i++) { Class ctype = ctypes[i]; Field[] fields = getFields(ctype); if (fields != null && fields.length > 0) { int count = 0; for (Field field : fields) { String name = field.getName().toLowerCase(); if (lnames.containsKey(name)) { count++; Class ftype = field.getType(); Class mtype = lnames.get(name); if (ObjectUtil.isSameDataType(ftype, mtype)) { count++; } } } float currentCount = count * 100.0f / fields.length; if (currentCount > maxCount) { maxCount = currentCount; maxIdx = i; } else if (maxIdx == -1 && ctype.isAssignableFrom(itemType)) { maxIdx = i; } } } if (maxIdx > -1) { newFieldData.returnType = ctypes[maxIdx]; return ctypes[maxIdx]; } Set<Class> processed = new HashSet(Arrays.asList(ctypes)); // now try to locate it in all cachedComponentTypes for (Entry<Class, ComponentType> entry : cachedComponentTypes.entrySet()) { Class myMasterClass = entry.getKey(); if (myMasterClass != this.masterClass && entry.getValue() != null) { ctypes = entry.getValue().getComponentClassType(); if (ctypes != null) { length = ctypes.length; maxCount = 0.0f; for (int i = 0; i < length; i++) { Class ctype = ctypes[i]; if (!processed.contains(ctype)) { Field[] fields = getFields(ctype); if (fields != null && fields.length > 0) { int count = 0; for (Field field : fields) { String name = field.getName(); if (name != null) { name = name.toLowerCase(); if (lnames.containsKey(name)) { count++; Class ftype = field.getType(); Class mtype = lnames.get(name); if (ObjectUtil.isSameType(ftype, mtype)) { count++; } } } } float currentCount = count * 100.0f / fields.length; if (currentCount > maxCount) { maxCount = currentCount; maxIdx = i; } // else if (maxIdx == -1 && ctype.isAssignableFrom(itemType)) { // maxIdx = i; // } } } } if (maxIdx > -1 && maxCount > MIN_MAX_COUNT) { newFieldData.returnType = ctypes[maxIdx]; type.add(ctypes[maxIdx]); return ctypes[maxIdx]; } processed.addAll(Arrays.asList(ctypes)); } } } if (ctypes != null && ctypes.length == 1) { return ctypes[0]; } } } } else if ((returnType != null && (Collection.class.isAssignableFrom(returnType) || returnType.isArray())) || (itemType != null && (Collection.class.isAssignableFrom(itemType) || itemType.isArray()))) { // && ComponentType.class.isAssignableFrom(erasedType.getClass()) if (type != null) { ComponentType componentType = type.getComponentType(); while (componentType != null && componentType.getComponentType() != null && level > 1) { componentType = componentType.getComponentType(); level--; } if (level == 1 && componentType != null && componentType.getClassType() != null) { return componentType.getClassType(); } Class[] ctypes = type.getComponentClassType(); if (ctypes != null && ctypes.length > 0) { if (ctypes.length == 1) { Class cmptype = ctypes[0].getComponentType(); if (cmptype != null && (cmptype.isArray() || Collection.class.isAssignableFrom(cmptype))) { type.add(cmptype); } //if (!ObjectUtil.isBasicDataType(ctypes[0])) { return ctypes[0]; //} } int length = ctypes.length; int depth = CollectionArrayTypeGuesser.getDepth(obj); Class baseType = CollectionArrayTypeGuesser.getBaseType(obj); Class possible = null; for (int i = 0; i < length; i++) { Class ctype = ctypes[i]; if (ctype.isArray() || Collection.class.isAssignableFrom(ctype)) { //Class compType = CollectionArrayTypeGuesser.guessElementType(collection, ctype, getJsonClassType()); int typedepth = CollectionArrayTypeGuesser.getDepth(ctype); Class cbaseType = CollectionArrayTypeGuesser.getBaseType(ctype); if (depth == typedepth) { if (ObjectUtil.isSameType(baseType, cbaseType)) { Class cmptype = ctype.getComponentType(); if (cmptype.isArray() || Collection.class.isAssignableFrom(cmptype)) { type.add(cmptype); } return ctype; } else if (itemType.isAssignableFrom(ctype) || ctype.isAssignableFrom(itemType)) { possible = ctype; } } } } if (possible != null) { return possible; } } } } // else if (StringUtil.isNumeric(obj.toString())) { // if (obj.toString().contains(".")) { // return Double.class; // } else { // return Integer.class; // } // } if (type != null && type.getComponentType() != null) { Class classType = type.getComponentType().getClassType(); if (classType != null && ObjectUtil.isSameDataType(classType, itemType)) { return classType; } } return itemType; } }
From source file:com.github.wshackle.java4cpp.J4CppMain.java
public static void main(String[] args) throws IOException, ClassNotFoundException { main_completed = false;/*w w w .j a va 2 s . co m*/ Options options = new Options(); options.addOption(Option.builder("?").desc("Print this message").longOpt("help").build()); options.addOption(Option.builder("n").hasArg().desc("C++ namespace for newly generated classes.") .longOpt("namespace").build()); options.addOption( Option.builder("c").hasArgs().desc("Single Java class to extract.").longOpt("classes").build()); options.addOption( Option.builder("p").hasArgs().desc("Java Package prefix to extract").longOpt("packages").build()); options.addOption(Option.builder("o").hasArg().desc("Output C++ source file.").longOpt("output").build()); options.addOption(Option.builder("j").hasArg().desc("Input jar file").longOpt("jar").build()); options.addOption(Option.builder("h").hasArg().desc("Output C++ header file.").longOpt("header").build()); options.addOption(Option.builder("l").hasArg() .desc("Maximum limit on classes to extract from jars.[default=200]").longOpt("limit").build()); options.addOption(Option.builder("v").desc("enable verbose output").longOpt("verbose").build()); options.addOption(Option.builder().hasArg().desc("Classes per output file.[default=10]") .longOpt(CLASSESPEROUTPUT).build()); options.addOption(Option.builder().hasArgs().desc( "Comma seperated list of nativeclass=javaclass native where nativeclass will be generated as an extension/implementation of the java class.") .longOpt("natives").build()); options.addOption(Option.builder().hasArg() .desc("library name for System.loadLibrary(...) for native extension classes") .longOpt("loadlibname").build()); String output = null; String header = null; String jar = null; Set<String> classnamesToFind = null; Set<String> packageprefixes = null; String loadlibname = null; Map<String, String> nativesNameMap = null; Map<String, Class> nativesClassMap = null; int limit = DEFAULT_LIMIT; int classes_per_file = 10; List<Class> classes = new ArrayList<>(); String limitstring = Integer.toString(limit); try { // parse the command line arguments System.out.println("args = " + Arrays.toString(args)); CommandLine line = new DefaultParser().parse(options, args); loadlibname = line.getOptionValue("loadlibname"); verbose = line.hasOption("verbose"); if (line.hasOption(CLASSESPEROUTPUT)) { String cpoStr = line.getOptionValue(CLASSESPEROUTPUT); try { int cpoI = Integer.valueOf(cpoStr); classes_per_file = cpoI; } catch (Exception e) { System.err.println("Option for " + CLASSESPEROUTPUT + "=\"" + cpoStr + "\""); printHelpAndExit(options, args); } } if (line.hasOption("natives")) { String natives[] = line.getOptionValues("natives"); if (verbose) { System.out.println("natives = " + Arrays.toString(natives)); } nativesNameMap = new HashMap<>(); nativesClassMap = new HashMap<>(); for (int i = 0; i < natives.length; i++) { int eq_index = natives[i].indexOf('='); String nativeClassName = natives[i].substring(0, eq_index).trim(); String javaClassName = natives[i].substring(eq_index + 1).trim(); Class javaClass = null; try { javaClass = Class.forName(javaClassName); } catch (ClassNotFoundException e) { //e.printStackTrace(); System.err.println("Class for " + javaClassName + " not found. (It may be found later in jar if specified.)"); } nativesNameMap.put(javaClassName, nativeClassName); if (javaClass != null) { nativesClassMap.put(nativeClassName, javaClass); if (!classes.contains(javaClass)) { classes.add(javaClass); } } } } // // validate that block-size has been set // if (line.hasOption("block-size")) { // // print the value of block-size // if(verbose) System.out.println(line.getOptionValue("block-size")); // } jar = line.getOptionValue("jar", jar); if (verbose) { System.out.println("jar = " + jar); } if (null != jar) { if (jar.startsWith("~/")) { jar = new File(new File(getHomeDir()), jar.substring(2)).getCanonicalPath(); } if (jar.startsWith("./")) { jar = new File(new File(getCurrentDir()), jar.substring(2)).getCanonicalPath(); } if (jar.startsWith("../")) { jar = new File(new File(getCurrentDir()).getParentFile(), jar.substring(3)).getCanonicalPath(); } } if (line.hasOption("classes")) { classnamesToFind = new HashSet<String>(); String classStrings[] = line.getOptionValues("classes"); if (verbose) { System.out.println("classStrings = " + Arrays.toString(classStrings)); } classnamesToFind.addAll(Arrays.asList(classStrings)); if (verbose) { System.out.println("classnamesToFind = " + classnamesToFind); } } // if (!line.hasOption("namespace")) { // if (classname != null && classname.length() > 0) { // namespace = classname.toLowerCase().replace(".", "_"); // } else if (jar != null && jar.length() > 0) { // int lastSep = jar.lastIndexOf(File.separator); // int start = Math.max(0, lastSep + 1); // int period = jar.indexOf('.', start + 1); // int end = Math.max(start + 1, period); // namespace = jar.substring(start, end).toLowerCase(); // namespace = namespace.replace(" ", "_"); // if (namespace.indexOf("-") > 0) { // namespace = namespace.substring(0, namespace.indexOf("-")); // } // } // } namespace = line.getOptionValue("namespace", namespace); if (verbose) { System.out.println("namespace = " + namespace); } if (null != namespace) { output = namespace + ".cpp"; } output = line.getOptionValue("output", output); if (verbose) { System.out.println("output = " + output); } if (null != output) { if (output.startsWith("~/")) { output = System.getProperty("user.home") + output.substring(1); } header = output.substring(0, output.lastIndexOf('.')) + ".h"; } else { output = "out.cpp"; } header = line.getOptionValue("header", header); if (verbose) { System.out.println("header = " + header); } if (null != header) { if (header.startsWith("~/")) { header = System.getProperty("user.home") + header.substring(1); } } else { header = "out.h"; } if (line.hasOption("packages")) { packageprefixes = new HashSet<String>(); packageprefixes.addAll(Arrays.asList(line.getOptionValues("packages"))); } if (line.hasOption("limit")) { limitstring = line.getOptionValue("limit", Integer.toString(DEFAULT_LIMIT)); limit = Integer.valueOf(limitstring); } if (line.hasOption("help")) { printHelpAndExit(options, args); } } catch (ParseException exp) { if (verbose) { System.out.println("Unexpected exception:" + exp.getMessage()); } printHelpAndExit(options, args); } Set<Class> excludedClasses = new HashSet<>(); Set<String> foundClassNames = new HashSet<>(); excludedClasses.add(Object.class); excludedClasses.add(String.class); excludedClasses.add(void.class); excludedClasses.add(Void.class); excludedClasses.add(Class.class); excludedClasses.add(Enum.class); Set<String> packagesSet = new TreeSet<>(); List<URL> urlsList = new ArrayList<>(); String cp = System.getProperty("java.class.path"); if (verbose) { System.out.println("System.getProperty(\"java.class.path\") = " + cp); } if (null != cp) { for (String cpe : cp.split(File.pathSeparator)) { if (verbose) { System.out.println("class path element = " + cpe); } File f = new File(cpe); if (f.isDirectory()) { urlsList.add(new URL("file:" + f.getCanonicalPath() + File.separator)); } else if (cpe.endsWith(".jar")) { urlsList.add(new URL("jar:file:" + f.getCanonicalPath() + "!/")); } } } cp = System.getenv("CLASSPATH"); if (verbose) { System.out.println("System.getenv(\"CLASSPATH\") = " + cp); } if (null != cp) { for (String cpe : cp.split(File.pathSeparator)) { if (verbose) { System.out.println("class path element = " + cpe); } File f = new File(cpe); if (f.isDirectory()) { urlsList.add(new URL("file:" + f.getCanonicalPath() + File.separator)); } else if (cpe.endsWith(".jar")) { urlsList.add(new URL("jar:file:" + f.getCanonicalPath() + "!/")); } } } if (verbose) { System.out.println("urlsList = " + urlsList); } if (null != jar && jar.length() > 0) { Path jarPath = FileSystems.getDefault().getPath(jar); ZipInputStream zip = new ZipInputStream(Files.newInputStream(jarPath, StandardOpenOption.READ)); URL jarUrl = new URL("jar:file:" + jarPath.toFile().getCanonicalPath() + "!/"); urlsList.add(jarUrl); URL[] urls = urlsList.toArray(new URL[urlsList.size()]); if (verbose) { System.out.println("urls = " + Arrays.toString(urls)); } URLClassLoader cl = URLClassLoader.newInstance(urls); for (ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry()) { // This ZipEntry represents a class. Now, what class does it represent? String entryName = entry.getName(); if (verbose) { System.out.println("entryName = " + entryName); } if (!entry.isDirectory() && entryName.endsWith(".class")) { if (entryName.indexOf('$') >= 0) { continue; } String classFileName = entry.getName().replace('/', '.'); String className = classFileName.substring(0, classFileName.length() - ".class".length()); if (classnamesToFind != null && classnamesToFind.size() > 0 && !classnamesToFind.contains(className)) { if (verbose) { System.out.println("skipping className=" + className + " because it does not found in=" + classnamesToFind); } continue; } try { Class clss = cl.loadClass(className); if (null != nativesClassMap && null != nativesNameMap && nativesNameMap.containsKey(className)) { nativesClassMap.put(nativesNameMap.get(className), clss); if (!classes.contains(clss)) { classes.add(clss); } } if (packageprefixes != null && packageprefixes.size() > 0) { if (null == clss.getPackage()) { continue; } final String pkgName = clss.getPackage().getName(); boolean matchFound = false; for (String prefix : packageprefixes) { if (pkgName.startsWith(prefix)) { matchFound = true; break; } } if (!matchFound) { continue; } } Package p = clss.getPackage(); if (null != p) { packagesSet.add(clss.getPackage().getName()); } if (!classes.contains(clss) && isAddableClass(clss, excludedClasses)) { if (null != classnamesToFind && classnamesToFind.contains(className) && !foundClassNames.contains(className)) { foundClassNames.add(className); if (verbose) { System.out.println("foundClassNames = " + foundClassNames); } } // if(verbose) System.out.println("clss = " + clss); classes.add(clss); // Class superClass = clss.getSuperclass(); // while (null != superClass // && !classes.contains(superClass) // && isAddableClass(superClass, excludedClasses)) { // classes.add(superClass); // superClass = superClass.getSuperclass(); // } } } catch (ClassNotFoundException | NoClassDefFoundError ex) { System.err.println( "Caught " + ex.getClass().getName() + ":" + ex.getMessage() + " for className=" + className + ", entryName=" + entryName + ", jarPath=" + jarPath); } } } } if (null != classnamesToFind) { if (verbose) { System.out.println("Checking classnames arguments"); } for (String classname : classnamesToFind) { if (verbose) { System.out.println("classname = " + classname); } if (foundClassNames.contains(classname)) { if (verbose) { System.out.println("foundClassNames.contains(" + classname + ")"); } continue; } try { if (classes.contains(Class.forName(classname))) { if (verbose) { System.out.println("Classes list already contains: " + classname); } continue; } } catch (Exception e) { } if (null != classname && classname.length() > 0) { urlsList.add(new URL("file://" + System.getProperty("user.dir") + "/")); URL[] urls = urlsList.toArray(new URL[urlsList.size()]); if (verbose) { System.out.println("urls = " + Arrays.toString(urls)); } URLClassLoader cl = URLClassLoader.newInstance(urls); Class c = null; try { c = cl.loadClass(classname); } catch (ClassNotFoundException e) { System.err.println("Class " + classname + " not found "); } if (verbose) { System.out.println("c = " + c); } if (null == c) { try { c = ClassLoader.getSystemClassLoader().loadClass(classname); } catch (ClassNotFoundException e) { if (verbose) { System.out.println("System ClassLoader failed to find " + classname); } } } if (null != c) { classes.add(c); } else { System.err.println("Class " + classname + " not found"); } } } if (verbose) { System.out.println("Finished checking classnames arguments"); } } if (classes == null || classes.size() < 1) { if (null == nativesClassMap || nativesClassMap.keySet().size() < 1) { System.err.println("No Classes specified or found."); System.exit(1); } } if (verbose) { System.out.println("Classes found = " + classes.size()); } if (classes.size() > limit) { System.err.println("limit=" + limit); System.err.println( "Too many classes please use -c or -p options to limit classes or -l to increase limit."); if (verbose) { System.out.println("packagesSet = " + packagesSet); } System.exit(1); } List<Class> newClasses = new ArrayList<Class>(); for (Class clss : classes) { Class superClass = clss.getSuperclass(); while (null != superClass && !classes.contains(superClass) && !newClasses.contains(superClass) && isAddableClass(superClass, excludedClasses)) { newClasses.add(superClass); superClass = superClass.getSuperclass(); } try { Field fa[] = clss.getDeclaredFields(); for (Field f : fa) { if (Modifier.isPublic(f.getModifiers())) { Class fClass = f.getType(); if (!classes.contains(fClass) && !newClasses.contains(fClass) && isAddableClass(fClass, excludedClasses)) { newClasses.add(fClass); } } } } catch (NoClassDefFoundError e) { e.printStackTrace(); } for (Method m : clss.getDeclaredMethods()) { if (m.isSynthetic()) { continue; } if (!Modifier.isPublic(m.getModifiers()) || Modifier.isAbstract(m.getModifiers())) { continue; } Class retType = m.getReturnType(); if (verbose) { System.out.println("Checking dependancies for Method = " + m); } if (!classes.contains(retType) && !newClasses.contains(retType) && isAddableClass(retType, excludedClasses)) { newClasses.add(retType); superClass = retType.getSuperclass(); while (null != superClass && !classes.contains(superClass) && !newClasses.contains(superClass) && isAddableClass(superClass, excludedClasses)) { newClasses.add(superClass); superClass = superClass.getSuperclass(); } } for (Class paramType : m.getParameterTypes()) { if (!classes.contains(paramType) && !newClasses.contains(paramType) && isAddableClass(paramType, excludedClasses)) { newClasses.add(paramType); superClass = paramType.getSuperclass(); while (null != superClass && !classes.contains(superClass) && !newClasses.contains(superClass) && !excludedClasses.contains(superClass)) { newClasses.add(superClass); superClass = superClass.getSuperclass(); } } } } } if (null != nativesClassMap) { for (Class clss : nativesClassMap.values()) { if (null != clss) { Class superClass = clss.getSuperclass(); while (null != superClass && !classes.contains(superClass) && !newClasses.contains(superClass) && !excludedClasses.contains(superClass)) { newClasses.add(superClass); superClass = superClass.getSuperclass(); } } } } if (verbose) { System.out.println("Dependency classes needed = " + newClasses.size()); } classes.addAll(newClasses); List<Class> newOrderClasses = new ArrayList<>(); for (Class clss : classes) { if (newOrderClasses.contains(clss)) { continue; } Class superClass = clss.getSuperclass(); Stack<Class> stack = new Stack<>(); while (null != superClass && !newOrderClasses.contains(superClass) && !superClass.equals(java.lang.Object.class)) { stack.push(superClass); superClass = superClass.getSuperclass(); } while (!stack.empty()) { newOrderClasses.add(stack.pop()); } newOrderClasses.add(clss); } classes = newOrderClasses; if (verbose) { System.out.println("Total number of classes = " + classes.size()); System.out.println("classes = " + classes); } String forward_header = header.substring(0, header.lastIndexOf('.')) + "_fwd.h"; Map<String, String> map = new HashMap<>(); map.put(JAR, jar != null ? jar : ""); map.put("%CLASSPATH_PREFIX%", getCurrentDir() + ((jar != null) ? (File.pathSeparator + ((new File(jar).getCanonicalPath()).replace("\\", "\\\\"))) : "")); map.put("%FORWARD_HEADER%", forward_header); map.put("%HEADER%", header); map.put("%PATH_SEPERATOR%", File.pathSeparator); String tabs = ""; String headerDefine = forward_header.substring(Math.max(0, forward_header.indexOf(File.separator))) .replace(".", "_"); map.put(HEADER_DEFINE, headerDefine); map.put(NAMESPACE, namespace); if (null != nativesClassMap) { for (Entry<String, Class> e : nativesClassMap.entrySet()) { final Class javaClass = e.getValue(); final String nativeClassName = e.getKey(); try (PrintWriter pw = new PrintWriter(new FileWriter(nativeClassName + ".java"))) { if (javaClass.isInterface()) { pw.println("public class " + nativeClassName + " implements " + javaClass.getCanonicalName() + ", AutoCloseable{"); } else { pw.println("public class " + nativeClassName + " extends " + javaClass.getCanonicalName() + " implements AutoCloseable{"); } if (null != loadlibname && loadlibname.length() > 0) { pw.println(TAB_STRING + "static {"); pw.println(TAB_STRING + TAB_STRING + "System.loadLibrary(\"" + loadlibname + "\");"); pw.println(TAB_STRING + "}"); pw.println(); } pw.println(TAB_STRING + "public " + nativeClassName + "() {"); pw.println(TAB_STRING + "}"); pw.println(); pw.println(TAB_STRING + "private long nativeAddress=0;"); pw.println(TAB_STRING + "private boolean nativeDeleteOnClose=false;"); pw.println(); pw.println(TAB_STRING + "protected " + nativeClassName + "(final long nativeAddress) {"); pw.println(TAB_STRING + TAB_STRING + "this.nativeAddress = nativeAddress;"); pw.println(TAB_STRING + "}"); pw.println(TAB_STRING + "private native void nativeDelete();"); pw.println(); pw.println(TAB_STRING + "@Override"); pw.println(TAB_STRING + "public synchronized void close() {"); // pw.println(TAB_STRING + TAB_STRING + "if(nativeAddress != 0 && nativeDeleteOnClose) {"); pw.println(TAB_STRING + TAB_STRING + "nativeDelete();"); // pw.println(TAB_STRING + TAB_STRING + "}"); // pw.println(TAB_STRING + TAB_STRING + "nativeAddress=0;"); // pw.println(TAB_STRING + TAB_STRING + "nativeDeleteOnClose=false;"); pw.println(TAB_STRING + "}"); pw.println(); pw.println(TAB_STRING + "protected void finalizer() {"); pw.println(TAB_STRING + TAB_STRING + "close();"); pw.println(TAB_STRING + "}"); pw.println(); Method ma[] = javaClass.getDeclaredMethods(); for (Method m : ma) { int modifiers = m.getModifiers(); if (Modifier.isAbstract(modifiers) && Modifier.isPublic(modifiers) && !Modifier.isStatic(modifiers) // && !m.isDefault() && !m.isSynthetic()) { pw.println(); pw.println(TAB_STRING + "@Override"); String params = ""; for (int i = 0; i < m.getParameterTypes().length; i++) { params += m.getParameterTypes()[i].getCanonicalName() + " param" + i; if (i < m.getParameterTypes().length - 1) { params += ","; } } pw.println(TAB_STRING + "native public " + m.getReturnType().getCanonicalName() + " " + m.getName() + "(" + params + ");"); // + IntStream.range(0, m.getParameterTypes().length) // .mapToObj(i -> m.getParameterTypes()[i].getCanonicalName() + " param" + i) // .collect(Collectors.joining(",")) + ");"); } } pw.println("}"); } } } try (PrintWriter pw = new PrintWriter(new FileWriter(forward_header))) { tabs = ""; processTemplate(pw, map, "header_fwd_template_start.h", tabs); Class lastClass = null; for (int class_index = 0; class_index < classes.size(); class_index++) { Class clss = classes.get(class_index); String clssOnlyName = getCppClassName(clss); tabs = openClassNamespace(clss, pw, tabs, lastClass); tabs += TAB_STRING; pw.println(tabs + "class " + clssOnlyName + ";"); tabs = tabs.substring(0, tabs.length() - 1); Class nextClass = (class_index < (classes.size() - 1)) ? classes.get(class_index + 1) : null; tabs = closeClassNamespace(clss, pw, tabs, nextClass); lastClass = clss; } processTemplate(pw, map, "header_fwd_template_end.h", tabs); } headerDefine = header.substring(Math.max(0, header.indexOf(File.separator))).replace(".", "_"); map.put(HEADER_DEFINE, headerDefine); map.put(NAMESPACE, namespace); if (classes_per_file < 1) { classes_per_file = classes.size(); } final int num_class_segments = (classes.size() > 1) ? ((classes.size() + classes_per_file - 1) / classes_per_file) : 1; String fmt = "%d"; if (num_class_segments > 10) { fmt = "%02d"; } if (num_class_segments > 100) { fmt = "%03d"; } String header_file_base = header; if (header_file_base.endsWith(".h")) { header_file_base = header_file_base.substring(0, header_file_base.length() - 2); } else if (header_file_base.endsWith(".hh")) { header_file_base = header_file_base.substring(0, header_file_base.length() - 3); } else if (header_file_base.endsWith(".hpp")) { header_file_base = header_file_base.substring(0, header_file_base.length() - 4); } try (PrintWriter pw = new PrintWriter(new FileWriter(header))) { tabs = ""; processTemplate(pw, map, HEADER_TEMPLATE_STARTH, tabs); for (int segment_index = 0; segment_index < num_class_segments; segment_index++) { String header_segment_file = header_file_base + String.format(fmt, segment_index) + ".h"; pw.println("#include \"" + header_segment_file + "\""); } if (null != nativesClassMap) { tabs = TAB_STRING; for (Entry<String, Class> e : nativesClassMap.entrySet()) { final Class javaClass = e.getValue(); final String nativeClassName = e.getKey(); pw.println(); pw.println(tabs + "class " + nativeClassName + "Context;"); pw.println(); map.put(CLASS_NAME, nativeClassName); map.put("%BASE_CLASS_FULL_NAME%", "::" + namespace + "::" + getModifiedClassName(javaClass).replace(".", "::")); map.put(OBJECT_CLASS_FULL_NAME, "::" + namespace + "::java::lang::Object"); processTemplate(pw, map, HEADER_CLASS_STARTH, tabs); tabs += TAB_STRING; pw.println(tabs + nativeClassName + "Context *context;"); pw.println(tabs + nativeClassName + "();"); pw.println(tabs + "~" + nativeClassName + "();"); Method methods[] = javaClass.getDeclaredMethods(); for (int j = 0; j < methods.length; j++) { Method method = methods[j]; int modifiers = method.getModifiers(); if (!Modifier.isPublic(modifiers)) { continue; } if (Modifier.isAbstract(modifiers) && Modifier.isPublic(modifiers) && !Modifier.isStatic(modifiers) // && !method.isDefault() && !method.isSynthetic()) { pw.println(tabs + getNativeMethodCppDeclaration(method, javaClass)); } } pw.println(tabs + "void initContext(" + nativeClassName + "Context *ctx,bool isref);"); pw.println(tabs + "void deleteContext();"); tabs = tabs.substring(TAB_STRING.length()); pw.println(tabs + "}; // end class " + nativeClassName); } } tabs = ""; processTemplate(pw, map, HEADER_TEMPLATE_ENDH, tabs); } for (int segment_index = 0; segment_index < num_class_segments; segment_index++) { String header_segment_file = header_file_base + String.format(fmt, segment_index) + ".h"; try (PrintWriter pw = new PrintWriter(new FileWriter(header_segment_file))) { tabs = ""; //processTemplate(pw, map, HEADER_TEMPLATE_STARTH, tabs); pw.println("// Never include this file (" + header_segment_file + ") directly. include " + header + " instead."); pw.println(); Class lastClass = null; final int start_segment_index = segment_index * classes_per_file; final int end_segment_index = Math.min(segment_index * classes_per_file + classes_per_file, classes.size()); List<Class> classesSegList = classes.subList(start_segment_index, end_segment_index); pw.println(); pw.println(tabs + "// start_segment_index = " + start_segment_index); pw.println(tabs + "// start_segment_index = " + end_segment_index); pw.println(tabs + "// segment_index = " + segment_index); pw.println(tabs + "// classesSegList=" + classesSegList); pw.println(); for (int class_index = 0; class_index < classesSegList.size(); class_index++) { Class clss = classesSegList.get(class_index); pw.println(); pw.println(tabs + "// class_index = " + class_index + " clss=" + clss); pw.println(); String clssName = clss.getCanonicalName(); tabs = openClassNamespace(clss, pw, tabs, lastClass); String clssOnlyName = getCppClassName(clss); map.put(CLASS_NAME, clssOnlyName); map.put("%BASE_CLASS_FULL_NAME%", classToCppBase(clss)); map.put(OBJECT_CLASS_FULL_NAME, getCppRelativeName(Object.class, clss)); tabs += TAB_STRING; processTemplate(pw, map, HEADER_CLASS_STARTH, tabs); tabs += TAB_STRING; Constructor constructors[] = clss.getDeclaredConstructors(); if (!hasNoArgConstructor(constructors)) { if (Modifier.isAbstract(clss.getModifiers()) || clss.isInterface()) { pw.println(tabs + "protected:"); pw.println(tabs + clssOnlyName + "() {};"); pw.println(tabs + "public:"); } else { if (constructors.length > 0) { pw.println(tabs + "protected:"); } pw.println(tabs + clssOnlyName + "();"); if (constructors.length > 0) { pw.println(tabs + "public:"); } } } for (Constructor c : constructors) { if (c.getParameterTypes().length == 0 && Modifier.isProtected(c.getModifiers())) { pw.println(tabs + "protected:"); pw.println(tabs + clssOnlyName + "();"); pw.println(tabs + "public:"); } if (checkConstructor(c, clss, classes)) { continue; } if (c.getParameterTypes().length == 1 && clss.isAssignableFrom(c.getParameterTypes()[0])) { continue; } if (!Modifier.isPublic(c.getModifiers())) { continue; } if (c.getParameterTypes().length == 1) { if (c.getParameterTypes()[0].getName().equals(clss.getName())) { // if(verbose) System.out.println("skipping constructor."); continue; } } if (!checkParameters(c.getParameterTypes(), classes)) { continue; } pw.println( tabs + clssOnlyName + getCppParamDeclarations(c.getParameterTypes(), clss) + ";"); if (isConstructorToMakeEasy(c, clss)) { pw.println(tabs + clssOnlyName + getEasyCallCppParamDeclarations(c.getParameterTypes(), clss) + ";"); } } pw.println(tabs + "~" + clssOnlyName + "();"); Field fa[] = clss.getDeclaredFields(); for (int findex = 0; findex < fa.length; findex++) { Field field = fa[findex]; if (addGetterMethod(field, clss, classes)) { pw.println(tabs + getCppFieldGetterDeclaration(field, clss)); } if (addSetterMethod(field, clss, classes)) { pw.println(tabs + getCppFieldSetterDeclaration(field, clss)); } } Method methods[] = clss.getDeclaredMethods(); for (int j = 0; j < methods.length; j++) { Method method = methods[j]; if (!checkMethod(method, classes)) { continue; } if ((method.getModifiers() & Modifier.PUBLIC) == Modifier.PUBLIC) { pw.println(tabs + getCppDeclaration(method, clss)); } if (isArrayStringMethod(method)) { pw.println(tabs + getCppModifiers(method.getModifiers()) + getCppType(method.getReturnType(), clss) + " " + fixMethodName(method) + "(int argc,const char **argv);"); } if (isMethodToMakeEasy(method)) { pw.println(tabs + getEasyCallCppDeclaration(method, clss)); } } tabs = tabs.substring(TAB_STRING.length()); pw.println(tabs + "}; // end class " + clssOnlyName); tabs = tabs.substring(0, tabs.length() - 1); Class nextClass = (class_index < (classesSegList.size() - 1)) ? classesSegList.get(class_index + 1) : null; tabs = closeClassNamespace(clss, pw, tabs, nextClass); pw.println(); lastClass = clss; } //processTemplate(pw, map, HEADER_TEMPLATE_ENDH, tabs); } } for (int segment_index = 0; segment_index < num_class_segments; segment_index++) { String output_segment_file = output; if (output_segment_file.endsWith(".cpp")) { output_segment_file = output_segment_file.substring(0, output_segment_file.length() - 4); } else if (output_segment_file.endsWith(".cc")) { output_segment_file = output_segment_file.substring(0, output_segment_file.length() - 3); } output_segment_file += "" + String.format(fmt, segment_index) + ".cpp"; try (PrintWriter pw = new PrintWriter(new FileWriter(output_segment_file))) { tabs = ""; if (segment_index < 1) { processTemplate(pw, map, "cpp_template_start_first.cpp", tabs); } else { processTemplate(pw, map, CPP_TEMPLATE_STARTCPP, tabs); } final int start_segment_index = segment_index * classes_per_file; final int end_segment_index = Math.min(segment_index * classes_per_file + classes_per_file, classes.size()); List<Class> classesSegList = classes.subList(start_segment_index, end_segment_index); pw.println(); pw.println(tabs + "// start_segment_index = " + start_segment_index); pw.println(tabs + "// start_segment_index = " + end_segment_index); pw.println(tabs + "// segment_index = " + segment_index); pw.println(tabs + "// classesSegList=" + classesSegList); pw.println(); Class lastClass = null; for (int class_index = 0; class_index < classesSegList.size(); class_index++) { Class clss = classesSegList.get(class_index); pw.println(); pw.println(tabs + "// class_index = " + class_index + " clss=" + clss); pw.println(); String clssName = clss.getCanonicalName(); tabs = openClassNamespace(clss, pw, tabs, lastClass); String clssOnlyName = getCppClassName(clss); map.put(CLASS_NAME, clssOnlyName); map.put("%BASE_CLASS_FULL_NAME%", classToCppBase(clss)); map.put(FULL_CLASS_NAME, clssName); String fcjs = classToJNISignature(clss); fcjs = fcjs.substring(1, fcjs.length() - 1); map.put(FULL_CLASS_JNI_SIGNATURE, fcjs); if (verbose) { System.out.println("fcjs = " + fcjs); } map.put(OBJECT_CLASS_FULL_NAME, getCppRelativeName(Object.class, clss)); map.put("%INITIALIZE_CONTEXT%", ""); map.put("%INITIALIZE_CONTEXT_REF%", ""); processTemplate(pw, map, CPP_START_CLASSCPP, tabs); Constructor constructors[] = clss.getDeclaredConstructors(); if (!hasNoArgConstructor(constructors)) { if (!Modifier.isAbstract(clss.getModifiers()) && !clss.isInterface()) { pw.println(tabs + clssOnlyName + "::" + clssOnlyName + "() : " + classToCppBase(clss) + "((jobject)NULL,false) {"); map.put(JNI_SIGNATURE, "()V"); map.put(CONSTRUCTOR_ARGS, ""); processTemplate(pw, map, CPP_NEWCPP, tabs); pw.println(tabs + "}"); pw.println(); } } for (Constructor c : constructors) { if (checkConstructor(c, clss, classes)) { continue; } Class[] paramClasses = c.getParameterTypes(); pw.println(tabs + clssOnlyName + "::" + clssOnlyName + getCppParamDeclarations(paramClasses, clss) + " : " + classToCppBase(clss) + "((jobject)NULL,false) {"); tabs = tabs + TAB_STRING; map.put(JNI_SIGNATURE, "(" + getJNIParamSignature(paramClasses) + ")V"); map.put(CONSTRUCTOR_ARGS, (paramClasses.length > 0 ? "," : "") + getCppParamNames(paramClasses)); processTemplate(pw, map, CPP_NEWCPP, tabs); tabs = tabs.substring(0, tabs.length() - 1); pw.println(tabs + "}"); pw.println(); if (isConstructorToMakeEasy(c, clss)) { pw.println(tabs + clssOnlyName + "::" + clssOnlyName + getEasyCallCppParamDeclarations(c.getParameterTypes(), clss) + " : " + classToCppBase(clss) + "((jobject)NULL,false) {"); processTemplate(pw, map, "cpp_start_easy_constructor.cpp", tabs); for (int paramIndex = 0; paramIndex < paramClasses.length; paramIndex++) { Class paramClasse = paramClasses[paramIndex]; String parmName = getParamNameIn(paramClasse, paramIndex); if (isString(paramClasse)) { pw.println(tabs + "jstring " + parmName + " = env->NewStringUTF(easyArg_" + paramIndex + ");"); } else if (isPrimitiveArray(paramClasse)) { String callString = getMethodCallString(paramClasse.getComponentType()); pw.println(tabs + getCppArrayType(paramClasse.getComponentType()) + " " + classToParamNameDecl(paramClasse, paramIndex) + "= env->New" + callString + "Array(easyArg_" + paramIndex + "_length);"); pw.println(tabs + "env->Set" + callString + "ArrayRegion(" + classToParamNameDecl(paramClasse, paramIndex) + ",0,easyArg_" + paramIndex + "_length,easyArg_" + paramIndex + ");"); } else { pw.println(tabs + getCppType(paramClasse, clss) + " " + classToParamNameDecl(paramClasse, paramIndex) + "= easyArg_" + paramIndex + ";"); } } processTemplate(pw, map, "cpp_new_easy_internals.cpp", tabs); for (int paramIndex = 0; paramIndex < paramClasses.length; paramIndex++) { Class paramClasse = paramClasses[paramIndex]; String parmName = getParamNameIn(paramClasse, paramIndex); if (isString(paramClasse)) { pw.println(tabs + "jobjectRefType ref_" + paramIndex + " = env->GetObjectRefType(" + parmName + ");"); pw.println(tabs + "if(ref_" + paramIndex + " == JNIGlobalRefType) {"); pw.println(tabs + TAB_STRING + "env->DeleteGlobalRef(" + parmName + ");"); pw.println(tabs + "}"); } else if (isPrimitiveArray(paramClasse)) { String callString = getMethodCallString(paramClasse.getComponentType()); pw.println(tabs + "env->Get" + callString + "ArrayRegion(" + classToParamNameDecl(paramClasse, paramIndex) + ",0,easyArg_" + paramIndex + "_length,easyArg_" + paramIndex + ");"); pw.println(tabs + "jobjectRefType ref_" + paramIndex + " = env->GetObjectRefType(" + parmName + ");"); pw.println(tabs + "if(ref_" + paramIndex + " == JNIGlobalRefType) {"); pw.println(tabs + TAB_STRING + "env->DeleteGlobalRef(" + parmName + ");"); pw.println(tabs + "}"); } else { } } processTemplate(pw, map, "cpp_end_easy_constructor.cpp", tabs); pw.println(tabs + "}"); } } pw.println(); pw.println(tabs + "// Destructor for " + clssName); pw.println(tabs + clssOnlyName + "::~" + clssOnlyName + "() {"); pw.println(tabs + "\t// Place-holder for later extensibility."); pw.println(tabs + "}"); pw.println(); Field fa[] = clss.getDeclaredFields(); for (int findex = 0; findex < fa.length; findex++) { Field field = fa[findex]; if (addGetterMethod(field, clss, classes)) { pw.println(); pw.println(tabs + "// Field getter for " + field.getName()); pw.println(getCppFieldGetterDefinitionStart(tabs, clssOnlyName, field, clss)); map.put("%FIELD_NAME%", field.getName()); map.put(JNI_SIGNATURE, classToJNISignature(field.getType())); Class returnClass = field.getType(); map.put(METHOD_ONFAIL, getOnFailString(returnClass, clss)); map.put(METHOD_ARGS, ""); map.put("%METHOD_RETURN%", isVoid(returnClass) ? "" : "return"); map.put("%METHOD_CALL_TYPE%", getMethodCallString(returnClass)); map.put("%METHOD_RETURN_TYPE%", getCppType(returnClass, clss)); map.put("%RETURN_VAR_DECLARE%", getMethodReturnVarDeclare(returnClass)); String retStore = isVoid(returnClass) ? "" : "retVal= (" + getMethodReturnVarType(returnClass) + ") "; map.put("%METHOD_RETURN_STORE%", retStore); map.put("%METHOD_RETURN_GET%", getMethodReturnGet(tabs, returnClass, clss)); if (Modifier.isStatic(field.getModifiers())) { processTemplate(pw, map, "cpp_static_getfield.cpp", tabs); } else { processTemplate(pw, map, "cpp_getfield.cpp", tabs); } pw.println(tabs + "}"); } if (addSetterMethod(field, clss, classes)) { pw.println(); pw.println(tabs + "// Field setter for " + field.getName()); pw.println(getCppFieldSetterDefinitionStart(tabs, clssOnlyName, field, clss)); map.put("%FIELD_NAME%", field.getName()); map.put(JNI_SIGNATURE, classToJNISignature(field.getType())); Class returnClass = void.class; map.put(METHOD_ONFAIL, getOnFailString(returnClass, clss)); Class[] paramClasses = new Class[] { field.getType() }; String methodArgs = getCppParamNames(paramClasses); map.put(METHOD_ARGS, (paramClasses.length > 0 ? "," : "") + methodArgs); map.put("%METHOD_RETURN%", isVoid(returnClass) ? "" : "return"); map.put("%METHOD_CALL_TYPE%", getMethodCallString(field.getType())); map.put("%METHOD_RETURN_TYPE%", getCppType(returnClass, clss)); map.put("%RETURN_VAR_DECLARE%", getMethodReturnVarDeclare(returnClass)); String retStore = isVoid(returnClass) ? "" : "retVal= (" + getMethodReturnVarType(returnClass) + ") "; map.put("%METHOD_RETURN_STORE%", retStore); map.put("%METHOD_RETURN_GET%", getMethodReturnGet(tabs, returnClass, clss)); if (Modifier.isStatic(field.getModifiers())) { processTemplate(pw, map, "cpp_static_setfield.cpp", tabs); } else { processTemplate(pw, map, "cpp_setfield.cpp", tabs); } pw.println(tabs + "}"); } } Method methods[] = clss.getDeclaredMethods(); for (int j = 0; j < methods.length; j++) { Method method = methods[j]; if (checkMethod(method, classes)) { pw.println(); pw.println(getCppMethodDefinitionStart(tabs, clssOnlyName, method, clss)); map.put(METHOD_NAME, method.getName()); if (fixMethodName(method).contains("equals2")) { if (verbose) { System.out.println("debug me"); } } map.put("%JAVA_METHOD_NAME%", method.getName()); Class[] paramClasses = method.getParameterTypes(); String methodArgs = getCppParamNames(paramClasses); map.put(METHOD_ARGS, (paramClasses.length > 0 ? "," : "") + methodArgs); Class returnClass = method.getReturnType(); map.put(JNI_SIGNATURE, "(" + getJNIParamSignature(paramClasses) + ")" + classToJNISignature(returnClass)); map.put(METHOD_ONFAIL, getOnFailString(returnClass, clss)); map.put("%METHOD_RETURN%", isVoid(returnClass) ? "" : "return"); map.put("%METHOD_CALL_TYPE%", getMethodCallString(returnClass)); map.put("%METHOD_RETURN_TYPE%", getCppType(returnClass, clss)); map.put("%RETURN_VAR_DECLARE%", getMethodReturnVarDeclare(returnClass)); String retStore = isVoid(returnClass) ? "" : "retVal= (" + getMethodReturnVarType(returnClass) + ") "; map.put("%METHOD_RETURN_STORE%", retStore); map.put("%METHOD_RETURN_GET%", getMethodReturnGet(tabs, returnClass, clss)); tabs += TAB_STRING; if (!Modifier.isStatic(method.getModifiers())) { processTemplate(pw, map, CPP_METHODCPP, tabs); } else { processTemplate(pw, map, CPP_STATIC_METHODCPP, tabs); } tabs = tabs.substring(0, tabs.length() - TAB_STRING.length()); pw.println(tabs + "}"); if (isArrayStringMethod(method)) { map.put(METHOD_RETURN_STORE, isVoid(returnClass) ? "" : getCppType(returnClass, clss) + " returnVal="); map.put(METHOD_RETURN_GET, isVoid(returnClass) ? "return ;" : "return returnVal;"); processTemplate(pw, map, CPP_EASY_STRING_ARRAY_METHODCPP, tabs); } else if (isMethodToMakeEasy(method)) { pw.println(); pw.println(tabs + "// Easy call alternative for " + method.getName()); pw.println(getEasyCallCppMethodDefinitionStart(tabs, clssOnlyName, method, clss)); tabs += TAB_STRING; map.put("%RETURN_VAR_DECLARE%", getMethodReturnVarDeclareOut(returnClass, clss)); processTemplate(pw, map, "cpp_start_easy_method.cpp", tabs); for (int paramIndex = 0; paramIndex < paramClasses.length; paramIndex++) { Class paramClasse = paramClasses[paramIndex]; String parmName = getParamNameIn(paramClasse, paramIndex); if (isString(paramClasse)) { pw.println(tabs + "jstring " + parmName + " = env->NewStringUTF(easyArg_" + paramIndex + ");"); } else if (isPrimitiveArray(paramClasse)) { String callString = getMethodCallString(paramClasse.getComponentType()); pw.println(tabs + getCppArrayType(paramClasse.getComponentType()) + " " + classToParamNameDecl(paramClasse, paramIndex) + "= env->New" + callString + "Array(easyArg_" + paramIndex + "_length);"); pw.println(tabs + "env->Set" + callString + "ArrayRegion(" + classToParamNameDecl(paramClasse, paramIndex) + ",0,easyArg_" + paramIndex + "_length,easyArg_" + paramIndex + ");"); } else { pw.println(tabs + getCppType(paramClasse, clss) + " " + classToParamNameDecl(paramClasse, paramIndex) + "= easyArg_" + paramIndex + ";"); } } String methodArgsIn = getCppParamNamesIn(paramClasses); String retStoreOut = isVoid(returnClass) ? "" : "retVal= (" + getMethodReturnOutVarType(returnClass, clss) + ") "; pw.println(tabs + retStoreOut + fixMethodName(method) + "(" + methodArgsIn + ");"); for (int paramIndex = 0; paramIndex < paramClasses.length; paramIndex++) { Class paramClasse = paramClasses[paramIndex]; String parmName = getParamNameIn(paramClasse, paramIndex); if (isString(paramClasse)) { pw.println(tabs + "jobjectRefType ref_" + paramIndex + " = env->GetObjectRefType(" + parmName + ");"); pw.println(tabs + "if(ref_" + paramIndex + " == JNIGlobalRefType) {"); pw.println(tabs + TAB_STRING + "env->DeleteGlobalRef(" + parmName + ");"); pw.println(tabs + "}"); } else if (isPrimitiveArray(paramClasse)) { String callString = getMethodCallString(paramClasse.getComponentType()); pw.println(tabs + "env->Get" + callString + "ArrayRegion(" + classToParamNameDecl(paramClasse, paramIndex) + ",0,easyArg_" + paramIndex + "_length,easyArg_" + paramIndex + ");"); pw.println(tabs + "jobjectRefType ref_" + paramIndex + " = env->GetObjectRefType(" + parmName + ");"); pw.println(tabs + "if(ref_" + paramIndex + " == JNIGlobalRefType) {"); pw.println(tabs + TAB_STRING + "env->DeleteGlobalRef(" + parmName + ");"); pw.println(tabs + "}"); } else { } } processTemplate(pw, map, "cpp_end_easy_method.cpp", tabs); if (!isVoid(returnClass)) { pw.println(tabs + "return retVal;"); } tabs = tabs.substring(TAB_STRING.length()); pw.println(tabs + "}"); pw.println(); } } } processTemplate(pw, map, CPP_END_CLASSCPP, tabs); tabs = tabs.substring(0, tabs.length() - 1); Class nextClass = (class_index < (classesSegList.size() - 1)) ? classesSegList.get(class_index + 1) : null; tabs = closeClassNamespace(clss, pw, tabs, nextClass); lastClass = clss; } if (segment_index < 1) { if (null != nativesClassMap) { for (Entry<String, Class> e : nativesClassMap.entrySet()) { final Class javaClass = e.getValue(); final String nativeClassName = e.getKey(); map.put(CLASS_NAME, nativeClassName); map.put(FULL_CLASS_NAME, nativeClassName); map.put(FULL_CLASS_JNI_SIGNATURE, nativeClassName); map.put("%BASE_CLASS_FULL_NAME%", "::" + namespace + "::" + getModifiedClassName(javaClass).replace(".", "::")); map.put(OBJECT_CLASS_FULL_NAME, "::" + namespace + "::java::lang::Object"); map.put("%INITIALIZE_CONTEXT%", "context=NULL; initContext(NULL,false);"); map.put("%INITIALIZE_CONTEXT_REF%", "context=NULL; initContext(objref.context,true);"); tabs += TAB_STRING; processTemplate(pw, map, CPP_START_CLASSCPP, tabs); pw.println(); pw.println(tabs + nativeClassName + "::" + nativeClassName + "() : " + getModifiedClassName(javaClass).replace(".", "::") + "((jobject)NULL,false) {"); tabs += TAB_STRING; pw.println(tabs + "context=NULL;"); pw.println(tabs + "initContext(NULL,false);"); map.put(JNI_SIGNATURE, "()V"); map.put(CONSTRUCTOR_ARGS, ""); processTemplate(pw, map, "cpp_new_native.cpp", tabs); tabs = tabs.substring(TAB_STRING.length()); pw.println(tabs + "}"); pw.println(); pw.println(tabs + "// Destructor for " + nativeClassName); pw.println(tabs + nativeClassName + "::~" + nativeClassName + "() {"); pw.println(tabs + TAB_STRING + "if(NULL != context) {"); pw.println(tabs + TAB_STRING + TAB_STRING + "deleteContext();"); pw.println(tabs + TAB_STRING + "}"); pw.println(tabs + TAB_STRING + "context=NULL;"); pw.println(tabs + "}"); pw.println(); // pw.println(tabs + "public:"); // pw.println(tabs + nativeClassName + "();"); // pw.println(tabs + "~" + nativeClassName + "();"); tabs = tabs.substring(TAB_STRING.length()); // Method methods[] = javaClass.getDeclaredMethods(); // for (int j = 0; j < methods.length; j++) { // Method method = methods[j]; // int modifiers = method.getModifiers(); // if (!Modifier.isPublic(modifiers)) { // continue; // } // pw.println(tabs + getCppDeclaration(method, javaClass)); // } // pw.println(tabs + "}; // end class " + nativeClassName); processTemplate(pw, map, CPP_END_CLASSCPP, tabs); } } processTemplate(pw, map, "cpp_template_end_first.cpp", tabs); tabs = ""; if (null != nativesClassMap) { pw.println("using namespace " + namespace + ";"); pw.println("#ifdef __cplusplus"); pw.println("extern \"C\" {"); pw.println("#endif"); int max_method_count = 0; tabs = ""; for (Entry<String, Class> e : nativesClassMap.entrySet()) { final Class javaClass = e.getValue(); final String nativeClassName = e.getKey(); map.put(CLASS_NAME, nativeClassName); map.put(FULL_CLASS_NAME, nativeClassName); map.put("%BASE_CLASS_FULL_NAME%", "::" + namespace + "::" + getModifiedClassName(javaClass).replace(".", "::")); map.put(OBJECT_CLASS_FULL_NAME, "::" + namespace + "::java::lang::Object"); map.put(FULL_CLASS_JNI_SIGNATURE, nativeClassName); map.put(METHOD_ONFAIL, "return;"); Method methods[] = javaClass.getDeclaredMethods(); if (max_method_count < methods.length) { max_method_count = methods.length; } for (int j = 0; j < methods.length; j++) { Method method = methods[j]; int modifiers = method.getModifiers(); if (!Modifier.isPublic(modifiers)) { continue; } if (Modifier.isAbstract(modifiers) && Modifier.isPublic(modifiers) && !Modifier.isStatic(modifiers) // && !method.isDefault() && !method.isSynthetic()) { Class[] paramClasses = method.getParameterTypes(); String methodArgs = getCppParamNames(paramClasses); map.put(METHOD_ARGS, methodArgs); map.put(METHOD_NAME, method.getName()); Class returnClass = method.getReturnType(); String retStore = isVoid(returnClass) ? "" : "retVal= (" + getMethodReturnVarType(returnClass) + ") "; map.put(METHOD_ONFAIL, getOnFailString(returnClass, javaClass)); map.put("%RETURN_VAR_DECLARE%", getMethodReturnVarDeclare(returnClass)); map.put("%METHOD_RETURN_STORE%", retStore); map.put("%METHOD_RETURN_GET%", getMethodReturnGet(tabs, returnClass, javaClass)); pw.println(); String paramDecls = getCppParamDeclarations(paramClasses, javaClass); String argsToAdd = method.getParameterTypes().length > 0 ? "," + paramDecls.substring(1, paramDecls.length() - 1) : ""; pw.println("JNIEXPORT " + getCppType(returnClass, javaClass) + " JNICALL Java_" + nativeClassName + "_" + method.getName() + "(JNIEnv *env, jobject jthis" + argsToAdd + ") {"); tabs = TAB_STRING; processTemplate(pw, map, "cpp_native_wrap.cpp", tabs); tabs = tabs.substring(TAB_STRING.length()); pw.println("}"); pw.println(); } } pw.println("JNIEXPORT void JNICALL Java_" + nativeClassName + "_nativeDelete(JNIEnv *env, jobject jthis) {"); tabs += TAB_STRING; map.put(METHOD_ONFAIL, getOnFailString(void.class, javaClass)); processTemplate(pw, map, "cpp_native_delete.cpp", tabs); tabs = tabs.substring(TAB_STRING.length()); pw.println(tabs + "}"); pw.println(); } pw.println("#ifdef __cplusplus"); pw.println("} // end extern \"C\""); pw.println("#endif"); map.put("%MAX_METHOD_COUNT%", Integer.toString(max_method_count + 1)); processTemplate(pw, map, "cpp_start_register_native.cpp", tabs); for (Entry<String, Class> e : nativesClassMap.entrySet()) { final Class javaClass = e.getValue(); final String nativeClassName = e.getKey(); map.put(CLASS_NAME, nativeClassName); map.put(FULL_CLASS_NAME, nativeClassName); map.put("%BASE_CLASS_FULL_NAME%", "::" + namespace + "::" + getModifiedClassName(javaClass).replace(".", "::")); map.put(OBJECT_CLASS_FULL_NAME, "::" + namespace + "::java::lang::Object"); processTemplate(pw, map, "cpp_start_register_native_class.cpp", tabs); tabs += TAB_STRING; Method methods[] = javaClass.getDeclaredMethods(); int method_number = 0; for (int j = 0; j < methods.length; j++) { Method method = methods[j]; int modifiers = method.getModifiers(); if (!Modifier.isPublic(modifiers)) { continue; } if (Modifier.isAbstract(modifiers) && Modifier.isPublic(modifiers) && !Modifier.isStatic(modifiers) // && !method.isDefault() && !method.isSynthetic()) { map.put("%METHOD_NUMBER%", Integer.toString(method_number)); map.put(METHOD_NAME, method.getName()); map.put(JNI_SIGNATURE, "(" + getJNIParamSignature(method.getParameterTypes()) + ")" + classToJNISignature(method.getReturnType())); processTemplate(pw, map, "cpp_register_native_item.cpp", tabs); method_number++; } } map.put("%METHOD_NUMBER%", Integer.toString(method_number)); map.put(METHOD_NAME, "nativeDelete"); map.put(JNI_SIGNATURE, "()V"); processTemplate(pw, map, "cpp_register_native_item.cpp", tabs); map.put("%NUM_NATIVE_METHODS%", Integer.toString(method_number)); processTemplate(pw, map, "cpp_end_register_native_class.cpp", tabs); tabs = tabs.substring(TAB_STRING.length()); } processTemplate(pw, map, "cpp_end_register_native.cpp", tabs); } else { pw.println("// No Native classes : registerNativMethods not needed."); pw.println("static void registerNativeMethods(JNIEnv *env) {}"); } } else { processTemplate(pw, map, CPP_TEMPLATE_ENDCPP, tabs); } } if (null != nativesClassMap) { tabs = ""; for (Entry<String, Class> e : nativesClassMap.entrySet()) { String nativeClassName = e.getKey(); File nativeClassHeaderFile = new File( namespace.toLowerCase() + "_" + nativeClassName.toLowerCase() + ".h"); map.put("%NATIVE_CLASS_HEADER%", nativeClassHeaderFile.getName()); map.put(CLASS_NAME, nativeClassName); if (nativeClassHeaderFile.exists()) { if (verbose) { System.out.println("skipping " + nativeClassHeaderFile.getCanonicalPath() + " since it already exists."); } } else { try (PrintWriter pw = new PrintWriter(new FileWriter(nativeClassHeaderFile))) { processTemplate(pw, map, "header_native_imp.h", tabs); } } File nativeClassCppFile = new File( namespace.toLowerCase() + "_" + nativeClassName.toLowerCase() + ".cpp"); if (nativeClassCppFile.exists()) { if (verbose) { System.out.println("skipping " + nativeClassCppFile.getCanonicalPath() + " since it already exists."); } } else { try (PrintWriter pw = new PrintWriter(new FileWriter(nativeClassCppFile))) { processTemplate(pw, map, "cpp_native_imp_start.cpp", tabs); Class javaClass = e.getValue(); Method methods[] = javaClass.getDeclaredMethods(); int method_number = 0; for (int j = 0; j < methods.length; j++) { Method method = methods[j]; int modifiers = method.getModifiers(); if (!Modifier.isPublic(modifiers)) { continue; } if (Modifier.isAbstract(modifiers) && Modifier.isPublic(modifiers) && !Modifier.isStatic(modifiers) // && !method.isDefault() && !method.isSynthetic()) { Class[] paramClasses = method.getParameterTypes(); // String methodArgs = getCppParamNames(paramClasses); String paramDecls = getCppParamDeclarations(paramClasses, javaClass); String methodArgs = method.getParameterTypes().length > 0 ? paramDecls.substring(1, paramDecls.length() - 1) : ""; map.put(METHOD_ARGS, methodArgs); map.put(METHOD_NAME, method.getName()); Class returnClass = method.getReturnType(); String retStore = isVoid(returnClass) ? "" : "retVal= (" + getMethodReturnVarType(returnClass) + ") "; map.put(METHOD_ONFAIL, getOnFailString(returnClass, javaClass)); map.put("%RETURN_TYPE%", getCppType(returnClass, javaClass)); map.put("%RETURN_VAR_DECLARE%", getMethodReturnVarDeclare(returnClass)); map.put("%METHOD_RETURN_STORE%", retStore); map.put("%METHOD_RETURN_GET%", getMethodReturnGet(tabs, returnClass, javaClass)); processTemplate(pw, map, "cpp_native_imp_stub.cpp", tabs); } } processTemplate(pw, map, "cpp_native_imp_end.cpp", tabs); } } } } } main_completed = true; }
From source file:ca.oson.json.Oson.java
<T> T newInstance(Map<String, Object> map, Class<T> valueType) { InstanceCreator creator = getTypeAdapter(valueType); if (creator != null) { return (T) creator.createInstance(valueType); }//from w w w .java 2 s . co m T obj = null; if (valueType != null) { obj = (T) getDefaultValue(valueType); if (obj != null) { return obj; } } if (map == null) { return null; } // @JsonTypeInfo(use = JsonTypeInfo.Id.MINIMAL_CLASS, include = As.PROPERTY, property = "@class") //@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = As.PROPERTY, property = "@class") String JsonClassType = null; if (valueType != null) { if (getAnnotationSupport()) { for (Annotation annotation : valueType.getAnnotations()) { if (annotation instanceof JsonTypeInfo) { JsonTypeInfo jsonTypeInfo = (JsonTypeInfo) annotation; JsonTypeInfo.Id use = jsonTypeInfo.use(); JsonTypeInfo.As as = jsonTypeInfo.include(); if ((use == JsonTypeInfo.Id.MINIMAL_CLASS || use == JsonTypeInfo.Id.CLASS) && as == As.PROPERTY) { JsonClassType = jsonTypeInfo.property(); } } } } } if (JsonClassType == null) { JsonClassType = getJsonClassType(); } String className = null; if (map.containsKey(JsonClassType)) { className = map.get(JsonClassType).toString(); } Class<T> classType = getClassType(className); // && (valueType == null || valueType.isAssignableFrom(classType) || Map.class.isAssignableFrom(valueType)) if (classType != null) { valueType = classType; } if (valueType == null) { return (T) map; // or null, which is better? } Constructor<?>[] constructors = null; Class implClass = null; if (valueType.isInterface() || Modifier.isAbstract(valueType.getModifiers())) { implClass = DeSerializerUtil.implementingClass(valueType.getName()); } if (implClass != null) { constructors = implClass.getDeclaredConstructors(); } else { constructors = valueType.getDeclaredConstructors();//.getConstructors(); } Object singleMapValue = null; Class singleMapValueType = null; if (map.size() == 1) { singleMapValue = map.get(valueType.getName()); if (singleMapValue != null) { singleMapValueType = singleMapValue.getClass(); if (singleMapValueType == String.class) { singleMapValue = StringUtil.unquote(singleMapValue.toString(), isEscapeHtml()); } try { if (valueType == Locale.class) { Constructor constructor = null; String[] parts = ((String) singleMapValue).split("_"); if (parts.length == 1) { constructor = valueType.getConstructor(String.class); constructor.setAccessible(true); obj = (T) constructor.newInstance(singleMapValue); } else if (parts.length == 2) { constructor = valueType.getConstructor(String.class, String.class); constructor.setAccessible(true); obj = (T) constructor.newInstance(parts); } else if (parts.length == 3) { constructor = valueType.getConstructor(String.class, String.class, String.class); constructor.setAccessible(true); obj = (T) constructor.newInstance(parts); } if (obj != null) { return obj; } } } catch (Exception e) { } Map<Class, Constructor> cmaps = new HashMap<>(); for (Constructor constructor : constructors) { //Class[] parameterTypes = constructor.getParameterTypes(); int parameterCount = constructor.getParameterCount(); if (parameterCount == 1) { Class[] types = constructor.getParameterTypes(); cmaps.put(types[0], constructor); } } if (cmaps.size() > 0) { Constructor constructor = null; if ((cmaps.containsKey(Boolean.class) || cmaps.containsKey(boolean.class)) && BooleanUtil.isBoolean(singleMapValue.toString())) { constructor = cmaps.get(Boolean.class); if (constructor == null) { constructor = cmaps.get(boolean.class); } if (constructor != null) { try { constructor.setAccessible(true); obj = (T) constructor .newInstance(BooleanUtil.string2Boolean(singleMapValue.toString())); if (obj != null) { return obj; } } catch (Exception e) { } } } else if (StringUtil.isNumeric(singleMapValue.toString())) { Class[] classes = new Class[] { int.class, Integer.class, long.class, Long.class, double.class, Double.class, Byte.class, byte.class, Short.class, short.class, Float.class, float.class, BigDecimal.class, BigInteger.class, AtomicInteger.class, AtomicLong.class, Number.class }; for (Class cls : classes) { constructor = cmaps.get(cls); if (constructor != null) { try { obj = (T) constructor.newInstance(NumberUtil.getNumber(singleMapValue, cls)); if (obj != null) { return obj; } } catch (Exception e) { } } } } else if (StringUtil.isArrayOrList(singleMapValue.toString()) || singleMapValue.getClass().isArray() || Collection.class.isAssignableFrom(singleMapValue.getClass())) { for (Entry<Class, Constructor> entry : cmaps.entrySet()) { Class cls = entry.getKey(); constructor = entry.getValue(); if (cls.isArray() || Collection.class.isAssignableFrom(cls)) { Object listObject = null; if (singleMapValue instanceof String) { JSONArray objArray = new JSONArray(singleMapValue.toString()); listObject = (List) fromJsonMap(objArray); } else { listObject = singleMapValue; } FieldData objectDTO = new FieldData(listObject, cls, true); listObject = json2Object(objectDTO); if (listObject != null) { try { obj = (T) constructor.newInstance(listObject); if (obj != null) { return obj; } } catch (Exception e) { } } } } } for (Entry<Class, Constructor> entry : cmaps.entrySet()) { Class cls = entry.getKey(); constructor = entry.getValue(); try { obj = (T) constructor.newInstance(singleMapValue); if (obj != null) { return obj; } } catch (Exception e) { } } } } } if (implClass != null) { valueType = implClass; } try { obj = valueType.newInstance(); if (obj != null) { return setSingleMapValue(obj, valueType, singleMapValue, singleMapValueType); } } catch (InstantiationException | IllegalAccessException e) { //e.printStackTrace(); } ///* for (Constructor constructor : constructors) { //Class[] parameterTypes = constructor.getParameterTypes(); int parameterCount = constructor.getParameterCount(); if (parameterCount > 0) { constructor.setAccessible(true); Annotation[] annotations = constructor.getDeclaredAnnotations(); // getAnnotations(); for (Annotation annotation : annotations) { boolean isJsonCreator = false; if (annotation instanceof JsonCreator) { isJsonCreator = true; } else if (annotation instanceof ca.oson.json.annotation.FieldMapper) { ca.oson.json.annotation.FieldMapper fieldMapper = (ca.oson.json.annotation.FieldMapper) annotation; if (fieldMapper.jsonCreator() == BOOLEAN.TRUE) { isJsonCreator = true; } } if (isJsonCreator) { Parameter[] parameters = constructor.getParameters(); String[] parameterNames = ObjectUtil.getParameterNames(parameters); //parameterCount = parameters.length; Object[] parameterValues = new Object[parameterCount]; int i = 0; for (String parameterName : parameterNames) { parameterValues[i] = getParameterValue(map, valueType, parameterName, parameters[i].getType()); i++; } try { obj = (T) constructor.newInstance(parameterValues); if (obj != null) { return setSingleMapValue(obj, valueType, singleMapValue, singleMapValueType); } } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { //e.printStackTrace(); } } } } else { try { constructor.setAccessible(true); obj = (T) constructor.newInstance(); if (obj != null) { return setSingleMapValue(obj, valueType, singleMapValue, singleMapValueType); } } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { //e.printStackTrace(); } } } //*/ // try again for (Constructor constructor : constructors) { int parameterCount = constructor.getParameterCount(); if (parameterCount > 0) { constructor.setAccessible(true); try { List<String> parameterNames = ObjectUtil.getParameterNames(constructor); if (parameterNames != null && parameterNames.size() > 0) { Class[] parameterTypes = constructor.getParameterTypes(); int length = parameterTypes.length; if (length == parameterNames.size()) { Object[] parameterValues = new Object[length]; Object parameterValue; for (int i = 0; i < length; i++) { parameterValues[i] = getParameterValue(map, valueType, parameterNames.get(i), parameterTypes[i]); } try { obj = (T) constructor.newInstance(parameterValues); if (obj != null) { return setSingleMapValue(obj, valueType, singleMapValue, singleMapValueType); } } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { //e.printStackTrace(); } } } } catch (IOException e1) { // e1.printStackTrace(); } } } // try more for (Constructor constructor : constructors) { int parameterCount = constructor.getParameterCount(); if (parameterCount > 0) { constructor.setAccessible(true); Class[] parameterTypes = constructor.getParameterTypes(); List<String> parameterNames; try { parameterNames = ObjectUtil.getParameterNames(constructor); if (parameterNames != null) { int length = parameterTypes.length; if (length > parameterNames.size()) { length = parameterNames.size(); } Object[] parameterValues = new Object[length]; for (int i = 0; i < length; i++) { parameterValues[i] = getParameterValue(map, valueType, parameterNames.get(i), parameterTypes[i]); } obj = (T) constructor.newInstance(parameterValues); if (obj != null) { return setSingleMapValue(obj, valueType, singleMapValue, singleMapValueType); } } } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | IOException e) { //e.printStackTrace(); } } } // try more try { Method[] methods = valueType.getMethods(); // .getMethod("getInstance", null); List<Method> methodList = new ArrayList<>(); if (methods != null) { for (Method method : methods) { String methodName = method.getName(); if (methodName.equals("getInstance") || methodName.equals("newInstance") || methodName.equals("createInstance") || methodName.equals("factory")) { Class returnType = method.getReturnType(); if (valueType.isAssignableFrom(returnType) && Modifier.isStatic(method.getModifiers())) { int parameterCount = method.getParameterCount(); if (parameterCount == 0) { try { obj = ObjectUtil.getMethodValue(null, method); if (obj != null) { return setSingleMapValue(obj, valueType, singleMapValue, singleMapValueType); } } catch (IllegalArgumentException e) { // TODO Auto-generated catch block //e.printStackTrace(); } } else { methodList.add(method); } } } } for (Method method : methodList) { try { int parameterCount = method.getParameterCount(); Object[] parameterValues = new Object[parameterCount]; Object parameterValue; int i = 0; Class[] parameterTypes = method.getParameterTypes(); String[] parameterNames = ObjectUtil.getParameterNames(method); if (parameterCount == 1 && valueType != null && singleMapValue != null && singleMapValueType != null) { if (ObjectUtil.isSameDataType(parameterTypes[0], singleMapValueType)) { try { obj = ObjectUtil.getMethodValue(null, method, singleMapValue); if (obj != null) { return obj; } } catch (IllegalArgumentException ex) { //ex.printStackTrace(); } } } else if (parameterNames != null && parameterNames.length == parameterCount) { for (String parameterName : ObjectUtil.getParameterNames(method)) { parameterValues[i] = getParameterValue(map, valueType, parameterName, parameterTypes[i]); i++; } } else { // try annotation Parameter[] parameters = method.getParameters(); parameterNames = ObjectUtil.getParameterNames(parameters); parameterCount = parameters.length; parameterValues = new Object[parameterCount]; i = 0; for (String parameterName : parameterNames) { parameterValues[i] = getParameterValue(map, valueType, parameterName, parameterTypes[i]); i++; } } obj = ObjectUtil.getMethodValue(null, method, parameterValues); if (obj != null) { return setSingleMapValue(obj, valueType, singleMapValue, singleMapValueType); } } catch (IOException | IllegalArgumentException e) { //e.printStackTrace(); } } } } catch (SecurityException e) { // e.printStackTrace(); } // try all static methods, if the return type is correct, get it as the final object Method[] methods = valueType.getDeclaredMethods(); for (Method method : methods) { if (Modifier.isStatic(method.getModifiers())) { Class returnType = method.getReturnType(); if (valueType.isAssignableFrom(returnType)) { try { Object[] parameterValues = null; int parameterCount = method.getParameterCount(); if (parameterCount > 0) { if (parameterCount == 1 && map.size() == 1 && singleMapValue != null && singleMapValueType != null) { if (ObjectUtil.isSameDataType(method.getParameterTypes()[0], singleMapValueType)) { obj = ObjectUtil.getMethodValue(null, method, singleMapValueType); if (obj != null) { return obj; } } } parameterValues = new Object[parameterCount]; Object parameterValue; int i = 0; Class[] parameterTypes = method.getParameterTypes(); String[] parameterNames = ObjectUtil.getParameterNames(method); if (parameterNames != null && parameterNames.length == parameterCount) { for (String parameterName : ObjectUtil.getParameterNames(method)) { parameterValues[i] = getParameterValue(map, valueType, parameterName, parameterTypes[i]); i++; } } else { // try annotation Parameter[] parameters = method.getParameters(); parameterNames = ObjectUtil.getParameterNames(parameters); parameterCount = parameters.length; parameterValues = new Object[parameterCount]; i = 0; for (String parameterName : parameterNames) { parameterValues[i] = getParameterValue(map, valueType, parameterName, parameterTypes[i]); i++; } } } obj = ObjectUtil.getMethodValue(obj, method, parameterValues); if (obj != null) { return setSingleMapValue(obj, valueType, singleMapValue, singleMapValueType); } } catch (IOException | IllegalArgumentException e) { //e.printStackTrace(); } } } } return null; }
From source file:ca.oson.json.Oson.java
private <E, R> String object2Serialize(FieldData objectDTO) { E obj = (E) objectDTO.valueToProcess; Class<R> valueType = objectDTO.returnType; if (obj == null) { return null; }/* ww w . j av a 2 s . com*/ // it is possible the same object shared by multiple variables inside the same enclosing object int hash = ObjectUtil.hashCode(obj, valueType); if (!objectDTO.goAhead(hash)) { return "{}"; } ClassMapper classMapper = objectDTO.classMapper; // first build up the class-level processing rules // || (objectDTO.level == 0 && objectDTO.fieldMapper == null) //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); } FIELD_NAMING format = getFieldNaming(); String repeated = getPrettyIndentationln(objectDTO.level), pretty = getPrettySpace(); objectDTO.incrLevel(); String repeatedItem = getPrettyIndentationln(objectDTO.level); // @Expose Set<String> exposed = null; if (isUseGsonExpose()) { exposed = new HashSet<>(); } boolean annotationSupport = getAnnotationSupport(); Annotation[] annotations = null; if (annotationSupport) { annotations = valueType.getAnnotations(); ca.oson.json.annotation.ClassMapper classMapperAnnotation = null; // 3. Apply annotations from other sources 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.TRUE)) { 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.TRUE) { 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; } if (jsonAutoDetect.getterVisibility() == Visibility.NONE) { classMapper.useAttribute = false; } 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); exposed = null; } } // 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.serializer; //getSerializer(valueType); if (function == null) { function = DeSerializerUtil.getSerializer(valueType.getName()); } if (function != null) { try { Object returnValue = null; if (function instanceof DataMapper2JsonFunction) { DataMapper classData = new DataMapper(valueType, obj, classMapper, objectDTO.level, getPrettyIndentation()); objectDTO.jsonRawValue = false; DataMapper2JsonFunction f = (DataMapper2JsonFunction) function; return f.apply(classData); } else if (function instanceof FieldData2JsonFunction) { FieldData2JsonFunction f = (FieldData2JsonFunction) function; FieldData fieldData = objectDTO.clone(); returnValue = f.apply(fieldData); } else { returnValue = function.apply(obj); } if (returnValue != null) { Class returnType = returnValue.getClass(); if (returnType == String.class) { return StringUtil.doublequote(returnValue, isEscapeHtml()); } else if (returnType == valueType || valueType.isAssignableFrom(returnType)) { // just continue to do the serializing } else { objectDTO.valueToProcess = returnValue; objectDTO.returnType = returnType; return object2String(objectDTO); } } } catch (Exception e) { e.printStackTrace(); } } Set<Class> ignoreFieldsWithAnnotations = classMapper.ignoreFieldsWithAnnotations; Map<String, String> keyJsonStrings = new LinkedHashMap<>(); // to hold relation between name and changed name Map<String, String> fieldNames = new LinkedHashMap<>(); Set<String> processedNameSet = new HashSet<>(); //StringBuffer sb = new StringBuffer(); Map<String, Method> getters = null; Map<String, Method> setters = null; Map<String, Method> otherMethods = null; if (valueType.isInterface()) { valueType = (Class<R>) obj.getClass(); } else if (Modifier.isAbstract(valueType.getModifiers())) { // valueType } else { // Class objClass = obj.getClass(); // if (valueType.isAssignableFrom(objClass)) { // valueType = objClass; // } } // if (valueType.isInterface()) { // getters = getGetters(obj); // setters = getSetters(obj); // otherMethods = getOtherMethods(obj); // } else { getters = getGetters(valueType); setters = getSetters(valueType); otherMethods = getOtherMethods(valueType); // } Set<Method> jsonAnyGetterMethods = new HashSet<>(); if (classMapper.isToStringAsSerializer()) { try { Method getter = valueType.getDeclaredMethod("toString", null); if (getter != null) { E getterValue = ObjectUtil.getMethodValue(obj, getter); if (getterValue != null) { Class returnType = getterValue.getClass(); if (returnType == String.class) { return StringUtil.doublequote(getterValue, isEscapeHtml()); } else if (returnType == valueType || valueType.isAssignableFrom(returnType)) { // just continue to do the serializing } else { objectDTO.valueToProcess = getterValue; objectDTO.returnType = returnType; return object2String(objectDTO); } } } } catch (NoSuchMethodException | SecurityException e) { // e.printStackTrace(); } } //if (getters != null && getters.size() > 0) { boolean isJsonRawValue = false; String jsonValueFieldName = DeSerializerUtil.getJsonValueFieldName(valueType.getName()); // if (jsonValueFieldName == null) { // // get all fieldmappers for this class? // Set<FieldMapper> fieldMappers = getFieldMappers(valueType); // // looking for the method // for (FieldMapper fieldMapper: fieldMappers) { // if (fieldMapper.jsonValue != null && fieldMapper.jsonValue) { // jsonValueFieldName = fieldMapper.java; // isJsonRawValue = fieldMapper.isJsonRawValue(); // break; // } // } // } if (jsonValueFieldName == null) { jsonValueFieldName = classMapper.getJsonValueFieldName(); } if (jsonValueFieldName != null) { String lcjava = jsonValueFieldName.toLowerCase(); Method getter = null; if (getters != null && getters.containsKey(lcjava)) { getter = getters.get(lcjava); } else { try { getter = valueType.getMethod(jsonValueFieldName); } catch (NoSuchMethodException | SecurityException e) { // e.printStackTrace(); } if (getter == null) { try { getter = valueType.getMethod("get" + StringUtil.capitalize(jsonValueFieldName)); } catch (NoSuchMethodException | SecurityException e) { //e.printStackTrace(); } } } if (getter != null) { E getterValue = ObjectUtil.getMethodValue(obj, getter); if (getterValue != null) { Class returnType = getterValue.getClass(); if (returnType == String.class) { if (isJsonRawValue) { return getterValue.toString(); } else if (StringUtil.parenthesized(getterValue.toString())) { return getterValue.toString(); } else { return StringUtil.doublequote(getterValue, isEscapeHtml()); } } else if (returnType == valueType || valueType.isAssignableFrom(returnType)) { // just continue to do the serializing } else { objectDTO.valueToProcess = getterValue; objectDTO.returnType = returnType; objectDTO.jsonRawValue = isJsonRawValue; return object2String(objectDTO); } } } } //} try { Field[] fields = null; // if (valueType.isInterface()) { // fields = getFields(obj); // } else { fields = getFields(valueType); // } for (Field f : fields) { f.setAccessible(true); String name = f.getName(); String fieldName = name; String lcfieldName = fieldName.toLowerCase(); if (Modifier.isFinal(f.getModifiers()) && Modifier.isStatic(f.getModifiers())) { getters.remove(lcfieldName); continue; } // 6. Create a blank field mapper instance FieldMapper fieldMapper = new FieldMapper(name, name, valueType); Class<?> returnType = f.getType(); // value.getClass(); // 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 fieldMapper = classifyFieldMapper(fieldMapper, classMapper); FieldMapper javaFieldMapper = getFieldMapper(name, null, valueType); // getter and setter methods Method getter = getters.get(lcfieldName); Method setter = setters.get(lcfieldName); if (getter != null) { getter.setAccessible(true); } // control by visibility is not always a good idea // here consider the visibility of field and related getter method together if (ignoreModifiers(f.getModifiers(), classMapper.includeFieldsWithModifiers)) { if (getter != null) { if (ignoreModifiers(getter.getModifiers(), classMapper.includeFieldsWithModifiers)) { getters.remove(lcfieldName); continue; } } else { continue; } } boolean ignored = false; Set<String> names = new HashSet<>(); if (annotationSupport) { annotations = f.getDeclaredAnnotations();//.getAnnotations(); // field and getter should be treated the same way, if allowed in the class level // might not be 100% correct, as the useAttribute as not be applied from annotations yet // && ((javaFieldMapper == null || javaFieldMapper.useAttribute == null) && (fieldMapper.useAttribute == null || fieldMapper.useAttribute)) // || (javaFieldMapper != null && javaFieldMapper.useAttribute != null && javaFieldMapper.useAttribute) // annotations might apply to method only, not the field, so need to get them, regardless using attribute or not if (getter != null) { annotations = Stream .concat(Arrays.stream(annotations), Arrays.stream(getter.getDeclaredAnnotations())) .toArray(Annotation[]::new); // no annotations, then try set method if ((annotations == null || annotations.length == 0) && setter != null) { annotations = setter.getDeclaredAnnotations(); } } ca.oson.json.annotation.FieldMapper fieldMapperAnnotation = null; for (Annotation annotation : annotations) { if (ignoreField(annotation, 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.TRUE)) { 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.TRUE) { fieldMapperAnnotation = ann; //break; } } } else { // to improve performance, using swith on string switch (annotation.annotationType().getName()) { case "com.fasterxml.jackson.annotation.JsonAnyGetter": case "org.codehaus.jackson.annotate.JsonAnyGetter": fieldMapper.jsonAnyGetter = true; break; case "com.fasterxml.jackson.annotation.JsonIgnore": case "org.codehaus.jackson.annotate.JsonIgnore": fieldMapper.ignore = true; break; case "javax.persistence.Transient": ignored = true; break; case "com.fasterxml.jackson.annotation.JsonIgnoreProperties": JsonIgnoreProperties jsonIgnoreProperties = (JsonIgnoreProperties) annotation; if (!jsonIgnoreProperties.allowGetters()) { fieldMapper.ignore = true; } else { fieldMapper.ignore = false; classMapper.jsonIgnoreProperties.remove(name); } break; case "com.google.gson.annotations.Expose": Expose expose = (Expose) annotation; if (!expose.serialize()) { fieldMapper.ignore = true; } else if (exposed != null) { exposed.add(lcfieldName); } 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 "com.fasterxml.jackson.annotation.JsonValue": case "org.codehaus.jackson.annotate.JsonValue": fieldMapper.jsonValue = true; break; case "org.junit.Ignore": fieldMapper.ignore = true; break; case "javax.persistence.Enumerated": fieldMapper.enumType = ((Enumerated) annotation).value(); break; // case "javax.persistence.MapKeyEnumerated": // mapper.enumType = ((javax.persistence.MapKeyEnumerated) 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.WRITE_ONLY) { fieldMapper.ignore = true; break; } if (jsonProperty.required()) { fieldMapper.required = true; } if (jsonProperty.defaultValue() != null && jsonProperty.defaultValue().length() > 0) { 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); } } } // 10. Apply annotations from Oson // special name to handle if (fieldMapperAnnotation != null) { fieldMapper = overwriteBy(fieldMapper, fieldMapperAnnotation, classMapper); exposed = null; } } if (ignored) { if (getter != null) { getters.remove(lcfieldName); } continue; } // 11. Apply Java configuration for this particular field if (javaFieldMapper != null && javaFieldMapper.isSerializing()) { fieldMapper = overwriteBy(fieldMapper, javaFieldMapper); } if (fieldMapper.ignore != null && fieldMapper.ignore) { if (getter != null) { getters.remove(lcfieldName); } continue; } // in the ignored list if (ObjectUtil.inSet(name, classMapper.jsonIgnoreProperties)) { getters.remove(lcfieldName); continue; } if (fieldMapper.jsonAnyGetter != null && fieldMapper.jsonAnyGetter && getter != null) { getters.remove(lcfieldName); jsonAnyGetterMethods.add(getter); 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 (getter != null) { getters.remove(lcfieldName); } continue; } else if (fieldMapper.until != null && fieldMapper.until <= getVersion()) { if (getter != null) { getters.remove(lcfieldName); } continue; } //jsonIgnoreProperties // handling name now boolean jnameFixed = false; String json = fieldMapper.json; if (StringUtil.isEmpty(json)) { if (getter != null) { getters.remove(lcfieldName); } continue; } else if (!json.equals(name)) { name = json; jnameFixed = true; } if (!jnameFixed) { for (String jsoname : names) { if (!name.equals(jsoname) && !StringUtil.isEmpty(jsoname)) { name = jsoname; jnameFixed = true; break; } } } // only if the name is still the same as the field name // format it based on the naming settings // otherwise, it is set on purpose if (fieldName.equals(name)) { name = StringUtil.formatName(name, format); jnameFixed = true; } fieldMapper.java = fieldName; fieldMapper.json = name; // field valuie E value = null; try { value = (E) f.get(obj);// ObjectUtil.unwraponce(f.get(obj)); } catch (Exception e) { } if (value != null) { Class vtype = value.getClass(); if (returnType.isAssignableFrom(vtype)) { returnType = vtype; } } // value from getter E getterValue = null; if (getter != null) { if (fieldMapper.useAttribute == null || fieldMapper.useAttribute) { getterValue = ObjectUtil.getMethodValue(obj, getter); //getterValue = ObjectUtil.unwraponce(getterValue); } getters.remove(lcfieldName); } // determine which value to use if (getterValue != null) { if (getterValue.equals(value) || StringUtil.isEmpty(value)) { value = getterValue; } else if (DefaultValue.isDefault(value, returnType) && !DefaultValue.isDefault(getterValue, returnType)) { value = getterValue; } // else if (getterValue.toString().length() > value.toString().length()) { // value = getterValue; // } } String str; FieldData fieldData = new FieldData(obj, f, value, returnType, false, fieldMapper, objectDTO.level, objectDTO.set); str = object2Json(fieldData); if (fieldMapper.jsonValue != null && fieldMapper.jsonValue) { if (fieldMapper.isJsonRawValue()) { return StringUtil.unquote(str, isEscapeHtml()); } else { return StringUtil.doublequote(str, isEscapeHtml()); } } if (StringUtil.isNull(str)) { if (fieldMapper.defaultType == JSON_INCLUDE.NON_NULL || fieldMapper.defaultType == JSON_INCLUDE.NON_EMPTY || fieldMapper.defaultType == JSON_INCLUDE.NON_DEFAULT) { continue; } else { str = "null"; } } else if (StringUtil.isEmpty(str)) { if (fieldMapper.defaultType == JSON_INCLUDE.NON_EMPTY || fieldMapper.defaultType == JSON_INCLUDE.NON_DEFAULT) { continue; } str = "\"\""; } else if (fieldMapper.defaultType == JSON_INCLUDE.NON_DEFAULT && DefaultValue.isDefault(str, returnType)) { continue; } StringBuffer sb = new StringBuffer(); sb.append(repeatedItem); if (fieldMapper.jsonNoName == null || !fieldMapper.jsonNoName) { sb.append("\"" + name + "\":" + pretty); } sb.append(str); sb.append(","); keyJsonStrings.put(lcfieldName, sb.toString()); processedNameSet.add(name); fieldNames.put(lcfieldName, name.toLowerCase()); } // now process get methods for (Entry<String, Method> entry : getters.entrySet()) { String lcfieldName = entry.getKey(); Method getter = entry.getValue(); if (ignoreModifiers(getter.getModifiers(), classMapper.includeFieldsWithModifiers)) { continue; } if (Modifier.isFinal(getter.getModifiers()) && Modifier.isStatic(getter.getModifiers())) { continue; } String name = getter.getName(); if (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 (processedNameSet.contains(name) || fieldNames.containsKey(lcfieldName)) { continue; } getter.setAccessible(true); Method setter = setters.get(lcfieldName); // 6. Create a blank field mapper instance FieldMapper fieldMapper = new FieldMapper(name, name, valueType); Class<?> returnType = getter.getReturnType(); // 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 fieldMapper = classifyFieldMapper(fieldMapper, classMapper); FieldMapper javaFieldMapper = getFieldMapper(name, null, valueType); boolean ignored = false; Set<String> names = new HashSet<>(); if (annotationSupport) { annotations = getter.getDeclaredAnnotations();//.getAnnotations(); // no annotations, then try set method if ((annotations == null || annotations.length == 0) && setter != null) { annotations = setter.getDeclaredAnnotations(); } ca.oson.json.annotation.FieldMapper fieldMapperAnnotation = null; for (Annotation annotation : annotations) { if (ignoreField(annotation, 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.TRUE)) { 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.TRUE) { fieldMapperAnnotation = ann; //break; } } } else { // to improve performance, using swith on string switch (annotation.annotationType().getName()) { case "com.fasterxml.jackson.annotation.JsonAnyGetter": case "org.codehaus.jackson.annotate.JsonAnyGetter": fieldMapper.jsonAnyGetter = true; break; case "com.fasterxml.jackson.annotation.JsonIgnore": case "org.codehaus.jackson.annotate.JsonIgnore": fieldMapper.ignore = true; break; case "javax.persistence.Transient": ignored = true; break; case "com.fasterxml.jackson.annotation.JsonIgnoreProperties": JsonIgnoreProperties jsonIgnoreProperties = (JsonIgnoreProperties) annotation; if (!jsonIgnoreProperties.allowGetters()) { fieldMapper.ignore = true; } else { fieldMapper.ignore = false; classMapper.jsonIgnoreProperties.remove(name); } break; case "com.google.gson.annotations.Expose": Expose expose = (Expose) annotation; if (!expose.serialize()) { fieldMapper.ignore = true; } else if (exposed != null) { exposed.add(lcfieldName); } 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 "com.fasterxml.jackson.annotation.JsonValue": case "org.codehaus.jackson.annotate.JsonValue": fieldMapper.jsonValue = true; break; case "javax.persistence.Enumerated": fieldMapper.enumType = ((Enumerated) annotation).value(); break; // case "javax.persistence.MapKeyEnumerated": // mapper.enumType = ((javax.persistence.MapKeyEnumerated) 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.WRITE_ONLY) { fieldMapper.ignore = true; break; } if (jsonProperty.required()) { fieldMapper.required = true; } if (jsonProperty.defaultValue() != null && jsonProperty.defaultValue().length() > 0) { fieldMapper.defaultValue = jsonProperty.defaultValue(); } break; case "org.junit.Ignore": fieldMapper.ignore = true; 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 // special name to handle if (fieldMapperAnnotation != null) { fieldMapper = overwriteBy(fieldMapper, fieldMapperAnnotation, classMapper); exposed = null; } } if (ignored) { continue; } // 11. Apply Java configuration for this particular field if (javaFieldMapper != null && javaFieldMapper.isSerializing()) { fieldMapper = overwriteBy(fieldMapper, javaFieldMapper); } if (fieldMapper.ignore != null && fieldMapper.ignore) { continue; } // in the ignored list if (ObjectUtil.inSet(name, classMapper.jsonIgnoreProperties)) { continue; } if (fieldMapper.jsonAnyGetter != null && fieldMapper.jsonAnyGetter) { jsonAnyGetterMethods.add(getter); continue; } if (fieldMapper.useAttribute != null && !fieldMapper.useAttribute) { continue; } if (fieldMapper.since != null && fieldMapper.since > getVersion()) { if (getter != null) { getters.remove(lcfieldName); } continue; } else if (fieldMapper.until != null && fieldMapper.until <= getVersion()) { if (getter != null) { getters.remove(lcfieldName); } continue; } // handling name now boolean jnameFixed = false; String json = fieldMapper.json; if (StringUtil.isEmpty(json)) { if (getter != null) { getters.remove(lcfieldName); } continue; } else if (!json.equals(name)) { name = json; jnameFixed = true; } if (!jnameFixed) { for (String jsoname : names) { if (!name.equals(jsoname) && !StringUtil.isEmpty(jsoname)) { name = jsoname; jnameFixed = true; break; } } } // only if the name is still the same as the field name // format it based on the naming settings // otherwise, it is set on purpose if (fieldName.equals(name)) { name = StringUtil.formatName(name, format); jnameFixed = true; } fieldMapper.java = fieldName; fieldMapper.json = name; // get value E value = ObjectUtil.getMethodValue(obj, getter); if (fieldMapper.jsonValue != null && fieldMapper.jsonValue) { if (value != null) { if (fieldMapper.isJsonRawValue()) { return value.toString(); } else { return StringUtil.doublequote(value, isEscapeHtml()); } } } if (returnType == Class.class) { if (value != null && returnType != value.getClass()) { returnType = value.getClass(); } else { continue; } } String str = null; //if (returnType != valueType) { FieldData fieldData = new FieldData(obj, null, value, returnType, false, fieldMapper, objectDTO.level, objectDTO.set); objectDTO.getter = getter; str = object2Json(fieldData); //} if (StringUtil.isNull(str)) { if (fieldMapper.defaultType == JSON_INCLUDE.NON_NULL || fieldMapper.defaultType == JSON_INCLUDE.NON_EMPTY || fieldMapper.defaultType == JSON_INCLUDE.NON_DEFAULT) { continue; } else { str = "null"; } } else if (StringUtil.isEmpty(str)) { if (fieldMapper.defaultType == JSON_INCLUDE.NON_EMPTY || fieldMapper.defaultType == JSON_INCLUDE.NON_DEFAULT) { continue; } str = "null"; } else if (fieldMapper.defaultType == JSON_INCLUDE.NON_DEFAULT && DefaultValue.isDefault(str, returnType)) { continue; } StringBuffer sb = new StringBuffer(); sb.append(repeatedItem); if (fieldMapper.jsonNoName == null || !fieldMapper.jsonNoName) { sb.append("\"" + name + "\":" + pretty); } sb.append(str); sb.append(","); keyJsonStrings.put(lcfieldName, sb.toString()); processedNameSet.add(name); fieldNames.put(lcfieldName, name.toLowerCase()); } // handle @JsonAnyGetter if (annotationSupport) { for (Entry<String, Method> entry : otherMethods.entrySet()) { Method method = entry.getValue(); if (ignoreModifiers(method.getModifiers(), classMapper.includeFieldsWithModifiers)) { continue; } for (Annotation annotation : method.getAnnotations()) { if (ignoreField(annotation, ignoreFieldsWithAnnotations)) { continue; } if (annotation instanceof JsonValue || annotation instanceof org.codehaus.jackson.annotate.JsonValue) { Object mvalue = ObjectUtil.getMethodValue(obj, method); if (mvalue != null) { return StringUtil.doublequote(mvalue, isEscapeHtml()); } } else if (annotation instanceof JsonAnyGetter || annotation instanceof org.codehaus.jackson.annotate.JsonAnyGetter || annotation instanceof ca.oson.json.annotation.FieldMapper) { if (annotation instanceof ca.oson.json.annotation.FieldMapper) { ca.oson.json.annotation.FieldMapper fieldMapper = (ca.oson.json.annotation.FieldMapper) annotation; if (fieldMapper.jsonAnyGetter() == BOOLEAN.FALSE) { continue; } } jsonAnyGetterMethods.add(method); } } } } for (Method method : jsonAnyGetterMethods) { if (method != null) { Object allValues = ObjectUtil.getMethodValue(obj, method); if (allValues != null && allValues instanceof Map) { Map<String, Object> map = (Map) allValues; String str; for (String name : map.keySet()) { Object value = map.get(name); // java to json, check if this name is allowed or changed name = java2Json(name); if (!StringUtil.isEmpty(name)) { FieldData newFieldData = new FieldData(value, value.getClass(), false, objectDTO.level, objectDTO.set); newFieldData.defaultType = classMapper.defaultType; str = object2Json(newFieldData); if (StringUtil.isNull(str)) { if (classMapper.defaultType == JSON_INCLUDE.NON_NULL || classMapper.defaultType == JSON_INCLUDE.NON_EMPTY || classMapper.defaultType == JSON_INCLUDE.NON_DEFAULT) { continue; } else { str = "null"; } } else if (StringUtil.isEmpty(str)) { if (classMapper.defaultType == JSON_INCLUDE.NON_EMPTY || classMapper.defaultType == JSON_INCLUDE.NON_DEFAULT) { continue; } str = "null"; } else if (DefaultValue.isDefault(str, value.getClass())) { if (classMapper.defaultType == JSON_INCLUDE.NON_DEFAULT) { continue; } } StringBuffer sb = new StringBuffer(); sb.append(repeatedItem); sb.append("\"" + name + "\":" + pretty); sb.append(str); sb.append(","); keyJsonStrings.put(name, sb.toString()); } } } } } int size = keyJsonStrings.size(); if (size == 0) { return "{}"; // "" } else { String includeClassType = ""; if (classMapper.includeClassTypeInJson) { //getIncludeClassTypeInJson() includeClassType = repeatedItem + "\"@class\":" + pretty + "\"" + valueType.getName() + "\","; } if (exposed != null && exposed.size() > 0) { Map<String, String> map = new LinkedHashMap<>(); for (String key : keyJsonStrings.keySet()) { if (exposed.contains(key)) { map.put(key, keyJsonStrings.get(key)); } } keyJsonStrings = map; } if (keyJsonStrings.size() == 1 && this.isValueOnly()) { for (Map.Entry<String, String> entry : keyJsonStrings.entrySet()) { if (entry.getKey().toLowerCase().equals("value")) { String value = entry.getValue(); String[] values = value.split(":"); value = null; if (values.length == 1) { value = values[0]; } else if (values.length == 2) { value = values[1]; } if (value != null && value.length() > 1) { return value.substring(0, value.length() - 1); } } } } // based on sorting requirements StringBuffer sb = new StringBuffer(); if (classMapper.propertyOrders != null) { for (String property : classMapper.propertyOrders) { property = property.toLowerCase(); String jsonText = keyJsonStrings.get(property); if (jsonText != null) { sb.append(jsonText); keyJsonStrings.remove(property); } else { property = fieldNames.get(property); if (property != null && keyJsonStrings.containsKey(property)) { sb.append(keyJsonStrings.get(property)); keyJsonStrings.remove(property); } } } } List<String> properties = new ArrayList(keyJsonStrings.keySet()); if (classMapper.orderByKeyAndProperties) { Collections.sort(properties); } for (String property : properties) { sb.append(keyJsonStrings.get(property)); } String text = sb.toString(); size = text.length(); if (size == 0) { return "{}"; } else { return "{" + includeClassType + text.substring(0, size - 1) + repeated + "}"; } } } catch (IllegalArgumentException | SecurityException e) { e.printStackTrace(); throw new RuntimeException(e); // } catch (InvocationTargetException e) { } }
From source file:com.clark.func.Functions.java
/** * <p>//from w w w . j av a2 s . c o m * Return an accessible method (that is, one that can be invoked via * reflection) that implements the specified Method. If no such method can * be found, return <code>null</code>. * </p> * * @param method * The method that we wish to call * @return The accessible method */ public static Method getAccessibleMethod(Method method) { if (!isAccessible(method)) { return null; } // If the declaring class is public, we are done Class<?> cls = method.getDeclaringClass(); if (Modifier.isPublic(cls.getModifiers())) { return method; } String methodName = method.getName(); Class<?>[] parameterTypes = method.getParameterTypes(); // Check the implemented interfaces and subinterfaces method = getAccessibleMethodFromInterfaceNest(cls, methodName, parameterTypes); // Check the superclass chain if (method == null) { method = getAccessibleMethodFromSuperclass(cls, methodName, parameterTypes); } return method; }
From source file:com.clark.func.Functions.java
/** * <p>/*from w ww .j a v a 2s.co m*/ * Returns the desired Method much like <code>Class.getMethod</code>, * however it ensures that the returned Method is from a public class or * interface and not from an anonymous inner class. This means that the * Method is invokable and doesn't fall foul of Java bug <a * href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4071957" * >4071957</a>). * * <code><pre>Set set = Collections.unmodifiableSet(...); * Method method = ClassUtils.getPublicMethod(set.getClass(), "isEmpty", new Class[0]); * Object result = method.invoke(set, new Object[]);</pre></code> * </p> * * @param cls * the class to check, not null * @param methodName * the name of the method * @param parameterTypes * the list of parameters * @return the method * @throws NullPointerException * if the class is null * @throws SecurityException * if a a security violation occured * @throws NoSuchMethodException * if the method is not found in the given class or if the * metothod doen't conform with the requirements */ public static Method getPublicMethod(Class<?> cls, String methodName, Class<?> parameterTypes[]) throws SecurityException, NoSuchMethodException { Method declaredMethod = cls.getMethod(methodName, parameterTypes); if (Modifier.isPublic(declaredMethod.getDeclaringClass().getModifiers())) { return declaredMethod; } List<Class<?>> candidateClasses = new ArrayList<Class<?>>(); candidateClasses.addAll(getAllInterfaces(cls)); candidateClasses.addAll(getAllSuperclasses(cls)); for (Class<?> candidateClass : candidateClasses) { if (!Modifier.isPublic(candidateClass.getModifiers())) { continue; } Method candidateMethod; try { candidateMethod = candidateClass.getMethod(methodName, parameterTypes); } catch (NoSuchMethodException ex) { continue; } if (Modifier.isPublic(candidateMethod.getDeclaringClass().getModifiers())) { return candidateMethod; } } throw new NoSuchMethodException("Can't find a public method for " + methodName); }
From source file:com.clark.func.Functions.java
/** * <p>//w ww .jav a 2 s . com * Return an accessible method (that is, one that can be invoked via * reflection) by scanning through the superclasses. If no such method can * be found, return <code>null</code>. * </p> * * @param cls * Class to be checked * @param methodName * Method name of the method we wish to call * @param parameterTypes * The parameter type signatures * @return the accessible method or <code>null</code> if not found */ private static Method getAccessibleMethodFromSuperclass(Class<?> cls, String methodName, Class<?>... parameterTypes) { Class<?> parentClass = cls.getSuperclass(); while (parentClass != null) { if (Modifier.isPublic(parentClass.getModifiers())) { try { return parentClass.getMethod(methodName, parameterTypes); } catch (NoSuchMethodException e) { return null; } } parentClass = parentClass.getSuperclass(); } return null; }