Code:
import java.lang.reflect.*;
import java.util.HashMap;
import java.io.*;
/**
* This class is mainly intended to autopopulate hibernate POJOs.
* This requires POJOs to be generated with generics.
*
* LIST_SIZE - how many elements should be populated in list
* MAP_SIZE - how many elements should be in Map
* MAX_NESTING - In case of looping of mapping, we break at a certain depth as specified by this value.
* skip_id - in hibernate before persisting to db, id feild should be blank.
* For non-hibernate purpose keep this "false"
* id_feild - "oid" or "id" whatever is used by hibernate as db id. This is relevant if skip_id is set.
*
* @author Hari_Sujathan
*
*/
public class test {
public static int LIST_SIZE=5;
public static int MAP_SIZE=5;
public static int MAX_NESTING=3;
public static HashMap imports= new HashMap();
public static boolean skip_id=true;
public static String id_feild="id";
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
Class cls= Class.forName("com.hari.MyClass");//PLEASE FILL IN YOUR CLASS NAME HERE
if(cls.getName().indexOf(".")>0)
imports.put(cls.getName(),cls.getName());
String str=populateClass(cls,toLower(cls.getSimpleName()),"","","",0);
//System.out.println(str);
//System.out.println(imports.keySet());
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("src"+File.separator+cls.getSimpleName()+"_TestPopulate.java")));
Iterator itr=imports.keySet().iterator();
while(itr.hasNext()){
bw.write("import "+itr.next()+";\n");
}
bw.write("\n\n\t/**Test populated POJO - Hari Sujathan**/\n\n");
bw.write("public class "+cls.getSimpleName()+"_TestPopulate {\n");
bw.write("\t public "+cls.getSimpleName()+" populate"+cls.getSimpleName()+"(){\n\n");
bw.write(str);
bw.write("\nreturn "+toLower(cls.getSimpleName())+"_;\n");
bw.write("\n\t}\n\n}\n\n");
bw.close();
}
static String populateClass(Class cls,String name, String generic1, String generic2,String calledFeildName, int nesting) throws Exception{
StringBuffer sw= new StringBuffer();
if(generic1 ==null || generic1.length()==0){
if(cls.equals(Integer.class)){
if(name.equalsIgnoreCase(id_feild) && skip_id)
sw.append("\nInteger ").append(name).append("_").append(calledFeildName).append(" = null;");
else
sw.append("\nInteger ").append(name).append("_").append(calledFeildName).append(" = new Integer("+randomInt()+");");
return sw.toString();
}
if(cls.equals(Long.class)){
if(name.equalsIgnoreCase(id_feild) && skip_id)
sw.append("\nLong ").append(name).append("_").append(calledFeildName).append(" = null;");
else
sw.append("\nLong ").append(name).append("_").append(calledFeildName).append(" = new Long("+randomInt()+");");
return sw.toString();
}
if(cls.equals(String.class)){
sw.append("\nString ").append(name).append("_").append(calledFeildName).append(" = new String(\""+randomString()+"\");");
return sw.toString();
}
if(cls.equals(Boolean.class)){
sw.append("\nBoolean ").append(name).append("_").append(calledFeildName).append(" = new Boolean("+(randomInt()%2 == 0)+");");
return sw.toString();
}
if(cls.equals(Character.class)){
sw.append("\nCharacter ").append(name).append("_").append(calledFeildName).append(" = new Character((char)"+(char)randomInt()+");");
return sw.toString();
}
if(cls.equals(Timestamp.class)){
imports.put("java.sql.Timestamp","java.sql.Timestamp");
sw.append("\nTimestamp ").append(name).append("_").append(calledFeildName).append(" = new Timestamp("+randomInt()+");");
return sw.toString();
}
if(cls.equals(Date.class)){
imports.put("java.util.Date","java.util.Date");
sw.append("\nDate ").append(name).append("_").append(calledFeildName).append(" = new Date("+randomInt()+");");
return sw.toString();
}
if(cls.isEnum()){
if(cls.getName().indexOf(".")>0)
imports.put(cls.getName(),cls.getName());
int idx=(int) ((Math.random() *1000)% cls.getEnumConstants().length);
sw.append("\n").append(cls.getSimpleName()).append(" ").append(name).append("_").append(calledFeildName).append(" = ").append(cls.getSimpleName()).append(".").append(cls.getEnumConstants()[idx]).append(";\n");
return sw.toString();
}
}else{
if(cls.equals(ArrayList.class)){
sw.append("\nArrayList ").append(name).append("_").append(calledFeildName.toLowerCase()).append(" = new ArrayList();");
//if(generic1.indexOf(".")>0)
imports.put("java.util.ArrayList","java.util.ArrayList");
//
if(nesting > MAX_NESTING)
return sw.toString();
for(int i=0;i<LIST_SIZE;i++){
String listMemberName=Class.forName(generic1).getSimpleName().toLowerCase()+""+(i+1)+"_"+name.toLowerCase();
System.out.println(listMemberName);
String str=populateClass(Class.forName(generic1),listMemberName,"","",calledFeildName.toLowerCase(),nesting+1);
sw.append("\n").append(str).append("\n");
sw.append(name).append("_").append(calledFeildName.toLowerCase()).append(".add(").append(listMemberName).append("_").append(calledFeildName.toLowerCase()).append(");\n");
}
return sw.toString();
}
if(cls.equals(HashMap.class)){
sw.append("\nHashMap ").append(name).append("_").append(calledFeildName.toLowerCase()).append(" = new HashMap();");
//if(generic1.indexOf(".")>0)
imports.put("java.util.HashMap","java.util.HashMap");
//
if(nesting > MAX_NESTING)
return sw.toString();
for(int i=0;i<MAP_SIZE;i++){
String listMemberName1=Class.forName(generic1).getSimpleName().toLowerCase()+""+(i+1)+"_"+name.toLowerCase();
System.out.println(listMemberName1);
String str=populateClass(Class.forName(generic1),listMemberName1,"","",calledFeildName.toLowerCase(),nesting+1);
sw.append("\n").append(str).append("\n");
String listMemberName2=Class.forName(generic2).getSimpleName().toLowerCase()+""+(i+1)+"_"+name.toLowerCase();
System.out.println(listMemberName2);
String str2=populateClass(Class.forName(generic1),listMemberName2,"","",calledFeildName.toLowerCase(),nesting+1);
sw.append("\n").append(str2).append("\n");
sw.append(name).append("_").append(calledFeildName.toLowerCase()).append(".put(").append(listMemberName1).append("_").append(calledFeildName.toLowerCase()).append(",").append(listMemberName2).append("_").append(calledFeildName.toLowerCase()).append(");\n");
}
return sw.toString();
}
}
name=name+"_"+calledFeildName.toLowerCase();
if(cls.getName().indexOf(".")>0)
imports.put(cls.getName(),cls.getName());
sw.append(cls.getSimpleName()).append(" ").append(name).append(" = new ").append(cls.getSimpleName()).append("();");
Method[] methods=cls.getMethods();
for(int i=0;i<methods.length;i++){
//setter mothod is used to introspect each feild
if(methods[i].getName().startsWith("set")){
String feildName=toLower(methods[i].getName().substring(3));
//System.out.println(feildName);
String genericFeildType=methods[i].getGenericParameterTypes()[0].toString();
//System.out.println(genericFeildType);
String type=genericFeildType;
String generic=genericFeildType;
if(genericFeildType.indexOf("<")>0){
type=genericFeildType.substring(0,genericFeildType.indexOf("<"));
generic=genericFeildType.substring(genericFeildType.indexOf("<")+1,genericFeildType.indexOf(">"));
}else{
generic=type=genericFeildType=methods[i].getParameterTypes()[0].getName();
}
System.out.println(type+":"+generic+":"+generic.equals(type));
if(type.equals(generic)){
if(populatePrimitive(type,feildName,sw,name.toLowerCase())){
if(nesting > MAX_NESTING)
return sw.toString();
String childClz=populateClass(Class.forName(type),feildName,"","",name.toLowerCase(),nesting+1);
sw.append("\n").append(childClz).append("\n");
sw.append(name).append(".").append(methods[i].getName()).append("(").append(feildName).append("_").append(name.toLowerCase()).append(");");
}else{
sw.append("\n");
sw.append(name).append(".").append(methods[i].getName()).append("(").append(feildName).append("_").append(calledFeildName).append(");");
sw.append("\n");
}
}else if(type.indexOf("List")> 0 && type.indexOf("java.util")>=0){
String childLst=populateClass(Class.forName("java.util.ArrayList"),feildName,generic,"",name,nesting+1);
sw.append("\n").append(childLst).append("\n");
sw.append(name).append(".").append(methods[i].getName()).append("(").append(feildName).append("_").append(name.toLowerCase()).append(");");
}else if(type.indexOf("Map")> 0 && type.indexOf("java.util")>=0){
generic1=generic.substring(0,generic.indexOf(",")).trim();
generic2=generic.substring(generic.indexOf(",")+1).trim();
String childLst=populateClass(Class.forName("java.util.HashMap"),feildName,generic1,generic2,name,nesting+1);
sw.append("\n").append(childLst).append("\n");
sw.append(name).append(".").append(methods[i].getName()).append("(").append(feildName).append("_").append(name.toLowerCase()).append(");");
}
}
}
//System.out.println(sw.toString());
return sw.toString();
}
private static boolean populatePrimitive(String type, String feildName, StringBuffer sw,String calledFeildName) {
if(type.equals("int")){
if(calledFeildName.equalsIgnoreCase(id_feild) && skip_id)
sw.append("\nint ").append(feildName).append("_").append(calledFeildName).append(" = 0;");
else
sw.append("\nint ").append(feildName).append("_").append(calledFeildName).append(" = "+randomInt()+";");
return false;
}
if(type.equals("float")){
sw.append("\nfloat ").append(feildName).append("_").append(calledFeildName).append(" = (float)"+(float)(Math.random()*1000)+";");
return false;
}
if(type.equals("double")){
sw.append("\ndouble ").append(feildName).append("_").append(calledFeildName).append(" = "+(Math.random()*1000)+";");
return false;
}
if(type.equals("long")){
if(calledFeildName.equalsIgnoreCase(id_feild) && skip_id)
sw.append("\nlong ").append(feildName).append("_").append(calledFeildName).append(" = 0;");
else
sw.append("\nlong ").append(feildName).append("_").append(calledFeildName).append(" = "+randomInt()+";");
return false;
}
if(type.equals("short")){
sw.append("\nshort ").append(feildName).append("_").append(calledFeildName).append(" = (short)"+randomInt()+";");
return false;
}
if(type.equals("char")){
sw.append("\nchar ").append(feildName).append("_").append(calledFeildName).append(" = (char)"+randomInt()+";");
return false;
}
return true;
}
static String toLower(String str){
if(str!= null && str.length()>0)
return str.substring(0,1).toLowerCase()+str.substring(1);
return str;
}
static int randomInt(){
int ret= (int)(Math.random() * Integer.MAX_VALUE) % Short.MAX_VALUE;
while(ret==0){
ret= (int)(Math.random() * Integer.MAX_VALUE) % Short.MAX_VALUE;
}
return ret;
}
static String randomString(){
int strLen= (int)(Math.random() * Short.MAX_VALUE % 15);
while(strLen==0)
strLen= (int)(Math.random() * Short.MAX_VALUE % 15);
StringBuffer sb= new StringBuffer();
for(int i=0;i<strLen;i++){
char ch=(char) ('a'+((char)(Math.random() * 1000 % 26)));
sb.append(ch);
}
return sb.toString();
}
}
Copy this test.java to your hibernate project, edit the first line of main method: with the class name of the POJO that needs to be testpopulated. It creates file "src\<ClassName>_TestPopulate.java" with java code.
Note: Only few java types are covered like String, primitives, wrapper, enum, List, Map.
java.util.Set is not there because I used only List and Map in my project. This works for my purpose. variable naming convention of generated code is pretty ugly with very long names(it can be modified). If need to be expanded please email:
hari_sujathan@yahoo.com.
Also if criteria filtering at UI needs to be done without hitting db, I have written few classes for that as well (uses commons API and reflection).
- Hari
To experience the thrill of not working you have to work in TCS tidel park, Chennai 11th floor. 1000 people are working in 3X3 feet cubes..