5af3c5ea6c98860e979ed268aa4a41fcb601dcce
[iot2.git] / iotjava / iotpolicy / IoTCompiler.java
1 package iotpolicy;
2
3 import java_cup.runtime.ComplexSymbolFactory;
4 import java_cup.runtime.ScannerBuffer;
5 import java.io.*;
6 import java.util.Arrays;
7 import java.util.ArrayList;
8 import java.util.Collection;
9 import java.util.Collections;
10 import java.util.HashMap;
11 import java.util.HashSet;
12 import java.util.Iterator;
13 import java.util.List;
14 import java.util.Map;
15 import java.util.Set;
16
17 import iotpolicy.parser.Lexer;
18 import iotpolicy.parser.Parser;
19 import iotpolicy.tree.ParseNode;
20 import iotpolicy.tree.ParseNodeVector;
21 import iotpolicy.tree.ParseTreeHandler;
22 import iotpolicy.tree.Declaration;
23 import iotpolicy.tree.DeclarationHandler;
24 import iotpolicy.tree.CapabilityDecl;
25 import iotpolicy.tree.InterfaceDecl;
26 import iotpolicy.tree.RequiresDecl;
27 import iotpolicy.tree.EnumDecl;
28 import iotpolicy.tree.StructDecl;
29
30 import iotrmi.Java.IoTRMITypes;
31
32
33 /** Class IoTCompiler is the main interface/stub compiler for
34  *  files generation. This class calls helper classes
35  *  such as Parser, Lexer, InterfaceDecl, CapabilityDecl,
36  *  RequiresDecl, ParseTreeHandler, etc.
37  *
38  * @author      Rahmadi Trimananda <rahmadi.trimananda @ uci.edu>
39  * @version     1.0
40  * @since       2016-09-22
41  */
42 public class IoTCompiler {
43
44         /**
45          * Class properties
46          */
47         // Maps multiple interfaces to multiple objects of ParseTreeHandler
48         private Map<String,ParseTreeHandler> mapIntfacePTH;
49         private Map<String,DeclarationHandler> mapIntDeclHand;
50         private Map<String,Map<String,Set<String>>> mapInt2NewInts;
51         // Data structure to store our types (primitives and non-primitives) for compilation
52         private Map<String,String> mapPrimitives;
53         private Map<String,String> mapNonPrimitivesJava;
54         private Map<String,String> mapNonPrimitivesCplus;
55         // Other data structures
56         private Map<String,Integer> mapIntfaceObjId;            // Maps interface name to object Id
57         private Map<String,Integer> mapNewIntfaceObjId;         // Maps new interface name to its object Id (keep track of stubs)
58         private PrintWriter pw;
59         private String dir;
60         private String subdir;
61
62
63         /**
64          * Class constants
65          */
66         private final static String OUTPUT_DIRECTORY = "output_files";
67
68         private enum ParamCategory {
69
70                 PRIMITIVES,             // All the primitive types, e.g. byte, short, int, long, etc.
71                 NONPRIMITIVES,  // Non-primitive types, e.g. Set, Map, List, etc.
72                 ENUM,                   // Enum type
73                 STRUCT,                 // Struct type
74                 USERDEFINED             // Assumed as driver classes
75         }
76
77
78         /**
79          * Class constructors
80          */
81         public IoTCompiler() {
82
83                 mapIntfacePTH = new HashMap<String,ParseTreeHandler>();
84                 mapIntDeclHand = new HashMap<String,DeclarationHandler>();
85                 mapInt2NewInts = new HashMap<String,Map<String,Set<String>>>();
86                 mapIntfaceObjId = new HashMap<String,Integer>();
87                 mapNewIntfaceObjId = new HashMap<String,Integer>();
88                 mapPrimitives = new HashMap<String,String>();
89                         arraysToMap(mapPrimitives, IoTRMITypes.primitivesJava, IoTRMITypes.primitivesCplus);
90                 mapNonPrimitivesJava = new HashMap<String,String>();
91                         arraysToMap(mapNonPrimitivesJava, IoTRMITypes.nonPrimitivesJava, IoTRMITypes.nonPrimitiveJavaLibs);
92                 mapNonPrimitivesCplus = new HashMap<String,String>();
93                         arraysToMap(mapNonPrimitivesCplus, IoTRMITypes.nonPrimitivesJava, IoTRMITypes.nonPrimitivesCplus);
94                 pw = null;
95                 dir = OUTPUT_DIRECTORY;
96                 subdir = null;
97         }
98
99
100         /**
101          * setDataStructures() sets parse tree and other data structures based on policy files.
102          * <p>
103          * It also generates parse tree (ParseTreeHandler) and
104          * copies useful information from parse tree into
105          * InterfaceDecl, CapabilityDecl, and RequiresDecl 
106          * data structures.
107          * Additionally, the data structure handles are
108          * returned from tree-parsing for further process.
109          */
110         public void setDataStructures(String origInt, ParseNode pnPol, ParseNode pnReq) {
111
112                 ParseTreeHandler ptHandler = new ParseTreeHandler(origInt, pnPol, pnReq);
113                 DeclarationHandler decHandler = new DeclarationHandler();
114                 // Process ParseNode and generate Declaration objects
115                 // Interface
116                 ptHandler.processInterfaceDecl();
117                 InterfaceDecl intDecl = ptHandler.getInterfaceDecl();
118                 decHandler.addInterfaceDecl(origInt, intDecl);
119                 // Capabilities
120                 ptHandler.processCapabilityDecl();
121                 CapabilityDecl capDecl = ptHandler.getCapabilityDecl();
122                 decHandler.addCapabilityDecl(origInt, capDecl);
123                 // Requires
124                 ptHandler.processRequiresDecl();
125                 RequiresDecl reqDecl = ptHandler.getRequiresDecl();
126                 decHandler.addRequiresDecl(origInt, reqDecl);
127                 // Enumeration
128                 ptHandler.processEnumDecl();
129                 EnumDecl enumDecl = ptHandler.getEnumDecl();
130                 decHandler.addEnumDecl(origInt, enumDecl);
131                 // Struct
132                 ptHandler.processStructDecl();
133                 StructDecl structDecl = ptHandler.getStructDecl();
134                 decHandler.addStructDecl(origInt, structDecl);
135
136                 mapIntfacePTH.put(origInt, ptHandler);
137                 mapIntDeclHand.put(origInt, decHandler);
138                 // Set object Id counter to 0 for each interface
139                 mapIntfaceObjId.put(origInt, new Integer(0));
140         }
141
142
143         /**
144          * getMethodsForIntface() reads for methods in the data structure
145          * <p>
146          * It is going to give list of methods for a certain interface
147          *              based on the declaration of capabilities.
148          */
149         public void getMethodsForIntface(String origInt) {
150
151                 ParseTreeHandler ptHandler = mapIntfacePTH.get(origInt);
152                 Map<String,Set<String>> mapNewIntMethods = new HashMap<String,Set<String>>();
153                 // Get set of new interfaces, e.g. CameraWithCaptureAndData
154                 // Generate this new interface with all the methods it needs
155                 //              from different capabilities it declares
156                 DeclarationHandler decHandler = mapIntDeclHand.get(origInt);
157                 RequiresDecl reqDecl = (RequiresDecl) decHandler.getRequiresDecl(origInt);
158                 Set<String> setIntfaces = reqDecl.getInterfaces();
159                 for (String strInt : setIntfaces) {
160
161                         // Initialize a set of methods
162                         Set<String> setMethods = new HashSet<String>();
163                         // Get list of capabilities, e.g. ImageCapture, VideoRecording, etc.
164                         List<String> listCapab = reqDecl.getCapabList(strInt);
165                         for (String strCap : listCapab) {
166
167                                 // Get list of methods for each capability
168                                 CapabilityDecl capDecl = (CapabilityDecl) decHandler.getCapabilityDecl(origInt);
169                                 List<String> listCapabMeth = capDecl.getMethods(strCap);
170                                 for (String strMeth : listCapabMeth) {
171
172                                         // Add methods into setMethods
173                                         // This is to also handle redundancies (say two capabilities
174                                         //              share the same methods)
175                                         setMethods.add(strMeth);
176                                 }
177                         }
178                         // Add interface and methods information into map
179                         mapNewIntMethods.put(strInt, setMethods);
180                 }
181                 // Map the map of interface-methods to the original interface
182                 mapInt2NewInts.put(origInt, mapNewIntMethods);
183         }
184
185
186         /**
187          * HELPER: writeMethodJavaLocalInterface() writes the method of the local interface
188          */
189         private void writeMethodJavaLocalInterface(Collection<String> methods, InterfaceDecl intDecl) {
190
191                 for (String method : methods) {
192
193                         List<String> methParams = intDecl.getMethodParams(method);
194                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
195                         print("public " + intDecl.getMethodType(method) + " " +
196                                 intDecl.getMethodId(method) + "(");
197                         for (int i = 0; i < methParams.size(); i++) {
198                                 // Check for params with driver class types and exchange it 
199                                 //              with its remote interface
200                                 String paramType = checkAndGetParamClass(methPrmTypes.get(i));
201                                 print(paramType + " " + methParams.get(i));
202                                 // Check if this is the last element (don't print a comma)
203                                 if (i != methParams.size() - 1) {
204                                         print(", ");
205                                 }
206                         }
207                         println(");");
208                 }
209         }
210
211
212         /**
213          * HELPER: writeMethodJavaInterface() writes the method of the interface
214          */
215         private void writeMethodJavaInterface(Collection<String> methods, InterfaceDecl intDecl) {
216
217                 for (String method : methods) {
218
219                         List<String> methParams = intDecl.getMethodParams(method);
220                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
221                         print("public " + intDecl.getMethodType(method) + " " +
222                                 intDecl.getMethodId(method) + "(");
223                         for (int i = 0; i < methParams.size(); i++) {
224                                 // Check for params with driver class types and exchange it 
225                                 //              with its remote interface
226                                 String paramType = methPrmTypes.get(i);
227                                 print(paramType + " " + methParams.get(i));
228                                 // Check if this is the last element (don't print a comma)
229                                 if (i != methParams.size() - 1) {
230                                         print(", ");
231                                 }
232                         }
233                         println(");");
234                 }
235         }
236
237
238         /**
239          * HELPER: generateEnumJava() writes the enumeration declaration
240          */
241         private void generateEnumJava() throws IOException {
242
243                 // Create a new directory
244                 createDirectory(dir);
245                 for (String intface : mapIntfacePTH.keySet()) {
246                         // Get the right EnumDecl
247                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
248                         EnumDecl enumDecl = (EnumDecl) decHandler.getEnumDecl(intface);
249                         Set<String> enumTypes = enumDecl.getEnumDeclarations();
250                         // Iterate over enum declarations
251                         for (String enType : enumTypes) {
252                                 // Open a new file to write into
253                                 FileWriter fw = new FileWriter(dir + "/" + enType + ".java");
254                                 pw = new PrintWriter(new BufferedWriter(fw));
255                                 println("public enum " + enType + " {");
256                                 List<String> enumMembers = enumDecl.getMembers(enType);
257                                 for (int i = 0; i < enumMembers.size(); i++) {
258
259                                         String member = enumMembers.get(i);
260                                         print(member);
261                                         // Check if this is the last element (don't print a comma)
262                                         if (i != enumMembers.size() - 1)
263                                                 println(",");
264                                         else
265                                                 println("");
266                                 }
267                                 println("}\n");
268                                 pw.close();
269                                 System.out.println("IoTCompiler: Generated enum class " + enType + ".java...");
270                         }
271                 }
272         }
273
274
275         /**
276          * HELPER: generateStructJava() writes the struct declaration
277          */
278         private void generateStructJava() throws IOException {
279
280                 // Create a new directory
281                 createDirectory(dir);
282                 for (String intface : mapIntfacePTH.keySet()) {
283                         // Get the right StructDecl
284                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
285                         StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
286                         List<String> structTypes = structDecl.getStructTypes();
287                         // Iterate over enum declarations
288                         for (String stType : structTypes) {
289                                 // Open a new file to write into
290                                 FileWriter fw = new FileWriter(dir + "/" + stType + ".java");
291                                 pw = new PrintWriter(new BufferedWriter(fw));
292                                 println("public class " + stType + " {");
293                                 List<String> structMemberTypes = structDecl.getMemberTypes(stType);
294                                 List<String> structMembers = structDecl.getMembers(stType);
295                                 for (int i = 0; i < structMembers.size(); i++) {
296
297                                         String memberType = structMemberTypes.get(i);
298                                         String member = structMembers.get(i);
299                                         println("public static " + memberType + " " + member + ";");
300                                 }
301                                 println("}\n");
302                                 pw.close();
303                                 System.out.println("IoTCompiler: Generated struct class " + stType + ".java...");
304                         }
305                 }
306         }
307
308
309         /**
310          * generateJavaLocalInterface() writes the local interface and provides type-checking.
311          * <p>
312          * It needs to rewrite and exchange USERDEFINED types in input parameters of stub
313          * and original interfaces, e.g. exchange Camera and CameraWithVideoAndRecording.
314          * The local interface has to be the input parameter for the stub and the stub 
315          * interface has to be the input parameter for the local class.
316          */
317         public void generateJavaLocalInterfaces() throws IOException {
318
319                 // Create a new directory
320                 createDirectory(dir);
321                 for (String intface : mapIntfacePTH.keySet()) {
322                         // Open a new file to write into
323                         FileWriter fw = new FileWriter(dir + "/" + intface + ".java");
324                         pw = new PrintWriter(new BufferedWriter(fw));
325                         // Pass in set of methods and get import classes
326                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
327                         InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
328                         List<String> methods = intDecl.getMethods();
329                         Set<String> importClasses = getImportClasses(methods, intDecl);
330                         List<String> stdImportClasses = getStandardJavaIntfaceImportClasses();
331                         List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
332                         printImportStatements(allImportClasses);
333                         // Write interface header
334                         println("");
335                         println("public interface " + intface + " {");
336                         // Write methods
337                         writeMethodJavaLocalInterface(methods, intDecl);
338                         println("}");
339                         pw.close();
340                         System.out.println("IoTCompiler: Generated local interface " + intface + ".java...");
341                 }
342         }
343
344
345         /**
346          * generateJavaInterfaces() generate stub interfaces based on the methods list in Java
347          */
348         public void generateJavaInterfaces() throws IOException {
349
350                 // Create a new directory
351                 String path = createDirectories(dir, subdir);
352                 for (String intface : mapIntfacePTH.keySet()) {
353
354                         Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
355                         for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
356
357                                 // Open a new file to write into
358                                 String newIntface = intMeth.getKey();
359                                 FileWriter fw = new FileWriter(path + "/" + newIntface + ".java");
360                                 pw = new PrintWriter(new BufferedWriter(fw));
361                                 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
362                                 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
363                                 // Pass in set of methods and get import classes
364                                 List<String> methods = intDecl.getMethods();
365                                 Set<String> importClasses = getImportClasses(methods, intDecl);
366                                 List<String> stdImportClasses = getStandardJavaIntfaceImportClasses();
367                                 List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
368                                 printImportStatements(allImportClasses);
369                                 // Write interface header
370                                 println("");
371                                 println("public interface " + newIntface + " {\n");
372                                 // Write methods
373                                 writeMethodJavaInterface(methods, intDecl);
374                                 println("}");
375                                 pw.close();
376                                 System.out.println("IoTCompiler: Generated interface " + newIntface + ".java...");
377                         }
378                 }
379         }
380
381
382         /**
383          * HELPER: writePropertiesJavaPermission() writes the permission in properties
384          */
385         private void writePropertiesJavaPermission(String intface, InterfaceDecl intDecl) {
386
387                 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
388                 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
389                         String newIntface = intMeth.getKey();
390                         int newObjectId = getNewIntfaceObjectId(newIntface);
391                         println("private final static int object" + newObjectId + "Id = " + 
392                                 newObjectId + ";\t//" + newIntface);
393                         Set<String> methodIds = intMeth.getValue();
394                         print("private static Integer[] object" + newObjectId + "Permission = { ");
395                         int i = 0;
396                         for (String methodId : methodIds) {
397                                 int methodNumId = intDecl.getMethodNumId(methodId);
398                                 print(Integer.toString(methodNumId));
399                                 // Check if this is the last element (don't print a comma)
400                                 if (i != methodIds.size() - 1) {
401                                         print(", ");
402                                 }
403                                 i++;
404                         }
405                         println(" };");
406                         println("private List<Integer> set" + newObjectId + "Allowed;");
407                 }
408         }
409
410
411         /**
412          * HELPER: writePropertiesJavaStub() writes the properties of the stub class
413          */
414         private void writePropertiesJavaStub(String intface, String newIntface, boolean callbackExist, Set<String> callbackClasses) {
415
416                 println("private IoTRMICall rmiCall;");
417                 println("private String address;");
418                 println("private int[] ports;\n");
419                 // Get the object Id
420                 Integer objId = mapIntfaceObjId.get(intface);
421                 println("private final static int objectId = " + objId + ";");
422                 mapNewIntfaceObjId.put(newIntface, objId);
423                 mapIntfaceObjId.put(intface, objId++);
424                 if (callbackExist) {
425                 // We assume that each class only has one callback interface for now
426                         Iterator it = callbackClasses.iterator();
427                         String callbackType = (String) it.next();
428                         println("// Callback properties");
429                         println("private IoTRMIObject rmiObj;");
430                         println("List<" + callbackType + "> listCallbackObj;");
431                         println("private static int objIdCnt = 0;");
432                         // Generate permission stuff for callback stubs
433                         DeclarationHandler decHandler = mapIntDeclHand.get(callbackType);
434                         InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(callbackType);
435                         writePropertiesJavaPermission(callbackType, intDecl);
436                 }
437                 println("\n");
438         }
439
440
441         /**
442          * HELPER: writeConstructorJavaPermission() writes the permission in constructor
443          */
444         private void writeConstructorJavaPermission(String intface) {
445
446                 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
447                 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
448                         String newIntface = intMeth.getKey();
449                         int newObjectId = getNewIntfaceObjectId(newIntface);
450                         println("set" + newObjectId + "Allowed = Arrays.asList(object" + newObjectId +"Permission);");
451                 }
452         }
453
454
455         /**
456          * HELPER: writeConstructorJavaStub() writes the constructor of the stub class
457          */
458         private void writeConstructorJavaStub(String intface, String newStubClass, boolean callbackExist, Set<String> callbackClasses) {
459
460                 println("public " + newStubClass + "(int _port, String _address, int _rev, int[] _ports) throws Exception {");
461                 println("address = _address;");
462                 println("ports = _ports;");
463                 println("rmiCall = new IoTRMICall(_port, _address, _rev);");
464                 if (callbackExist) {
465                         Iterator it = callbackClasses.iterator();
466                         String callbackType = (String) it.next();
467                         writeConstructorJavaPermission(intface);
468                         println("listCallbackObj = new ArrayList<" + callbackType + ">();");
469                         println("___initCallBack();");
470                 }
471                 println("}\n");
472         }
473
474
475         /**
476          * HELPER: writeJavaMethodCallbackPermission() writes permission checks in stub for callbacks
477          */
478         private void writeJavaMethodCallbackPermission(String intface) {
479
480                 println("int methodId = IoTRMIObject.getMethodId(method);");
481                 // Get all the different stubs
482                 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
483                 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
484                         String newIntface = intMeth.getKey();
485                         int newObjectId = getNewIntfaceObjectId(newIntface);
486                         println("if (!set" + newObjectId + "Allowed.contains(methodId)) {");
487                         println("throw new Error(\"Callback object for " + intface + " is not allowed to access method: \" + methodId);");
488                         println("}");
489                 }
490         }
491
492
493         /**
494          * HELPER: writeInitCallbackJavaStub() writes callback initialization in stub
495          */
496         private void writeInitCallbackJavaStub(String intface, InterfaceDecl intDecl) {
497
498                 println("public void ___initCallBack() {");
499                 // Generate main thread for callbacks
500                 println("Thread thread = new Thread() {");
501                 println("public void run() {");
502                 println("try {");
503                 println("rmiObj = new IoTRMIObject(ports[0]);");
504                 println("while (true) {");
505                 println("byte[] method = rmiObj.getMethodBytes();");
506                 writeJavaMethodCallbackPermission(intface);
507                 println("int objId = IoTRMIObject.getObjectId(method);");
508                 println(intface + "_CallbackSkeleton skel = (" + intface + "_CallbackSkeleton) listCallbackObj.get(objId);");
509                 println("if (skel != null) {");
510                 println("skel.invokeMethod(rmiObj);");
511                 println("} else {");
512                 println("throw new Error(\"" + intface + ": Object with Id \" + objId + \" not found!\");");
513                 println("}");
514                 println("}");
515                 println("} catch (Exception ex) {");
516                 println("ex.printStackTrace();");
517                 println("throw new Error(\"Error instantiating class " + intface + "_CallbackSkeleton!\");");
518                 println("}");
519                 println("}");
520                 println("};");
521                 println("thread.start();\n");
522                 // Generate info sending part
523                 String method = "___initCallBack()";
524                 println("int methodId = " + intDecl.getHelperMethodNumId(method) + ";");
525                 println("Class<?> retType = void.class;");
526                 println("Class<?>[] paramCls = new Class<?>[] { int.class, String.class, int.class };");
527                 println("Object[] paramObj = new Object[] { ports[0], address, 0 };");
528                 println("rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
529                 println("}\n");
530         }
531
532
533         /**
534          * HELPER: checkAndWriteEnumTypeJavaStub() writes the enum type (convert from enum to int)
535          */
536         private void checkAndWriteEnumTypeJavaStub(List<String> methParams, List<String> methPrmTypes) {
537
538                 // Iterate and find enum declarations
539                 for (int i = 0; i < methParams.size(); i++) {
540                         String paramType = methPrmTypes.get(i);
541                         String param = methParams.get(i);
542                         String simpleType = getSimpleType(paramType);
543                         if (isEnumClass(simpleType)) {
544                         // Check if this is enum type
545                                 if (isArray(param)) {   // An array
546                                         println("int len" + i + " = " + param + ".length;");
547                                         println("int paramEnum" + i + "[] = new int[len];");
548                                         println("for (int i = 0; i < len" + i + "; i++) {");
549                                         println("paramEnum" + i + "[i] = " + param + "[i].ordinal();");
550                                         println("}");
551                                 } else if (isList(paramType)) { // A list
552                                         println("int len" + i + " = " + param + ".size();");
553                                         println("int paramEnum" + i + "[] = new int[len];");
554                                         println("for (int i = 0; i < len" + i + "; i++) {");
555                                         println("paramEnum" + i + "[i] = " + param + ".get(i).ordinal();");
556                                         println("}");
557                                 } else {        // Just one element
558                                         println("int paramEnum" + i + "[] = new int[1];");
559                                         println("paramEnum" + i + "[0] = " + param + ".ordinal();");
560                                 }
561                         }
562                 }
563         }
564
565
566         /**
567          * HELPER: checkAndWriteEnumRetTypeJavaStub() writes the enum return type (convert from enum to int)
568          */
569         private void checkAndWriteEnumRetTypeJavaStub(String retType) {
570
571                 // Strips off array "[]" for return type
572                 String pureType = getSimpleArrayType(getSimpleType(retType));
573                 // Take the inner type of generic
574                 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
575                         pureType = getTypeOfGeneric(retType)[0];
576                 if (isEnumClass(pureType)) {
577                 // Check if this is enum type
578                         // Enum decoder
579                         println("int[] retEnum = (int[]) retObj;");
580                         println(pureType + "[] enumVals = " + pureType + ".values();");
581                         if (isArray(retType)) {                 // An array
582                                 println("int retLen = retEnum.length;");
583                                 println(pureType + "[] enumRetVal = new " + pureType + "[retLen];");
584                                 println("for (int i = 0; i < retLen; i++) {");
585                                 println("enumRetVal[i] = enumVals[retEnum[i]];");
586                                 println("}");
587                         } else if (isList(retType)) {   // A list
588                                 println("int retLen = retEnum.length;");
589                                 println("List<" + pureType + "> enumRetVal = new ArrayList<" + pureType + ">();");
590                                 println("for (int i = 0; i < retLen; i++) {");
591                                 println("enumRetVal.add(enumVals[retEnum[i]]);");
592                                 println("}");
593                         } else {        // Just one element
594                                 println(pureType + " enumRetVal = enumVals[retEnum[0]];");
595                         }
596                         println("return enumRetVal;");
597                 }
598         }
599
600
601         /**
602          * HELPER: checkAndWriteStructSetupJavaStub() writes the struct type setup
603          */
604         private void checkAndWriteStructSetupJavaStub(List<String> methParams, List<String> methPrmTypes, 
605                         InterfaceDecl intDecl, String method) {
606                 
607                 // Iterate and find struct declarations
608                 for (int i = 0; i < methParams.size(); i++) {
609                         String paramType = methPrmTypes.get(i);
610                         String param = methParams.get(i);
611                         String simpleType = getSimpleType(paramType);
612                         if (isStructClass(simpleType)) {
613                         // Check if this is enum type
614                                 int methodNumId = intDecl.getMethodNumId(method);
615                                 String helperMethod = methodNumId + "struct" + i;
616                                 println("int methodIdStruct" + i + " = " + intDecl.getHelperMethodNumId(helperMethod) + ";");
617                                 println("Class<?> retTypeStruct" + i + " = void.class;");
618                                 println("Class<?>[] paramClsStruct" + i + " = new Class<?>[] { int.class };");
619                                 if (isArray(param)) {   // An array
620                                         println("Object[] paramObjStruct" + i + " = new Object[] { " + getSimpleArrayType(param) + ".length };");
621                                 } else if (isList(paramType)) { // A list
622                                         println("Object[] paramObjStruct" + i + " = new Object[] { " + getSimpleArrayType(param) + ".size() };");
623                                 } else {        // Just one element
624                                         println("Object[] paramObjStruct" + i + " = new Object[] { new Integer(1) };");
625                                 }
626                                 println("rmiCall.remoteCall(objectId, methodIdStruct" + i + 
627                                                 ", retTypeStruct" + i + ", null, paramClsStruct" + i + 
628                                                 ", paramObjStruct" + i + ");\n");
629                         }
630                 }
631         }
632
633
634         /**
635          * HELPER: isStructPresent() checks presence of struct
636          */
637         private boolean isStructPresent(List<String> methParams, List<String> methPrmTypes) {
638
639                 // Iterate and find enum declarations
640                 for (int i = 0; i < methParams.size(); i++) {
641                         String paramType = methPrmTypes.get(i);
642                         String param = methParams.get(i);
643                         String simpleType = getSimpleType(paramType);
644                         if (isStructClass(simpleType))
645                                 return true;
646                 }
647                 return false;
648         }
649
650
651         /**
652          * HELPER: writeLengthStructParamClassJavaStub() writes lengths of parameters
653          */
654         private void writeLengthStructParamClassJavaStub(List<String> methParams, List<String> methPrmTypes) {
655
656                 // Iterate and find struct declarations - count number of params
657                 for (int i = 0; i < methParams.size(); i++) {
658                         String paramType = methPrmTypes.get(i);
659                         String param = methParams.get(i);
660                         String simpleType = getGenericType(paramType);
661                         if (isStructClass(simpleType)) {
662                                 int members = getNumOfMembers(simpleType);
663                                 if (isArray(param)) {                   // An array
664                                         String structLen = param + ".length";
665                                         print(members + "*" + structLen);
666                                 } else if (isList(paramType)) { // A list
667                                         String structLen = param + ".size()";
668                                         print(members + "*" + structLen);
669                                 } else
670                                         print(Integer.toString(members));
671                         } else
672                                 print("1");
673                         if (i != methParams.size() - 1) {
674                                 print("+");
675                         }
676                 }
677         }
678
679
680         /**
681          * HELPER: writeStructMembersJavaStub() writes parameters of struct
682          */
683         private void writeStructMembersJavaStub(String simpleType, String paramType, String param) {
684
685                 // Get the struct declaration for this struct and generate initialization code
686                 StructDecl structDecl = getStructDecl(simpleType);
687                 List<String> memTypes = structDecl.getMemberTypes(simpleType);
688                 List<String> members = structDecl.getMembers(simpleType);
689                 if (isArray(param)) {                   // An array
690                         println("for(int i = 0; i < " + param + ".length; i++) {");
691                 } else if (isList(paramType)) { // A list
692                         println("for(int i = 0; i < " + param + ".size(); i++) {");
693                 }
694                 if (isArrayOrList(param, paramType)) {  // An array or list
695                         for (int i = 0; i < members.size(); i++) {
696                                 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
697                                 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
698                                 print("paramObj[pos++] = " + param + "[i].");
699                                 print(getSimpleIdentifier(members.get(i)));
700                                 println(";");
701                         }
702                         println("}");
703                 } else {        // Just one struct element
704                         for (int i = 0; i < members.size(); i++) {
705                                 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
706                                 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
707                                 print("paramObj[pos++] = " + param + ".");
708                                 print(getSimpleIdentifier(members.get(i)));
709                                 println(";");
710                         }
711                 }
712         }
713
714
715         /**
716          * HELPER: writeStructParamClassJavaStub() writes parameters if struct is present
717          */
718         private void writeStructParamClassJavaStub(List<String> methParams, List<String> methPrmTypes) {
719
720                 print("int paramLen = ");
721                 writeLengthStructParamClassJavaStub(methParams, methPrmTypes);
722                 println(";");
723                 println("Object[] paramObj = new Object[paramLen];");
724                 println("Class<?>[] paramCls = new Class<?>[paramLen];");
725                 println("int pos = 0;");
726                 // Iterate again over the parameters
727                 for (int i = 0; i < methParams.size(); i++) {
728                         String paramType = methPrmTypes.get(i);
729                         String param = methParams.get(i);
730                         String simpleType = getGenericType(paramType);
731                         if (isStructClass(simpleType)) {
732                                 writeStructMembersJavaStub(simpleType, paramType, param);
733                         } else {
734                                 String prmType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
735                                 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
736                                 print("paramObj[pos++] = ");
737                                 print(getEnumParam(methPrmTypes.get(i), getSimpleIdentifier(methParams.get(i)), i));
738                                 println(";");
739                         }
740                 }
741                 
742         }
743
744
745         /**
746          * HELPER: writeStructRetMembersJavaStub() writes parameters of struct for return statement
747          */
748         private void writeStructRetMembersJavaStub(String simpleType, String retType) {
749
750                 // Get the struct declaration for this struct and generate initialization code
751                 StructDecl structDecl = getStructDecl(simpleType);
752                 List<String> memTypes = structDecl.getMemberTypes(simpleType);
753                 List<String> members = structDecl.getMembers(simpleType);
754                 if (isArrayOrList(retType, retType)) {  // An array or list
755                         println("for(int i = 0; i < retLen; i++) {");
756                 }
757                 if (isArray(retType)) { // An array
758                         for (int i = 0; i < members.size(); i++) {
759                                 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
760                                 print("structRet[i]." + getSimpleIdentifier(members.get(i)));
761                                 println(" = (" + getSimpleType(getEnumType(prmType)) + ") retObj[retObjPos++];");
762                         }
763                         println("}");
764                 } else if (isList(retType)) {   // A list
765                         println(simpleType + " structRetMem = new " + simpleType + "();");
766                         for (int i = 0; i < members.size(); i++) {
767                                 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
768                                 print("structRetMem." + getSimpleIdentifier(members.get(i)));
769                                 println(" = (" + getSimpleType(getEnumType(prmType)) + ") retObj[retObjPos++];");
770                         }
771                         println("structRet.add(structRetMem);");
772                         println("}");
773                 } else {        // Just one struct element
774                         for (int i = 0; i < members.size(); i++) {
775                                 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
776                                 print("structRet." + getSimpleIdentifier(members.get(i)));
777                                 println(" = (" + getSimpleType(getEnumType(prmType)) + ") retObj[retObjPos++];");
778                         }
779                 }
780                 println("return structRet;");
781         }
782
783
784         /**
785          * HELPER: writeStructReturnJavaStub() writes parameters if struct is present for return statement
786          */
787         private void writeStructReturnJavaStub(String simpleType, String retType) {
788
789                 // Handle the returned struct!!!
790                 println("Object retLenObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
791                 // Minimum retLen is 1 if this is a single struct object
792                 println("int retLen = (int) retLenObj;");
793                 int numMem = getNumOfMembers(simpleType);
794                 println("Class<?>[] retCls = new Class<?>[" + numMem + "*retLen];");
795                 println("Class<?>[] retClsVal = new Class<?>[" + numMem + "*retLen];");
796                 println("int retPos = 0;");
797                 // Get the struct declaration for this struct and generate initialization code
798                 StructDecl structDecl = getStructDecl(simpleType);
799                 List<String> memTypes = structDecl.getMemberTypes(simpleType);
800                 List<String> members = structDecl.getMembers(simpleType);
801                 if (isArrayOrList(retType, retType)) {  // An array or list
802                         println("for(int i = 0; i < retLen; i++) {");
803                         for (int i = 0; i < members.size(); i++) {
804                                 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
805                                 println("retCls[retPos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
806                                 println("retClsVal[retPos++] = null;");
807                         }
808                         println("}");
809                 } else {        // Just one struct element
810                         for (int i = 0; i < members.size(); i++) {
811                                 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
812                                 println("retCls[retPos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
813                                 println("retClsVal[retPos++] = null;");
814                         }
815                 }
816                 println("Object[] retObj = rmiCall.getStructObjects(retCls, retClsVal);");
817                 if (isArray(retType)) {                 // An array
818                         println(simpleType + "[] structRet = new " + simpleType + "[retLen];");
819                         println("for(int i = 0; i < retLen; i++) {");
820                         println("structRet[i] = new " + simpleType + "();");
821                         println("}");
822                 } else if (isList(retType)) {   // A list
823                         println("List<" + simpleType + "> structRet = new ArrayList<" + simpleType + ">();");
824                 } else
825                         println(simpleType + " structRet = new " + simpleType + "();");
826                 println("int retObjPos = 0;");
827                 writeStructRetMembersJavaStub(simpleType, retType);
828         }
829
830
831         /**
832          * HELPER: writeStdMethodBodyJavaStub() writes the standard method body in the stub class
833          */
834         private void writeStdMethodBodyJavaStub(InterfaceDecl intDecl, List<String> methParams,
835                         List<String> methPrmTypes, String method) {
836
837                 checkAndWriteStructSetupJavaStub(methParams, methPrmTypes, intDecl, method);
838                 println("int methodId = " + intDecl.getMethodNumId(method) + ";");
839                 String retType = intDecl.getMethodType(method);
840                 println("Class<?> retType = " + getSimpleType(getStructType(getEnumType(retType))) + ".class;");
841                 checkAndWriteEnumTypeJavaStub(methParams, methPrmTypes);
842                 // Generate array of parameter types
843                 if (isStructPresent(methParams, methPrmTypes)) {
844                         writeStructParamClassJavaStub(methParams, methPrmTypes);
845                 } else {
846                         print("Class<?>[] paramCls = new Class<?>[] { ");
847                         for (int i = 0; i < methParams.size(); i++) {
848                                 String paramType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
849                                 print(getSimpleType(getEnumType(paramType)) + ".class");
850                                 // Check if this is the last element (don't print a comma)
851                                 if (i != methParams.size() - 1) {
852                                         print(", ");
853                                 }
854                         }
855                         println(" };");
856                         // Generate array of parameter objects
857                         print("Object[] paramObj = new Object[] { ");
858                         for (int i = 0; i < methParams.size(); i++) {
859                                 print(getEnumParam(methPrmTypes.get(i), getSimpleIdentifier(methParams.get(i)), i));
860                                 // Check if this is the last element (don't print a comma)
861                                 if (i != methParams.size() - 1) {
862                                         print(", ");
863                                 }
864                         }
865                         println(" };");
866                 }
867                 // Check if this is "void"
868                 if (retType.equals("void")) {
869                         println("rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
870                 } else { // We do have a return value
871                         // Generate array of parameter types
872                         if (isStructClass(getGenericType(getSimpleArrayType(retType)))) {
873                                 writeStructReturnJavaStub(getGenericType(getSimpleArrayType(retType)), retType);
874                         } else {
875                         // Check if the return value NONPRIMITIVES
876                                 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES) {
877                                         String[] retGenValType = getTypeOfGeneric(retType);
878                                         println("Class<?> retGenValType = " + retGenValType[0] + ".class;");
879                                         println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, retGenValType, paramCls, paramObj);");
880                                         println("return (" + retType + ")retObj;");
881                                 } else if (getParamCategory(retType) == ParamCategory.ENUM) {
882                                 // This is an enum type
883                                         println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
884                                         checkAndWriteEnumRetTypeJavaStub(retType);
885                                 } else {
886                                         println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
887                                         println("return (" + retType + ")retObj;");
888                                 }
889                         }
890                 }
891         }
892
893
894         /**
895          * HELPER: returnGenericCallbackType() returns the callback type
896          */
897         private String returnGenericCallbackType(String paramType) {
898
899                 if (getParamCategory(paramType) == ParamCategory.NONPRIMITIVES)
900                         return getTypeOfGeneric(paramType)[0];
901                 else
902                         return paramType;
903         }
904
905
906         /**
907          * HELPER: checkCallbackType() checks the callback type
908          */
909         private boolean checkCallbackType(String paramType, String callbackType) {
910
911                 String prmType = returnGenericCallbackType(paramType);
912                 return callbackType.equals(prmType);
913         }
914
915
916         /**
917          * HELPER: writeCallbackMethodBodyJavaStub() writes the callback method of the stub class
918          */
919         private void writeCallbackMethodBodyJavaStub(InterfaceDecl intDecl, List<String> methParams,
920                         List<String> methPrmTypes, String method, String callbackType) {
921
922                 println("try {");
923                 // Check if this is single object, array, or list of objects
924                 for (int i = 0; i < methParams.size(); i++) {
925                         String paramType = methPrmTypes.get(i);
926                         if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
927                                 String param = methParams.get(i);
928                                 if (isArrayOrList(paramType, param)) {  // Generate loop
929                                         println("for (" + paramType + " cb : " + getSimpleIdentifier(param) + ") {");
930                                         println(callbackType + "_CallbackSkeleton skel = new " + callbackType + "_CallbackSkeleton(cb, objIdCnt++);");
931                                 } else
932                                         println(callbackType + "_CallbackSkeleton skel = new " + callbackType + "_CallbackSkeleton(" +
933                                                 getSimpleIdentifier(param) + ", objIdCnt++);");
934                                 println("listCallbackObj.add(skel);");
935                                 if (isArrayOrList(paramType, param))
936                                         println("}");
937                         }
938                 }
939                 println("} catch (Exception ex) {");
940                 println("ex.printStackTrace();");
941                 println("throw new Error(\"Exception when generating skeleton objects!\");");
942                 println("}\n");
943                 println("int methodId = " + intDecl.getMethodNumId(method) + ";");
944                 String retType = intDecl.getMethodType(method);
945                 println("Class<?> retType = " + getSimpleType(getEnumType(retType)) + ".class;");
946                 // Generate array of parameter types
947                 print("Class<?>[] paramCls = new Class<?>[] { ");
948                 for (int i = 0; i < methParams.size(); i++) {
949                         String paramType = methPrmTypes.get(i);
950                         if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
951                                 print("int.class");
952                         } else { // Generate normal classes if it's not a callback object
953                                 String prmType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
954                                 print(getSimpleType(prmType) + ".class");
955                         }
956                         if (i != methParams.size() - 1) // Check if this is the last element
957                                 print(", ");
958                 }
959                 println(" };");
960                 // Generate array of parameter objects
961                 print("Object[] paramObj = new Object[] { ");
962                 for (int i = 0; i < methParams.size(); i++) {
963                         String paramType = methPrmTypes.get(i);
964                         if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
965                                 //if (isArray(methPrmTypes.get(i), methParams.get(i)))
966                                 if (isArray(methParams.get(i)))
967                                         print(getSimpleIdentifier(methParams.get(i)) + ".length");
968                                 else if (isList(methPrmTypes.get(i)))
969                                         print(getSimpleIdentifier(methParams.get(i)) + ".size()");
970                                 else
971                                         print("new Integer(1)");
972                         } else
973                                 print(getSimpleIdentifier(methParams.get(i)));
974                         if (i != methParams.size() - 1)
975                                 print(", ");
976                 }
977                 println(" };");
978                 // Check if this is "void"
979                 if (retType.equals("void")) {
980                         println("rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
981                 } else { // We do have a return value
982                 // Check if the return value NONPRIMITIVES
983                         if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES) {
984                                 String[] retGenValType = getTypeOfGeneric(retType);
985                                 println("Class<?> retGenValType = " + retGenValType[0] + ".class;");
986                                 println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, retGenValType, paramCls, paramObj);");
987                                 println("return (" + retType + ")retObj;");
988                         } else {
989                                 println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
990                                 println("return (" + retType + ")retObj;");
991                         }
992                 }
993         }
994
995
996         /**
997          * HELPER: writeMethodJavaStub() writes the methods of the stub class
998          */
999         private void writeMethodJavaStub(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
1000
1001                 for (String method : methods) {
1002
1003                         List<String> methParams = intDecl.getMethodParams(method);
1004                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1005                         print("public " + intDecl.getMethodType(method) + " " +
1006                                 intDecl.getMethodId(method) + "(");
1007                         boolean isCallbackMethod = false;
1008                         String callbackType = null;
1009                         for (int i = 0; i < methParams.size(); i++) {
1010
1011                                 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
1012                                 // Check if this has callback object
1013                                 if (callbackClasses.contains(paramType)) {
1014                                         isCallbackMethod = true;
1015                                         callbackType = paramType;       
1016                                         // Even if there're 2 callback arguments, we expect them to be of the same interface
1017                                 }
1018                                 print(methPrmTypes.get(i) + " " + methParams.get(i));
1019                                 // Check if this is the last element (don't print a comma)
1020                                 if (i != methParams.size() - 1) {
1021                                         print(", ");
1022                                 }
1023                         }
1024                         println(") {");
1025                         // Now, write the body of stub!
1026                         if (isCallbackMethod)
1027                                 writeCallbackMethodBodyJavaStub(intDecl, methParams, methPrmTypes, method, callbackType);
1028                         else
1029                                 writeStdMethodBodyJavaStub(intDecl, methParams, methPrmTypes, method);
1030                         println("}\n");
1031                         // Write the init callback helper method
1032                         if (isCallbackMethod)
1033                                 writeInitCallbackJavaStub(callbackType, intDecl);
1034                 }
1035         }
1036
1037
1038         /**
1039          * generateJavaStubClasses() generate stubs based on the methods list in Java
1040          */
1041         public void generateJavaStubClasses() throws IOException {
1042
1043                 // Create a new directory
1044                 String path = createDirectories(dir, subdir);
1045                 for (String intface : mapIntfacePTH.keySet()) {
1046
1047                         Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
1048                         for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
1049
1050                                 // Open a new file to write into
1051                                 String newIntface = intMeth.getKey();
1052                                 String newStubClass = newIntface + "_Stub";
1053                                 FileWriter fw = new FileWriter(path + "/" + newStubClass + ".java");
1054                                 pw = new PrintWriter(new BufferedWriter(fw));
1055                                 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
1056                                 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
1057                                 // Pass in set of methods and get import classes
1058                                 Set<String> methods = intMeth.getValue();
1059                                 Set<String> importClasses = getImportClasses(methods, intDecl);
1060                                 List<String> stdImportClasses = getStandardJavaImportClasses();
1061                                 List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
1062                                 printImportStatements(allImportClasses); println("");
1063                                 // Find out if there are callback objects
1064                                 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
1065                                 boolean callbackExist = !callbackClasses.isEmpty();
1066                                 // Write class header
1067                                 println("public class " + newStubClass + " implements " + newIntface + " {\n");
1068                                 // Write properties
1069                                 writePropertiesJavaStub(intface, newIntface, callbackExist, callbackClasses);
1070                                 // Write constructor
1071                                 writeConstructorJavaStub(intface, newStubClass, callbackExist, callbackClasses);
1072                                 // Write methods
1073                                 writeMethodJavaStub(intMeth.getValue(), intDecl, callbackClasses);
1074                                 println("}");
1075                                 pw.close();
1076                                 System.out.println("IoTCompiler: Generated stub class " + newStubClass + ".java...");
1077                         }
1078                 }
1079         }
1080
1081
1082         /**
1083          * HELPER: writePropertiesJavaCallbackStub() writes the properties of the callback stub class
1084          */
1085         private void writePropertiesJavaCallbackStub(String intface, String newIntface, boolean callbackExist, Set<String> callbackClasses) {
1086
1087                 println("private IoTRMICall rmiCall;");
1088                 println("private String address;");
1089                 println("private int[] ports;\n");
1090                 // Get the object Id
1091                 println("private static int objectId = 0;");
1092                 if (callbackExist) {
1093                 // We assume that each class only has one callback interface for now
1094                         Iterator it = callbackClasses.iterator();
1095                         String callbackType = (String) it.next();
1096                         println("// Callback properties");
1097                         println("private IoTRMIObject rmiObj;");
1098                         println("List<" + callbackType + "> listCallbackObj;");
1099                         println("private static int objIdCnt = 0;");
1100                         // Generate permission stuff for callback stubs
1101                         DeclarationHandler decHandler = mapIntDeclHand.get(callbackType);
1102                         InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(callbackType);
1103                         writePropertiesJavaPermission(callbackType, intDecl);
1104                 }
1105                 println("\n");
1106         }
1107
1108
1109         /**
1110          * HELPER: writeConstructorJavaCallbackStub() writes the constructor of the callback stub class
1111          */
1112         private void writeConstructorJavaCallbackStub(String intface, String newStubClass, boolean callbackExist, Set<String> callbackClasses) {
1113
1114                 // TODO: If we want callback in callback, then we need to add address and port initializations
1115                 println("public " + newStubClass + "(IoTRMICall _rmiCall, int _objectId) throws Exception {");
1116                 println("objectId = _objectId;");
1117                 println("rmiCall = _rmiCall;");
1118                 if (callbackExist) {
1119                         Iterator it = callbackClasses.iterator();
1120                         String callbackType = (String) it.next();
1121                         writeConstructorJavaPermission(intface);
1122                         println("listCallbackObj = new ArrayList<" + callbackType + ">();");
1123                         println("___initCallBack();");
1124                         println("// TODO: Add address and port initialization here if we want callback in callback!");
1125                 }
1126                 println("}\n");
1127         }
1128
1129
1130         /**
1131          * generateJavaCallbackStubClasses() generate callback stubs based on the methods list in Java
1132          * <p>
1133          * Callback stubs gets the IoTRMICall objects from outside of the class as contructor input
1134          * because all these stubs are populated by the class that takes in this object as a callback
1135          * object. In such a class, we only use one socket, hence one IoTRMICall, for all callback objects.
1136          */
1137         public void generateJavaCallbackStubClasses() throws IOException {
1138
1139                 // Create a new directory
1140                 String path = createDirectories(dir, subdir);
1141                 for (String intface : mapIntfacePTH.keySet()) {
1142
1143                         Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
1144                         for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
1145
1146                                 // Open a new file to write into
1147                                 String newIntface = intMeth.getKey();
1148                                 String newStubClass = newIntface + "_CallbackStub";
1149                                 FileWriter fw = new FileWriter(path + "/" + newStubClass + ".java");
1150                                 pw = new PrintWriter(new BufferedWriter(fw));
1151                                 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
1152                                 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
1153                                 // Pass in set of methods and get import classes
1154                                 Set<String> methods = intMeth.getValue();
1155                                 Set<String> importClasses = getImportClasses(methods, intDecl);
1156                                 List<String> stdImportClasses = getStandardJavaImportClasses();
1157                                 List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
1158                                 printImportStatements(allImportClasses); println("");
1159                                 // Find out if there are callback objects
1160                                 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
1161                                 boolean callbackExist = !callbackClasses.isEmpty();
1162                                 // Write class header
1163                                 println("public class " + newStubClass + " implements " + newIntface + " {\n");
1164                                 // Write properties
1165                                 writePropertiesJavaCallbackStub(intface, newIntface, callbackExist, callbackClasses);
1166                                 // Write constructor
1167                                 writeConstructorJavaCallbackStub(intface, newStubClass, callbackExist, callbackClasses);
1168                                 // Write methods
1169                                 // TODO: perhaps need to generate callback for callback
1170                                 writeMethodJavaStub(intMeth.getValue(), intDecl, callbackClasses);
1171                                 println("}");
1172                                 pw.close();
1173                                 System.out.println("IoTCompiler: Generated callback stub class " + newStubClass + ".java...");
1174                         }
1175                 }
1176         }
1177
1178
1179         /**
1180          * HELPER: writePropertiesJavaSkeleton() writes the properties of the skeleton class
1181          */
1182         private void writePropertiesJavaSkeleton(String intface, boolean callbackExist, InterfaceDecl intDecl) {
1183
1184                 println("private " + intface + " mainObj;");
1185                 //println("private int ports;");
1186                 println("private IoTRMIObject rmiObj;\n");
1187                 // Callback
1188                 if (callbackExist) {
1189                         println("private static int objIdCnt = 0;");
1190                         println("private IoTRMICall rmiCall;");
1191                 }
1192                 writePropertiesJavaPermission(intface, intDecl);
1193                 println("\n");
1194         }
1195
1196
1197         /**
1198          * HELPER: writeConstructorJavaSkeleton() writes the constructor of the skeleton class
1199          */
1200         private void writeConstructorJavaSkeleton(String newSkelClass, String intface) {
1201
1202                 println("public " + newSkelClass + "(" + intface + " _mainObj, int _port) throws Exception {");
1203                 println("mainObj = _mainObj;");
1204                 println("rmiObj = new IoTRMIObject(_port);");
1205                 // Generate permission control initialization
1206                 writeConstructorJavaPermission(intface);
1207                 println("___waitRequestInvokeMethod();");
1208                 println("}\n");
1209         }
1210
1211
1212         /**
1213          * HELPER: writeStdMethodBodyJavaSkeleton() writes the standard method body in the skeleton class
1214          */
1215         private void writeStdMethodBodyJavaSkeleton(List<String> methParams, String methodId, String methodType) {
1216
1217                 if (methodType.equals("void"))
1218                         print("mainObj." + methodId + "(");
1219                 else
1220                         print("return mainObj." + methodId + "(");
1221                 for (int i = 0; i < methParams.size(); i++) {
1222
1223                         print(getSimpleIdentifier(methParams.get(i)));
1224                         // Check if this is the last element (don't print a comma)
1225                         if (i != methParams.size() - 1) {
1226                                 print(", ");
1227                         }
1228                 }
1229                 println(");");
1230         }
1231
1232
1233         /**
1234          * HELPER: writeInitCallbackJavaSkeleton() writes the init callback method for skeleton class
1235          */
1236         private void writeInitCallbackJavaSkeleton(boolean callbackSkeleton) {
1237
1238                 // This is a callback skeleton generation
1239                 if (callbackSkeleton)
1240                         println("public void ___regCB(IoTRMIObject rmiObj) throws IOException {");
1241                 else
1242                         println("public void ___regCB() throws IOException {");
1243                 println("Object[] paramObj = rmiObj.getMethodParams(new Class<?>[] { int.class, String.class, int.class },");
1244                 println("\tnew Class<?>[] { null, null, null });");
1245                 println("rmiCall = new IoTRMICall((int) paramObj[0], (String) paramObj[1], (int) paramObj[2]);");
1246                 println("}\n");
1247         }
1248
1249
1250         /**
1251          * HELPER: writeMethodJavaSkeleton() writes the method of the skeleton class
1252          */
1253         private void writeMethodJavaSkeleton(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses, 
1254                         boolean callbackSkeleton) {
1255
1256                 for (String method : methods) {
1257
1258                         List<String> methParams = intDecl.getMethodParams(method);
1259                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1260                         String methodId = intDecl.getMethodId(method);
1261                         print("public " + intDecl.getMethodType(method) + " " + methodId + "(");
1262                         boolean isCallbackMethod = false;
1263                         String callbackType = null;
1264                         for (int i = 0; i < methParams.size(); i++) {
1265
1266                                 String origParamType = methPrmTypes.get(i);
1267                                 String paramType = checkAndGetParamClass(origParamType);
1268                                 if (callbackClasses.contains(origParamType)) { // Check if this has callback object
1269                                         isCallbackMethod = true;
1270                                         callbackType = origParamType;   
1271                                 }
1272                                 print(paramType + " " + methParams.get(i));
1273                                 // Check if this is the last element (don't print a comma)
1274                                 if (i != methParams.size() - 1) {
1275                                         print(", ");
1276                                 }
1277                         }
1278                         println(") {");
1279                         // Now, write the body of skeleton!
1280                         writeStdMethodBodyJavaSkeleton(methParams, methodId, intDecl.getMethodType(method));
1281                         println("}\n");
1282                         if (isCallbackMethod)
1283                                 writeInitCallbackJavaSkeleton(callbackSkeleton);
1284                 }
1285         }
1286
1287
1288         /**
1289          * HELPER: writeCallbackJavaStubGeneration() writes the callback stub generation part
1290          */
1291         private Map<Integer,String> writeCallbackJavaStubGeneration(List<String> methParams, List<String> methPrmTypes, 
1292                         String callbackType) {
1293
1294                 Map<Integer,String> mapStubParam = new HashMap<Integer,String>();
1295                 // Iterate over callback objects
1296                 for (int i = 0; i < methParams.size(); i++) {
1297                         String paramType = methPrmTypes.get(i);
1298                         String param = methParams.get(i);
1299                         //if (callbackType.equals(paramType)) {
1300                         if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
1301                                 println("try {");
1302                                 String exchParamType = checkAndGetParamClass(paramType);
1303                                 // Print array if this is array or list if this is a list of callback objects
1304                                 if (isArray(param)) {
1305                                         println("int numStubs" + i + " = (int) paramObj[" + i + "];");
1306                                         println(exchParamType + "[] stub" + i + " = new " + exchParamType + "[numStubs" + i + "];");
1307                                 } else if (isList(paramType)) {
1308                                         println("int numStubs" + i + " = (int) paramObj[" + i + "];");
1309                                         println("List<" + exchParamType + "> stub" + i + " = new ArrayList<" + exchParamType + ">();");
1310                                 } else {
1311                                         println(exchParamType + " stub" + i + " = new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt);");
1312                                         println("objIdCnt++;");
1313                                 }
1314                         }
1315                         // Generate a loop if needed
1316                         if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
1317                                 String exchParamType = checkAndGetParamClass(paramType);
1318                                 if (isArray(param)) {
1319                                         println("for (int objId = 0; objId < numStubs" + i + "; objId++) {");
1320                                         println("stub" + i + "[objId] = new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt);");
1321                                         println("objIdCnt++;");
1322                                         println("}");
1323                                 } else if (isList(paramType)) {
1324                                         println("for (int objId = 0; objId < numStubs" + i + "; objId++) {");
1325                                         println("stub" + i + ".add(new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt));");
1326                                         println("objIdCnt++;");
1327                                         println("}");
1328                                 }
1329                                 mapStubParam.put(i, "stub" + i);        // List of all stub parameters
1330                         }
1331                 }
1332                 return mapStubParam;
1333         }
1334
1335
1336         /**
1337          * HELPER: checkAndWriteEnumTypeJavaSkeleton() writes the enum type (convert from enum to int)
1338          */
1339         private void checkAndWriteEnumTypeJavaSkeleton(List<String> methParams, List<String> methPrmTypes) {
1340
1341                 // Iterate and find enum declarations
1342                 for (int i = 0; i < methParams.size(); i++) {
1343                         String paramType = methPrmTypes.get(i);
1344                         String param = methParams.get(i);
1345                         String simpleType = getSimpleType(paramType);
1346                         if (isEnumClass(simpleType)) {
1347                         // Check if this is enum type
1348                                 println("int paramInt" + i + "[] = (int[]) paramObj[" + i + "];");
1349                                 println(simpleType + "[] enumVals = " + simpleType + ".values();");
1350                                 if (isArray(param)) {   // An array
1351                                         println("int len" + i + " = paramInt" + i + ".length;");
1352                                         println(simpleType + "[] paramEnum = new " + simpleType + "[len];");
1353                                         println("for (int i = 0; i < len" + i + "; i++) {");
1354                                         println("paramEnum[i] = enumVals[paramInt" + i + "[i]];");
1355                                         println("}");
1356                                 } else if (isList(paramType)) { // A list
1357                                         println("int len" + i + " = paramInt" + i + ".length;");
1358                                         println("List<" + simpleType + "> paramEnum = new ArrayList<" + simpleType + ">();");
1359                                         println("for (int i = 0; i < len" + i + "; i++) {");
1360                                         println("paramEnum.add(enumVals[paramInt" + i + "[i]]);");
1361                                         println("}");
1362                                 } else {        // Just one element
1363                                         println(simpleType + " paramEnum" + i + " = enumVals[paramInt" + i + "[0]];");
1364                                 }
1365                         }
1366                 }
1367         }
1368
1369
1370         /**
1371          * HELPER: checkAndWriteEnumRetTypeJavaSkeleton() writes the enum return type (convert from enum to int)
1372          */
1373         private void checkAndWriteEnumRetTypeJavaSkeleton(String retType, String methodId) {
1374
1375                 // Strips off array "[]" for return type
1376                 String pureType = getSimpleArrayType(getSimpleType(retType));
1377                 // Take the inner type of generic
1378                 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
1379                         pureType = getTypeOfGeneric(retType)[0];
1380                 if (isEnumClass(pureType)) {
1381                 // Check if this is enum type
1382                         // Enum decoder
1383                         if (isArray(retType)) {                 // An array
1384                                 print(pureType + "[] retEnum = " + methodId + "(");
1385                         } else if (isList(retType)) {   // A list
1386                                 print("List<" + pureType + "> retEnum = " + methodId + "(");
1387                         } else {        // Just one element
1388                                 print(pureType + " retEnum = " + methodId + "(");
1389                         }
1390                 }
1391         }
1392
1393
1394         /**
1395          * HELPER: checkAndWriteEnumRetConvJavaSkeleton() writes the enum return type (convert from enum to int)
1396          */
1397         private void checkAndWriteEnumRetConvJavaSkeleton(String retType) {
1398
1399                 // Strips off array "[]" for return type
1400                 String pureType = getSimpleArrayType(getSimpleType(retType));
1401                 // Take the inner type of generic
1402                 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
1403                         pureType = getTypeOfGeneric(retType)[0];
1404                 if (isEnumClass(pureType)) {
1405                 // Check if this is enum type
1406                         if (isArray(retType)) { // An array
1407                                 println("int retLen = retEnum.length;");
1408                                 println("int[] retEnumVal = new int[retLen];");
1409                                 println("for (int i = 0; i < retLen; i++) {");
1410                                 println("retEnumVal[i] = retEnum[i].ordinal();");
1411                                 println("}");
1412                         } else if (isList(retType)) {   // A list
1413                                 println("int retLen = retEnum.size();");
1414                                 println("List<" + pureType + "> retEnumVal = new ArrayList<" + pureType + ">();");
1415                                 println("for (int i = 0; i < retLen; i++) {");
1416                                 println("retEnumVal.add(retEnum[i].ordinal());");
1417                                 println("}");
1418                         } else {        // Just one element
1419                                 println("int[] retEnumVal = new int[1];");
1420                                 println("retEnumVal[0] = retEnum.ordinal();");
1421                         }
1422                         println("Object retObj = retEnumVal;");
1423                 }
1424         }
1425         
1426         
1427         /**
1428          * HELPER: writeLengthStructParamClassSkeleton() writes lengths of params
1429          */
1430         private void writeLengthStructParamClassSkeleton(List<String> methParams, List<String> methPrmTypes, 
1431                         String method, InterfaceDecl intDecl) {
1432
1433                 // Iterate and find struct declarations - count number of params
1434                 for (int i = 0; i < methParams.size(); i++) {
1435                         String paramType = methPrmTypes.get(i);
1436                         String param = methParams.get(i);
1437                         String simpleType = getGenericType(paramType);
1438                         if (isStructClass(simpleType)) {
1439                                 int members = getNumOfMembers(simpleType);
1440                                 print(Integer.toString(members) + "*");
1441                                 int methodNumId = intDecl.getMethodNumId(method);
1442                                 print("struct" + methodNumId + "Size" + i);
1443                         } else
1444                                 print("1");
1445                         if (i != methParams.size() - 1) {
1446                                 print("+");
1447                         }
1448                 }
1449         }
1450
1451         
1452         /**
1453          * HELPER: writeStructMembersJavaSkeleton() writes member parameters of struct
1454          */
1455         private void writeStructMembersJavaSkeleton(String simpleType, String paramType, 
1456                         String param, String method, InterfaceDecl intDecl, int iVar) {
1457
1458                 // Get the struct declaration for this struct and generate initialization code
1459                 StructDecl structDecl = getStructDecl(simpleType);
1460                 List<String> memTypes = structDecl.getMemberTypes(simpleType);
1461                 List<String> members = structDecl.getMembers(simpleType);
1462                 if (isArrayOrList(param, paramType)) {  // An array or list
1463                         int methodNumId = intDecl.getMethodNumId(method);
1464                         String counter = "struct" + methodNumId + "Size" + iVar;
1465                         println("for(int i = 0; i < " + counter + "; i++) {");
1466                 }
1467                 println("int pos = 0;");
1468                 if (isArrayOrList(param, paramType)) {  // An array or list
1469                         println("for(int i = 0; i < retLen; i++) {");
1470                         for (int i = 0; i < members.size(); i++) {
1471                                 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
1472                                 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
1473                                 println("paramClsGen[pos++] = null;");
1474                         }
1475                         println("}");
1476                 } else {        // Just one struct element
1477                         for (int i = 0; i < members.size(); i++) {
1478                                 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
1479                                 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
1480                                 println("paramClsGen[pos++] = null;");
1481                         }
1482                 }
1483         }
1484
1485
1486         /**
1487          * HELPER: writeStructMembersInitJavaSkeleton() writes member parameters initialization of struct
1488          */
1489         private void writeStructMembersInitJavaSkeleton(InterfaceDecl intDecl, List<String> methParams,
1490                         List<String> methPrmTypes, String method) {
1491
1492                 for (int i = 0; i < methParams.size(); i++) {
1493                         String paramType = methPrmTypes.get(i);
1494                         String param = methParams.get(i);
1495                         String simpleType = getGenericType(paramType);
1496                         if (isStructClass(simpleType)) {
1497                                 int methodNumId = intDecl.getMethodNumId(method);
1498                                 String counter = "struct" + methodNumId + "Size" + i;
1499                                 // Declaration
1500                                 if (isArray(param)) {                   // An array
1501                                         println(simpleType + "[] paramStruct" + i + " = new " + simpleType + "[" + counter + "];");
1502                                         println("for(int i = 0; i < " + counter + "; i++) {");
1503                                         println("paramStruct" + i + "[i] = new " + simpleType + "();");
1504                                         println("}");
1505                                 } else if (isList(paramType)) { // A list
1506                                         println("List<" + simpleType + "> paramStruct" + i + " = new ArrayList<" + simpleType + ">();");
1507                                 } else
1508                                         println(simpleType + " paramStruct" + i + " = new " + simpleType + "();");
1509                                 println("int objPos = 0;");
1510                                 // Initialize members
1511                                 StructDecl structDecl = getStructDecl(simpleType);
1512                                 List<String> members = structDecl.getMembers(simpleType);
1513                                 List<String> memTypes = structDecl.getMemberTypes(simpleType);
1514                                 if (isArrayOrList(param, paramType)) {  // An array or list
1515                                         println("for(int i = 0; i < " + counter + "; i++) {");
1516                                 }
1517                                 if (isArray(param)) {   // An array
1518                                         for (int j = 0; j < members.size(); j++) {
1519                                                 String prmType = checkAndGetArray(memTypes.get(j), members.get(j));
1520                                                 print("paramStruct" + i + "[i]." + getSimpleIdentifier(members.get(j)));
1521                                                 println(" = (" + getSimpleType(getEnumType(prmType)) + ") paramObj[objPos++];");
1522                                         }
1523                                         println("}");
1524                                 } else if (isList(paramType)) { // A list
1525                                         println(simpleType + " paramStructMem = new " + simpleType + "();");
1526                                         for (int j = 0; j < members.size(); j++) {
1527                                                 String prmType = checkAndGetArray(memTypes.get(j), members.get(j));
1528                                                 print("paramStructMem." + getSimpleIdentifier(members.get(j)));
1529                                                 println(" = (" + getSimpleType(getEnumType(prmType)) + ") paramObj[objPos++];");
1530                                         }
1531                                         println("paramStruct" + i + ".add(paramStructMem);");
1532                                         println("}");
1533                                 } else {        // Just one struct element
1534                                         for (int j = 0; j < members.size(); j++) {
1535                                                 String prmType = checkAndGetArray(memTypes.get(j), members.get(j));
1536                                                 print("paramStruct" + i + "." + getSimpleIdentifier(members.get(j)));
1537                                                 println(" = (" + getSimpleType(getEnumType(prmType)) + ") paramObj[objPos++];");
1538                                         }
1539                                 }
1540                         } else {
1541                                 // Take offsets of parameters
1542                                 println("int offset" + i +" = objPos;");
1543                         }
1544                 }
1545         }
1546
1547
1548         /**
1549          * HELPER: writeStructReturnJavaSkeleton() writes struct for return statement
1550          */
1551         private void writeStructReturnJavaSkeleton(String simpleType, String retType) {
1552
1553                 // Minimum retLen is 1 if this is a single struct object
1554                 if (isArray(retType))
1555                         println("int retLen = retStruct.length;");
1556                 else if (isList(retType))
1557                         println("int retLen = retStruct.size();");
1558                 else    // Just single struct object
1559                         println("int retLen = 1;");
1560                 println("Object retLenObj = retLen;");
1561                 println("rmiObj.sendReturnObj(retLenObj);");
1562                 int numMem = getNumOfMembers(simpleType);
1563                 println("Class<?>[] retCls = new Class<?>[" + numMem + "*retLen];");
1564                 println("Object[] retObj = new Object[" + numMem + "*retLen];");
1565                 println("int retPos = 0;");
1566                 // Get the struct declaration for this struct and generate initialization code
1567                 StructDecl structDecl = getStructDecl(simpleType);
1568                 List<String> memTypes = structDecl.getMemberTypes(simpleType);
1569                 List<String> members = structDecl.getMembers(simpleType);
1570                 if (isArrayOrList(retType, retType)) {  // An array or list
1571                         println("for(int i = 0; i < retLen; i++) {");
1572                         for (int i = 0; i < members.size(); i++) {
1573                                 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
1574                                 println("retCls[retPos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
1575                                 print("retObj[retPos++] = retStruct[i].");
1576                                 print(getEnumParam(memTypes.get(i), getSimpleIdentifier(members.get(i)), i));
1577                                 println(";");
1578                         }
1579                         println("}");
1580                 } else {        // Just one struct element
1581                         for (int i = 0; i < members.size(); i++) {
1582                                 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
1583                                 println("retCls[retPos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
1584                                 print("retObj[retPos++] = retStruct.");
1585                                 print(getEnumParam(memTypes.get(i), getSimpleIdentifier(members.get(i)), i));
1586                                 println(";");
1587                         }
1588                 }
1589
1590         }
1591
1592
1593         /**
1594          * HELPER: writeMethodHelperReturnJavaSkeleton() writes return statement part in skeleton
1595          */
1596         private void writeMethodHelperReturnJavaSkeleton(InterfaceDecl intDecl, List<String> methParams,
1597                         List<String> methPrmTypes, String method, boolean isCallbackMethod, String callbackType,
1598                         boolean isStructMethod) {
1599
1600                 checkAndWriteEnumTypeJavaSkeleton(methParams, methPrmTypes);
1601                 Map<Integer,String> mapStubParam = null;
1602                 if (isCallbackMethod)
1603                         mapStubParam = writeCallbackJavaStubGeneration(methParams, methPrmTypes, callbackType);
1604                 // Check if this is "void"
1605                 String retType = intDecl.getMethodType(method);
1606                 if (retType.equals("void")) {
1607                         print(intDecl.getMethodId(method) + "(");
1608                 } else if (isEnumClass(getSimpleArrayType(getSimpleType(retType)))) {   // Enum type
1609                         checkAndWriteEnumRetTypeJavaSkeleton(retType, intDecl.getMethodId(method));
1610                 } else if (isStructClass(getSimpleArrayType(getSimpleType(retType)))) { // Struct type
1611                         print(retType + " retStruct = " + intDecl.getMethodId(method) + "(");
1612                 } else { // We do have a return value
1613                         print("Object retObj = " + intDecl.getMethodId(method) + "(");
1614                 }
1615                 for (int i = 0; i < methParams.size(); i++) {
1616
1617                         if (isCallbackMethod) {
1618                                 print(mapStubParam.get(i));     // Get the callback parameter
1619                         } else if (isEnumClass(getSimpleType(methPrmTypes.get(i)))) { // Enum class
1620                                 print(getEnumParam(methPrmTypes.get(i), methParams.get(i), i));
1621                         } else if (isStructClass(getSimpleType(methPrmTypes.get(i)))) {
1622                                 print("paramStruct" + i);
1623                         } else {
1624                                 String prmType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
1625                                 if (isStructMethod)
1626                                         print("(" + prmType + ") paramObj[offset" + i + "]");
1627                                 else
1628                                         print("(" + prmType + ") paramObj[" + i + "]");
1629                         }
1630                         if (i != methParams.size() - 1)
1631                                 print(", ");
1632                 }
1633                 println(");");
1634                 if (!retType.equals("void")) {
1635                         if (isEnumClass(getSimpleArrayType(getSimpleType(retType)))) { // Enum type
1636                                 checkAndWriteEnumRetConvJavaSkeleton(retType);
1637                                 println("rmiObj.sendReturnObj(retObj);");
1638                         } else if (isStructClass(getSimpleArrayType(getSimpleType(retType)))) { // Struct type
1639                                 writeStructReturnJavaSkeleton(getSimpleArrayType(getSimpleType(retType)), retType);
1640                                 println("rmiObj.sendReturnObj(retCls, retObj);");
1641                         } else
1642                                 println("rmiObj.sendReturnObj(retObj);");
1643                 }
1644                 if (isCallbackMethod) { // Catch exception if this is callback
1645                         println("} catch(Exception ex) {");
1646                         println("ex.printStackTrace();");
1647                         println("throw new Error(\"Exception from callback object instantiation!\");");
1648                         println("}");
1649                 }
1650         }
1651
1652
1653         /**
1654          * HELPER: writeMethodHelperStructJavaSkeleton() writes the struct in skeleton
1655          */
1656         private void writeMethodHelperStructJavaSkeleton(InterfaceDecl intDecl, List<String> methParams,
1657                         List<String> methPrmTypes, String method, Set<String> callbackClasses) {
1658
1659                 // Generate array of parameter objects
1660                 boolean isCallbackMethod = false;
1661                 String callbackType = null;
1662                 print("int paramLen = ");
1663                 writeLengthStructParamClassSkeleton(methParams, methPrmTypes, method, intDecl);
1664                 println(";");
1665                 println("Class<?>[] paramCls = new Class<?>[paramLen];");
1666                 println("Class<?>[] paramClsGen = new Class<?>[paramLen];");
1667                 // Iterate again over the parameters
1668                 for (int i = 0; i < methParams.size(); i++) {
1669                         String paramType = methPrmTypes.get(i);
1670                         String param = methParams.get(i);
1671                         String simpleType = getGenericType(paramType);
1672                         if (isStructClass(simpleType)) {
1673                                 writeStructMembersJavaSkeleton(simpleType, paramType, param, method, intDecl, i);
1674                         } else {
1675                                 String prmType = returnGenericCallbackType(methPrmTypes.get(i));
1676                                 if (callbackClasses.contains(prmType)) {
1677                                         isCallbackMethod = true;
1678                                         callbackType = prmType;
1679                                         println("paramCls[pos] = int.class;");
1680                                         println("paramClsGen[pos++] = null;");
1681                                 } else {        // Generate normal classes if it's not a callback object
1682                                         String paramTypeOth = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
1683                                         println("paramCls[pos] = " + getSimpleType(getEnumType(paramTypeOth)) + ".class;");
1684                                         print("paramClsGen[pos++] = ");
1685                                         String prmTypeOth = methPrmTypes.get(i);
1686                                         if (getParamCategory(prmTypeOth) == ParamCategory.NONPRIMITIVES)
1687                                                 println(getTypeOfGeneric(prmType)[0] + ".class;");
1688                                         else
1689                                                 println("null;");
1690                                 }
1691                         }
1692                 }
1693                 println("Object[] paramObj = rmiObj.getMethodParams(paramCls, paramClsGen);");
1694                 writeStructMembersInitJavaSkeleton(intDecl, methParams, methPrmTypes, method);
1695                 // Write the return value part
1696                 writeMethodHelperReturnJavaSkeleton(intDecl, methParams, methPrmTypes, method, isCallbackMethod, callbackType, true);
1697         }
1698
1699
1700         /**
1701          * HELPER: writeStdMethodHelperBodyJavaSkeleton() writes the standard method body helper in the skeleton class
1702          */
1703         private void writeStdMethodHelperBodyJavaSkeleton(InterfaceDecl intDecl, List<String> methParams,
1704                         List<String> methPrmTypes, String method, Set<String> callbackClasses) {
1705
1706                 // Generate array of parameter objects
1707                 boolean isCallbackMethod = false;
1708                 String callbackType = null;
1709                 print("Object[] paramObj = rmiObj.getMethodParams(new Class<?>[] { ");
1710                 for (int i = 0; i < methParams.size(); i++) {
1711
1712                         String paramType = returnGenericCallbackType(methPrmTypes.get(i));
1713                         if (callbackClasses.contains(paramType)) {
1714                                 isCallbackMethod = true;
1715                                 callbackType = paramType;
1716                                 print("int.class");
1717                         } else {        // Generate normal classes if it's not a callback object
1718                                 String prmType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
1719                                 print(getSimpleType(getEnumType(prmType)) + ".class");
1720                         }
1721                         if (i != methParams.size() - 1)
1722                                 print(", ");
1723                 }
1724                 println(" }, ");
1725                 // Generate generic class if it's a generic type.. null otherwise
1726                 print("new Class<?>[] { ");
1727                 for (int i = 0; i < methParams.size(); i++) {
1728                         String prmType = methPrmTypes.get(i);
1729                         if (getParamCategory(prmType) == ParamCategory.NONPRIMITIVES)
1730                                 print(getTypeOfGeneric(prmType)[0] + ".class");
1731                         else
1732                                 print("null");
1733                         if (i != methParams.size() - 1)
1734                                 print(", ");
1735                 }
1736                 println(" });");
1737                 // Write the return value part
1738                 writeMethodHelperReturnJavaSkeleton(intDecl, methParams, methPrmTypes, method, isCallbackMethod, callbackType, false);
1739         }
1740
1741
1742         /**
1743          * HELPER: writeMethodHelperJavaSkeleton() writes the method helper of the skeleton class
1744          */
1745         private void writeMethodHelperJavaSkeleton(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
1746
1747                 // Use this set to handle two same methodIds
1748                 Set<String> uniqueMethodIds = new HashSet<String>();
1749                 for (String method : methods) {
1750
1751                         List<String> methParams = intDecl.getMethodParams(method);
1752                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1753                         if (isStructPresent(methParams, methPrmTypes)) {        // Treat struct differently
1754                                 String methodId = intDecl.getMethodId(method);
1755                                 print("public void ___");
1756                                 String helperMethod = methodId;
1757                                 if (uniqueMethodIds.contains(methodId))
1758                                         helperMethod = helperMethod + intDecl.getMethodNumId(method);
1759                                 else
1760                                         uniqueMethodIds.add(methodId);
1761                                 String retType = intDecl.getMethodType(method);
1762                                 print(helperMethod + "(");
1763                                 boolean begin = true;
1764                                 for (int i = 0; i < methParams.size(); i++) { // Print size variables
1765                                         String paramType = methPrmTypes.get(i);
1766                                         String param = methParams.get(i);
1767                                         String simpleType = getSimpleType(paramType);
1768                                         if (isStructClass(simpleType)) {
1769                                                 if (!begin) {   // Generate comma for not the beginning variable
1770                                                         print(", "); begin = false;
1771                                                 }
1772                                                 int methodNumId = intDecl.getMethodNumId(method);
1773                                                 print("int struct" + methodNumId + "Size" + i);
1774                                         }
1775                                 }
1776                                 // Check if this is "void"
1777                                 if (retType.equals("void"))
1778                                         println(") {");
1779                                 else
1780                                         println(") throws IOException {");
1781                                 writeMethodHelperStructJavaSkeleton(intDecl, methParams, methPrmTypes, method, callbackClasses);
1782                                 println("}\n");
1783                         } else {
1784                                 String methodId = intDecl.getMethodId(method);
1785                                 print("public void ___");
1786                                 String helperMethod = methodId;
1787                                 if (uniqueMethodIds.contains(methodId))
1788                                         helperMethod = helperMethod + intDecl.getMethodNumId(method);
1789                                 else
1790                                         uniqueMethodIds.add(methodId);
1791                                 // Check if this is "void"
1792                                 String retType = intDecl.getMethodType(method);
1793                                 if (retType.equals("void"))
1794                                         println(helperMethod + "() {");
1795                                 else
1796                                         println(helperMethod + "() throws IOException {");
1797                                 // Now, write the helper body of skeleton!
1798                                 writeStdMethodHelperBodyJavaSkeleton(intDecl, methParams, methPrmTypes, method, callbackClasses);
1799                                 println("}\n");
1800                         }
1801                 }
1802                 // Write method helper for structs
1803                 writeMethodHelperStructSetupJavaSkeleton(methods, intDecl);
1804         }
1805
1806
1807         /**
1808          * HELPER: writeMethodHelperStructSetupJavaSkeleton() writes the method helper of struct setup in skeleton class
1809          */
1810         private void writeMethodHelperStructSetupJavaSkeleton(Collection<String> methods, 
1811                         InterfaceDecl intDecl) {
1812
1813                 // Use this set to handle two same methodIds
1814                 for (String method : methods) {
1815
1816                         List<String> methParams = intDecl.getMethodParams(method);
1817                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1818                         // Check for params with structs
1819                         for (int i = 0; i < methParams.size(); i++) {
1820                                 String paramType = methPrmTypes.get(i);
1821                                 String param = methParams.get(i);
1822                                 String simpleType = getSimpleType(paramType);
1823                                 if (isStructClass(simpleType)) {
1824                                         int methodNumId = intDecl.getMethodNumId(method);
1825                                         print("public int ___");
1826                                         String helperMethod = methodNumId + "struct" + i;
1827                                         println(helperMethod + "() {");
1828                                         // Now, write the helper body of skeleton!
1829                                         println("Object[] paramObj = rmiObj.getMethodParams(new Class<?>[] { int.class }, new Class<?>[] { null });");
1830                                         println("return (int) paramObj[0];");
1831                                         println("}\n");
1832                                 }
1833                         }
1834                 }
1835         }
1836
1837
1838         /**
1839          * HELPER: writeMethodHelperStructSetupJavaCallbackSkeleton() writes the method helper of struct setup in callback skeleton class
1840          */
1841         private void writeMethodHelperStructSetupJavaCallbackSkeleton(Collection<String> methods, 
1842                         InterfaceDecl intDecl) {
1843
1844                 // Use this set to handle two same methodIds
1845                 for (String method : methods) {
1846
1847                         List<String> methParams = intDecl.getMethodParams(method);
1848                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1849                         // Check for params with structs
1850                         for (int i = 0; i < methParams.size(); i++) {
1851                                 String paramType = methPrmTypes.get(i);
1852                                 String param = methParams.get(i);
1853                                 String simpleType = getSimpleType(paramType);
1854                                 if (isStructClass(simpleType)) {
1855                                         int methodNumId = intDecl.getMethodNumId(method);
1856                                         print("public int ___");
1857                                         String helperMethod = methodNumId + "struct" + i;
1858                                         println(helperMethod + "(IoTRMIObject rmiObj) {");
1859                                         // Now, write the helper body of skeleton!
1860                                         println("Object[] paramObj = rmiObj.getMethodParams(new Class<?>[] { int.class }, new Class<?>[] { null });");
1861                                         println("return (int) paramObj[0];");
1862                                         println("}\n");
1863                                 }
1864                         }
1865                 }
1866         }
1867
1868
1869         /**
1870          * HELPER: writeCountVarStructSkeleton() writes counter variable of struct for skeleton
1871          */
1872         private void writeCountVarStructSkeleton(Collection<String> methods, InterfaceDecl intDecl) {
1873
1874                 // Use this set to handle two same methodIds
1875                 for (String method : methods) {
1876
1877                         List<String> methParams = intDecl.getMethodParams(method);
1878                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1879                         // Check for params with structs
1880                         for (int i = 0; i < methParams.size(); i++) {
1881                                 String paramType = methPrmTypes.get(i);
1882                                 String param = methParams.get(i);
1883                                 String simpleType = getSimpleType(paramType);
1884                                 if (isStructClass(simpleType)) {
1885                                         int methodNumId = intDecl.getMethodNumId(method);
1886                                         println("int struct" + methodNumId + "Size" + i + " = 0;");
1887                                 }
1888                         }
1889                 }
1890         }
1891         
1892         
1893         /**
1894          * HELPER: writeInputCountVarStructSkeleton() writes input counter variable of struct for skeleton
1895          */
1896         private boolean writeInputCountVarStructSkeleton(String method, InterfaceDecl intDecl) {
1897
1898                 List<String> methParams = intDecl.getMethodParams(method);
1899                 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1900                 boolean structExist = false;
1901                 // Check for params with structs
1902                 for (int i = 0; i < methParams.size(); i++) {
1903                         String paramType = methPrmTypes.get(i);
1904                         String param = methParams.get(i);
1905                         String simpleType = getSimpleType(paramType);
1906                         boolean begin = true;
1907                         if (isStructClass(simpleType)) {
1908                                 structExist = true;
1909                                 if (!begin) {
1910                                         print(", "); begin = false;
1911                                 }
1912                                 int methodNumId = intDecl.getMethodNumId(method);
1913                                 print("struct" + methodNumId + "Size" + i);
1914                         }
1915                 }
1916                 return structExist;
1917         }
1918
1919
1920         /**
1921          * HELPER: writeMethodCallStructSkeleton() writes method call for wait invoke in skeleton
1922          */
1923         private void writeMethodCallStructSkeleton(Collection<String> methods, InterfaceDecl intDecl) {
1924
1925                 // Use this set to handle two same methodIds
1926                 for (String method : methods) {
1927
1928                         List<String> methParams = intDecl.getMethodParams(method);
1929                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1930                         // Check for params with structs
1931                         for (int i = 0; i < methParams.size(); i++) {
1932                                 String paramType = methPrmTypes.get(i);
1933                                 String param = methParams.get(i);
1934                                 String simpleType = getSimpleType(paramType);
1935                                 if (isStructClass(simpleType)) {
1936                                         int methodNumId = intDecl.getMethodNumId(method);
1937                                         print("case ");
1938                                         String helperMethod = methodNumId + "struct" + i;
1939                                         String tempVar = "struct" + methodNumId + "Size" + i;
1940                                         print(intDecl.getHelperMethodNumId(helperMethod) + ": ");
1941                                         print(tempVar + " = ___");
1942                                         println(helperMethod + "(); break;");
1943                                 }
1944                         }
1945                 }
1946         }
1947
1948
1949         /**
1950          * HELPER: writeMethodCallStructCallbackSkeleton() writes method call for wait invoke in skeleton
1951          */
1952         private void writeMethodCallStructCallbackSkeleton(Collection<String> methods, InterfaceDecl intDecl) {
1953
1954                 // Use this set to handle two same methodIds
1955                 for (String method : methods) {
1956
1957                         List<String> methParams = intDecl.getMethodParams(method);
1958                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1959                         // Check for params with structs
1960                         for (int i = 0; i < methParams.size(); i++) {
1961                                 String paramType = methPrmTypes.get(i);
1962                                 String param = methParams.get(i);
1963                                 String simpleType = getSimpleType(paramType);
1964                                 if (isStructClass(simpleType)) {
1965                                         int methodNumId = intDecl.getMethodNumId(method);
1966                                         print("case ");
1967                                         String helperMethod = methodNumId + "struct" + i;
1968                                         String tempVar = "struct" + methodNumId + "Size" + i;
1969                                         print(intDecl.getHelperMethodNumId(helperMethod) + ": ");
1970                                         print(tempVar + " = ___");
1971                                         println(helperMethod + "(rmiObj); break;");
1972                                 }
1973                         }
1974                 }
1975         }
1976
1977
1978         /**
1979          * HELPER: writeJavaMethodPermission() writes permission checks in skeleton
1980          */
1981         private void writeJavaMethodPermission(String intface) {
1982
1983                 // Get all the different stubs
1984                 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
1985                 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
1986                         String newIntface = intMeth.getKey();
1987                         int newObjectId = getNewIntfaceObjectId(newIntface);
1988                         println("if (_objectId == object" + newObjectId + "Id) {");
1989                         println("if (!set" + newObjectId + "Allowed.contains(methodId)) {");
1990                         println("throw new Error(\"Object with object Id: \" + _objectId + \"  is not allowed to access method: \" + methodId);");
1991                         println("}");
1992                         println("}");
1993                         println("else {");
1994                         println("throw new Error(\"Object Id: \" + _objectId + \" not recognized!\");");
1995                         println("}");
1996                 }
1997         }
1998
1999
2000         /**
2001          * HELPER: writeJavaWaitRequestInvokeMethod() writes the main loop of the skeleton class
2002          */
2003         private void writeJavaWaitRequestInvokeMethod(Collection<String> methods, InterfaceDecl intDecl, boolean callbackExist, String intface) {
2004
2005                 // Use this set to handle two same methodIds
2006                 Set<String> uniqueMethodIds = new HashSet<String>();
2007                 println("private void ___waitRequestInvokeMethod() throws IOException {");
2008                 // Write variables here if we have callbacks or enums or structs
2009                 writeCountVarStructSkeleton(methods, intDecl);
2010                 println("while (true) {");
2011                 println("rmiObj.getMethodBytes();");
2012                 println("int _objectId = rmiObj.getObjectId();");
2013                 println("int methodId = rmiObj.getMethodId();");
2014                 // Generate permission check
2015                 writeJavaMethodPermission(intface);
2016                 println("switch (methodId) {");
2017                 // Print methods and method Ids
2018                 for (String method : methods) {
2019                         String methodId = intDecl.getMethodId(method);
2020                         int methodNumId = intDecl.getMethodNumId(method);
2021                         print("case " + methodNumId + ": ___");
2022                         String helperMethod = methodId;
2023                         if (uniqueMethodIds.contains(methodId))
2024                                 helperMethod = helperMethod + methodNumId;
2025                         else
2026                                 uniqueMethodIds.add(methodId);
2027                         print(helperMethod + "(");
2028                         writeInputCountVarStructSkeleton(method, intDecl);
2029                         println("); break;");
2030                 }
2031                 String method = "___initCallBack()";
2032                 // Print case -9999 (callback handler) if callback exists
2033                 if (callbackExist) {
2034                         int methodId = intDecl.getHelperMethodNumId(method);
2035                         println("case " + methodId + ": ___regCB(); break;");
2036                 }
2037                 writeMethodCallStructSkeleton(methods, intDecl);
2038                 println("default: ");
2039                 println("throw new Error(\"Method Id \" + methodId + \" not recognized!\");");
2040                 println("}");
2041                 println("}");
2042                 println("}\n");
2043         }
2044
2045
2046         /**
2047          * generateJavaSkeletonClass() generate skeletons based on the methods list in Java
2048          */
2049         public void generateJavaSkeletonClass() throws IOException {
2050
2051                 // Create a new directory
2052                 String path = createDirectories(dir, subdir);
2053                 for (String intface : mapIntfacePTH.keySet()) {
2054                         // Open a new file to write into
2055                         String newSkelClass = intface + "_Skeleton";
2056                         FileWriter fw = new FileWriter(path + "/" + newSkelClass + ".java");
2057                         pw = new PrintWriter(new BufferedWriter(fw));
2058                         // Pass in set of methods and get import classes
2059                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2060                         InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
2061                         List<String> methods = intDecl.getMethods();
2062                         Set<String> importClasses = getImportClasses(methods, intDecl);
2063                         List<String> stdImportClasses = getStandardJavaImportClasses();
2064                         List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
2065                         printImportStatements(allImportClasses);
2066                         // Find out if there are callback objects
2067                         Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
2068                         boolean callbackExist = !callbackClasses.isEmpty();
2069                         // Write class header
2070                         println("");
2071                         println("public class " + newSkelClass  + " implements " + intface + " {\n");
2072                         // Write properties
2073                         writePropertiesJavaSkeleton(intface, callbackExist, intDecl);
2074                         // Write constructor
2075                         writeConstructorJavaSkeleton(newSkelClass, intface);
2076                         // Write methods
2077                         writeMethodJavaSkeleton(methods, intDecl, callbackClasses, false);
2078                         // Write method helper
2079                         writeMethodHelperJavaSkeleton(methods, intDecl, callbackClasses);
2080                         // Write waitRequestInvokeMethod() - main loop
2081                         writeJavaWaitRequestInvokeMethod(methods, intDecl, callbackExist, intface);
2082                         println("}");
2083                         pw.close();
2084                         System.out.println("IoTCompiler: Generated skeleton class " + newSkelClass + ".java...");
2085                 }
2086         }
2087
2088
2089         /**
2090          * HELPER: writePropertiesJavaCallbackSkeleton() writes the properties of the callback skeleton class
2091          */
2092         private void writePropertiesJavaCallbackSkeleton(String intface, boolean callbackExist) {
2093
2094                 println("private " + intface + " mainObj;");
2095                 // For callback skeletons, this is its own object Id
2096                 println("private static int objectId = 0;");
2097                 // Callback
2098                 if (callbackExist) {
2099                         println("private static int objIdCnt = 0;");
2100                         println("private IoTRMICall rmiCall;");
2101                 }
2102                 println("\n");
2103         }
2104
2105
2106         /**
2107          * HELPER: writeConstructorJavaCallbackSkeleton() writes the constructor of the skeleton class
2108          */
2109         private void writeConstructorJavaCallbackSkeleton(String newSkelClass, String intface) {
2110
2111                 println("public " + newSkelClass + "(" + intface + " _mainObj, int _objectId) throws Exception {");
2112                 println("mainObj = _mainObj;");
2113                 println("objectId = _objectId;");
2114                 println("}\n");
2115         }
2116
2117
2118         /**
2119          * HELPER: writeMethodHelperJavaCallbackSkeleton() writes the method helper of the callback skeleton class
2120          */
2121         private void writeMethodHelperJavaCallbackSkeleton(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
2122
2123                 // Use this set to handle two same methodIds
2124                 Set<String> uniqueMethodIds = new HashSet<String>();
2125                 for (String method : methods) {
2126
2127                         List<String> methParams = intDecl.getMethodParams(method);
2128                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2129                         if (isStructPresent(methParams, methPrmTypes)) {        // Treat struct differently
2130                                 String methodId = intDecl.getMethodId(method);
2131                                 print("public void ___");
2132                                 String helperMethod = methodId;
2133                                 if (uniqueMethodIds.contains(methodId))
2134                                         helperMethod = helperMethod + intDecl.getMethodNumId(method);
2135                                 else
2136                                         uniqueMethodIds.add(methodId);
2137                                 String retType = intDecl.getMethodType(method);
2138                                 print(helperMethod + "(");
2139                                 boolean begin = true;
2140                                 for (int i = 0; i < methParams.size(); i++) { // Print size variables
2141                                         String paramType = methPrmTypes.get(i);
2142                                         String param = methParams.get(i);
2143                                         String simpleType = getSimpleType(paramType);
2144                                         if (isStructClass(simpleType)) {
2145                                                 if (!begin) {   // Generate comma for not the beginning variable
2146                                                         print(", "); begin = false;
2147                                                 }
2148                                                 int methodNumId = intDecl.getMethodNumId(method);
2149                                                 print("int struct" + methodNumId + "Size" + i);
2150                                         }
2151                                 }
2152                                 // Check if this is "void"
2153                                 if (retType.equals("void"))
2154                                         println(", IoTRMIObject rmiObj) {");
2155                                 else
2156                                         println(", IoTRMIObject rmiObj) throws IOException {");
2157                                 writeMethodHelperStructJavaSkeleton(intDecl, methParams, methPrmTypes, method, callbackClasses);
2158                                 println("}\n");
2159                         } else {
2160                                 String methodId = intDecl.getMethodId(method);
2161                                 print("public void ___");
2162                                 String helperMethod = methodId;
2163                                 if (uniqueMethodIds.contains(methodId))
2164                                         helperMethod = helperMethod + intDecl.getMethodNumId(method);
2165                                 else
2166                                         uniqueMethodIds.add(methodId);
2167                                 // Check if this is "void"
2168                                 String retType = intDecl.getMethodType(method);
2169                                 if (retType.equals("void"))
2170                                         println(helperMethod + "(IoTRMIObject rmiObj) {");
2171                                 else
2172                                         println(helperMethod + "(IoTRMIObject rmiObj) throws IOException {");
2173                                 // Now, write the helper body of skeleton!
2174                                 writeStdMethodHelperBodyJavaSkeleton(intDecl, methParams, methPrmTypes, method, callbackClasses);
2175                                 println("}\n");
2176                         }
2177                 }
2178                 // Write method helper for structs
2179                 writeMethodHelperStructSetupJavaCallbackSkeleton(methods, intDecl);
2180         }
2181
2182
2183         /**
2184          * HELPER: writeJavaCallbackWaitRequestInvokeMethod() writes the request invoke method of the callback skeleton class
2185          */
2186         private void writeJavaCallbackWaitRequestInvokeMethod(Collection<String> methods, InterfaceDecl intDecl, boolean callbackExist) {
2187
2188                 // Use this set to handle two same methodIds
2189                 Set<String> uniqueMethodIds = new HashSet<String>();
2190                 println("public void invokeMethod(IoTRMIObject rmiObj) throws IOException {");
2191                 // Write variables here if we have callbacks or enums or structs
2192                 writeCountVarStructSkeleton(methods, intDecl);
2193                 // Write variables here if we have callbacks or enums or structs
2194                 println("int methodId = rmiObj.getMethodId();");
2195                 // TODO: code the permission check here!
2196                 println("switch (methodId) {");
2197                 // Print methods and method Ids
2198                 for (String method : methods) {
2199                         String methodId = intDecl.getMethodId(method);
2200                         int methodNumId = intDecl.getMethodNumId(method);
2201                         print("case " + methodNumId + ": ___");
2202                         String helperMethod = methodId;
2203                         if (uniqueMethodIds.contains(methodId))
2204                                 helperMethod = helperMethod + methodNumId;
2205                         else
2206                                 uniqueMethodIds.add(methodId);
2207                         print(helperMethod + "(");
2208                         if (writeInputCountVarStructSkeleton(method, intDecl))
2209                                 println(", rmiObj); break;");
2210                         else
2211                                 println("rmiObj); break;");
2212                 }
2213                 String method = "___initCallBack()";
2214                 // Print case -9999 (callback handler) if callback exists
2215                 if (callbackExist) {
2216                         int methodId = intDecl.getHelperMethodNumId(method);
2217                         println("case " + methodId + ": ___regCB(rmiObj); break;");
2218                 }
2219                 writeMethodCallStructCallbackSkeleton(methods, intDecl);
2220                 println("default: ");
2221                 println("throw new Error(\"Method Id \" + methodId + \" not recognized!\");");
2222                 println("}");
2223                 println("}\n");
2224         }
2225
2226
2227         /**
2228          * generateJavaCallbackSkeletonClass() generate callback skeletons based on the methods list in Java
2229          */
2230         public void generateJavaCallbackSkeletonClass() throws IOException {
2231
2232                 // Create a new directory
2233                 String path = createDirectories(dir, subdir);
2234                 for (String intface : mapIntfacePTH.keySet()) {
2235                         // Open a new file to write into
2236                         String newSkelClass = intface + "_CallbackSkeleton";
2237                         FileWriter fw = new FileWriter(path + "/" + newSkelClass + ".java");
2238                         pw = new PrintWriter(new BufferedWriter(fw));
2239                         // Pass in set of methods and get import classes
2240                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2241                         InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
2242                         List<String> methods = intDecl.getMethods();
2243                         Set<String> importClasses = getImportClasses(methods, intDecl);
2244                         List<String> stdImportClasses = getStandardJavaImportClasses();
2245                         List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
2246                         printImportStatements(allImportClasses);
2247                         // Find out if there are callback objects
2248                         Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
2249                         boolean callbackExist = !callbackClasses.isEmpty();
2250                         // Write class header
2251                         println("");
2252                         println("public class " + newSkelClass  + " implements " + intface + " {\n");
2253                         // Write properties
2254                         writePropertiesJavaCallbackSkeleton(intface, callbackExist);
2255                         // Write constructor
2256                         writeConstructorJavaCallbackSkeleton(newSkelClass, intface);
2257                         // Write methods
2258                         writeMethodJavaSkeleton(methods, intDecl, callbackClasses, true);
2259                         // Write method helper
2260                         writeMethodHelperJavaCallbackSkeleton(methods, intDecl, callbackClasses);
2261                         // Write waitRequestInvokeMethod() - main loop
2262                         writeJavaCallbackWaitRequestInvokeMethod(methods, intDecl, callbackExist);
2263                         println("}");
2264                         pw.close();
2265                         System.out.println("IoTCompiler: Generated callback skeleton class " + newSkelClass + ".java...");
2266                 }
2267         }
2268
2269
2270         /**
2271          * HELPER: writeMethodCplusLocalInterface() writes the method of the local interface
2272          */
2273         private void writeMethodCplusLocalInterface(Collection<String> methods, InterfaceDecl intDecl) {
2274
2275                 for (String method : methods) {
2276
2277                         List<String> methParams = intDecl.getMethodParams(method);
2278                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2279                         print("virtual " + checkAndGetCplusType(intDecl.getMethodType(method)) + " " +
2280                                 intDecl.getMethodId(method) + "(");
2281                         for (int i = 0; i < methParams.size(); i++) {
2282                                 // Check for params with driver class types and exchange it 
2283                                 //              with its remote interface
2284                                 String paramType = checkAndGetParamClass(methPrmTypes.get(i));
2285                                 paramType = checkAndGetCplusType(paramType);
2286                                 // Check for arrays - translate into vector in C++
2287                                 String paramComplete = checkAndGetCplusArray(paramType, methParams.get(i));
2288                                 print(paramComplete);
2289                                 // Check if this is the last element (don't print a comma)
2290                                 if (i != methParams.size() - 1) {
2291                                         print(", ");
2292                                 }
2293                         }
2294                         println(") = 0;");
2295                 }
2296         }
2297
2298
2299         /**
2300          * HELPER: writeMethodCplusInterface() writes the method of the interface
2301          */
2302         private void writeMethodCplusInterface(Collection<String> methods, InterfaceDecl intDecl) {
2303
2304                 for (String method : methods) {
2305
2306                         List<String> methParams = intDecl.getMethodParams(method);
2307                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2308                         print("virtual " + checkAndGetCplusType(intDecl.getMethodType(method)) + " " +
2309                                 intDecl.getMethodId(method) + "(");
2310                         for (int i = 0; i < methParams.size(); i++) {
2311                                 // Check for params with driver class types and exchange it 
2312                                 //              with its remote interface
2313                                 String paramType = methPrmTypes.get(i);
2314                                 paramType = checkAndGetCplusType(paramType);
2315                                 // Check for arrays - translate into vector in C++
2316                                 String paramComplete = checkAndGetCplusArray(paramType, methParams.get(i));
2317                                 print(paramComplete);
2318                                 // Check if this is the last element (don't print a comma)
2319                                 if (i != methParams.size() - 1) {
2320                                         print(", ");
2321                                 }
2322                         }
2323                         println(") = 0;");
2324                 }
2325         }
2326
2327
2328         /**
2329          * HELPER: generateEnumCplus() writes the enumeration declaration
2330          */
2331         public void generateEnumCplus() throws IOException {
2332
2333                 // Create a new directory
2334                 createDirectory(dir);
2335                 for (String intface : mapIntfacePTH.keySet()) {
2336                         // Get the right StructDecl
2337                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2338                         EnumDecl enumDecl = (EnumDecl) decHandler.getEnumDecl(intface);
2339                         Set<String> enumTypes = enumDecl.getEnumDeclarations();
2340                         // Iterate over enum declarations
2341                         for (String enType : enumTypes) {
2342                                 // Open a new file to write into
2343                                 FileWriter fw = new FileWriter(dir + "/" + enType + ".hpp");
2344                                 pw = new PrintWriter(new BufferedWriter(fw));
2345                                 // Write file headers
2346                                 println("#ifndef _" + enType.toUpperCase() + "_HPP__");
2347                                 println("#define _" + enType.toUpperCase() + "_HPP__");
2348                                 println("enum " + enType + " {");
2349                                 List<String> enumMembers = enumDecl.getMembers(enType);
2350                                 for (int i = 0; i < enumMembers.size(); i++) {
2351
2352                                         String member = enumMembers.get(i);
2353                                         print(member);
2354                                         // Check if this is the last element (don't print a comma)
2355                                         if (i != enumMembers.size() - 1)
2356                                                 println(",");
2357                                         else
2358                                                 println("");
2359                                 }
2360                                 println("};\n");
2361                                 println("#endif");
2362                                 pw.close();
2363                                 System.out.println("IoTCompiler: Generated enum " + enType + ".hpp...");
2364                         }
2365                 }
2366         }
2367
2368
2369         /**
2370          * HELPER: generateStructCplus() writes the struct declaration
2371          */
2372         public void generateStructCplus() throws IOException {
2373
2374                 // Create a new directory
2375                 createDirectory(dir);
2376                 for (String intface : mapIntfacePTH.keySet()) {
2377                         // Get the right StructDecl
2378                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2379                         StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
2380                         List<String> structTypes = structDecl.getStructTypes();
2381                         // Iterate over enum declarations
2382                         for (String stType : structTypes) {
2383                                 // Open a new file to write into
2384                                 FileWriter fw = new FileWriter(dir + "/" + stType + ".hpp");
2385                                 pw = new PrintWriter(new BufferedWriter(fw));
2386                                 // Write file headers
2387                                 println("#ifndef _" + stType.toUpperCase() + "_HPP__");
2388                                 println("#define _" + stType.toUpperCase() + "_HPP__");
2389                                 println("struct " + stType + " {");
2390                                 List<String> structMemberTypes = structDecl.getMemberTypes(stType);
2391                                 List<String> structMembers = structDecl.getMembers(stType);
2392                                 for (int i = 0; i < structMembers.size(); i++) {
2393
2394                                         String memberType = structMemberTypes.get(i);
2395                                         String member = structMembers.get(i);
2396                                         String structTypeC = checkAndGetCplusType(memberType);
2397                                         String structComplete = checkAndGetCplusArray(structTypeC, member);
2398                                         println(structComplete + ";");
2399                                 }
2400                                 println("};\n");
2401                                 println("#endif");
2402                                 pw.close();
2403                                 System.out.println("IoTCompiler: Generated struct " + stType + ".hpp...");
2404                         }
2405                 }
2406         }
2407
2408
2409         /**
2410          * generateCplusLocalInterfaces() writes the local interfaces and provides type-checking.
2411          * <p>
2412          * It needs to rewrite and exchange USERDEFINED types in input parameters of stub
2413          * and original interfaces, e.g. exchange Camera and CameraWithVideoAndRecording.
2414          * The local interface has to be the input parameter for the stub and the stub 
2415          * interface has to be the input parameter for the local class.
2416          */
2417         public void generateCplusLocalInterfaces() throws IOException {
2418
2419                 // Create a new directory
2420                 createDirectory(dir);
2421                 for (String intface : mapIntfacePTH.keySet()) {
2422                         // Open a new file to write into
2423                         FileWriter fw = new FileWriter(dir + "/" + intface + ".hpp");
2424                         pw = new PrintWriter(new BufferedWriter(fw));
2425                         // Write file headers
2426                         println("#ifndef _" + intface.toUpperCase() + "_HPP__");
2427                         println("#define _" + intface.toUpperCase() + "_HPP__");
2428                         println("#include <iostream>");
2429                         // Pass in set of methods and get include classes
2430                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2431                         InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
2432                         List<String> methods = intDecl.getMethods();
2433                         Set<String> includeClasses = getIncludeClasses(methods, intDecl, intface, true);
2434                         printIncludeStatements(includeClasses); println("");
2435                         println("using namespace std;\n");
2436                         //writeStructCplus(structDecl);
2437                         println("class " + intface); println("{");
2438                         println("public:");
2439                         // Write methods
2440                         writeMethodCplusLocalInterface(methods, intDecl);
2441                         println("};");
2442                         println("#endif");
2443                         pw.close();
2444                         System.out.println("IoTCompiler: Generated local interface " + intface + ".hpp...");
2445                 }
2446         }
2447
2448
2449         /**
2450          * generateCPlusInterfaces() generate stub interfaces based on the methods list in C++
2451          * <p>
2452          * For C++ we use virtual classe as interface
2453          */
2454         public void generateCPlusInterfaces() throws IOException {
2455
2456                 // Create a new directory
2457                 String path = createDirectories(dir, subdir);
2458                 for (String intface : mapIntfacePTH.keySet()) {
2459
2460                         Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
2461                         for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
2462
2463                                 // Open a new file to write into
2464                                 String newIntface = intMeth.getKey();
2465                                 FileWriter fw = new FileWriter(path + "/" + newIntface + ".hpp");
2466                                 pw = new PrintWriter(new BufferedWriter(fw));
2467                                 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2468                                 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
2469                                 // Write file headers
2470                                 println("#ifndef _" + newIntface.toUpperCase() + "_HPP__");
2471                                 println("#define _" + newIntface.toUpperCase() + "_HPP__");
2472                                 println("#include <iostream>");
2473                                 // Pass in set of methods and get import classes
2474                                 Set<String> includeClasses = getIncludeClasses(intMeth.getValue(), intDecl, intface, false);
2475                                 List<String> stdIncludeClasses = getStandardCplusIncludeClasses();
2476                                 List<String> allIncludeClasses = getAllLibClasses(stdIncludeClasses, includeClasses);
2477                                 printIncludeStatements(allIncludeClasses); println("");                 
2478                                 println("using namespace std;\n");
2479                                 println("class " + newIntface);
2480                                 println("{");
2481                                 println("public:");
2482                                 // Write methods
2483                                 writeMethodCplusInterface(intMeth.getValue(), intDecl);
2484                                 println("};");
2485                                 println("#endif");
2486                                 pw.close();
2487                                 System.out.println("IoTCompiler: Generated interface " + newIntface + ".hpp...");
2488                         }
2489                 }
2490         }
2491
2492
2493         /**
2494          * HELPER: writeMethodCplusStub() writes the methods of the stub
2495          */
2496         private void writeMethodCplusStub(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
2497
2498                 for (String method : methods) {
2499
2500                         List<String> methParams = intDecl.getMethodParams(method);
2501                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2502
2503                         //System.out.println("\n\nMethod return type: " + checkAndGetCplusType(intDecl.getMethodType(method)) + "\n\n");
2504
2505                         print(checkAndGetCplusType(intDecl.getMethodType(method)) + " " +
2506                                 intDecl.getMethodId(method) + "(");
2507                         boolean isCallbackMethod = false;
2508                         String callbackType = null;
2509                         for (int i = 0; i < methParams.size(); i++) {
2510
2511                                 String paramType = methPrmTypes.get(i);
2512                                 // Check if this has callback object
2513                                 if (callbackClasses.contains(paramType)) {
2514                                         isCallbackMethod = true;
2515                                         callbackType = paramType;       
2516                                         // Even if there're 2 callback arguments, we expect them to be of the same interface
2517                                 }
2518                                 String methPrmType = checkAndGetCplusType(methPrmTypes.get(i));
2519                                 String methParamComplete = checkAndGetCplusArray(methPrmType, methParams.get(i));
2520                                 print(methParamComplete);
2521                                 // Check if this is the last element (don't print a comma)
2522                                 if (i != methParams.size() - 1) {
2523                                         print(", ");
2524                                 }
2525                         }
2526                         println(") { ");
2527                         if (isCallbackMethod)
2528                                 writeCallbackMethodBodyCplusStub(intDecl, methParams, methPrmTypes, method, callbackType);
2529                         else
2530                                 writeStdMethodBodyCplusStub(intDecl, methParams, methPrmTypes, method);
2531                         println("}\n");
2532                         // Write the init callback helper method
2533                         if (isCallbackMethod) {
2534                                 writeInitCallbackCplusStub(callbackType, intDecl);
2535                                 writeInitCallbackSendInfoCplusStub(intDecl);
2536                         }
2537                 }
2538         }
2539
2540
2541         /**
2542          * HELPER: writeCallbackMethodBodyCplusStub() writes the callback method of the stub class
2543          */
2544         private void writeCallbackMethodBodyCplusStub(InterfaceDecl intDecl, List<String> methParams,
2545                         List<String> methPrmTypes, String method, String callbackType) {
2546
2547                 // Check if this is single object, array, or list of objects
2548                 boolean isArrayOrList = false;
2549                 String callbackParam = null;
2550                 for (int i = 0; i < methParams.size(); i++) {
2551
2552                         String paramType = methPrmTypes.get(i);
2553                         if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
2554                                 String param = methParams.get(i);
2555                                 if (isArrayOrList(paramType, param)) {  // Generate loop
2556                                         println("for (" + paramType + "* cb : " + getSimpleIdentifier(param) + ") {");
2557                                         println(callbackType + "_CallbackSkeleton* skel = new " + callbackType + "_CallbackSkeleton(cb, objIdCnt++);");
2558                                         isArrayOrList = true;
2559                                         callbackParam = getSimpleIdentifier(param);
2560                                 } else
2561                                         println(callbackType + "_CallbackSkeleton* skel = new " + callbackType + "_CallbackSkeleton(" +
2562                                                 getSimpleIdentifier(param) + ", objIdCnt++);");
2563                                 println("vecCallbackObj.push_back(skel);");
2564                                 if (isArrayOrList(paramType, param))
2565                                         println("}");
2566                         }
2567                 }
2568                 println("int numParam = " + methParams.size() + ";");
2569                 println("int methodId = " + intDecl.getMethodNumId(method) + ";");
2570                 String retType = intDecl.getMethodType(method);
2571                 //String retTypeC = checkAndGetCplusType(retType);
2572                 //println("string retType = \"" + checkAndGetCplusArrayType(getStructType(getEnumType(retTypeC))) + "\";");
2573                 println("string retType = \"" + checkAndGetCplusRetClsType(getStructType(getEnumType(retType))) + "\";");
2574                 // Generate array of parameter types
2575                 print("string paramCls[] = { ");
2576                 for (int i = 0; i < methParams.size(); i++) {
2577                         String paramType = methPrmTypes.get(i);
2578                         if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
2579                                 print("\"int\"");
2580                         } else { // Generate normal classes if it's not a callback object
2581                                 //String paramTypeC = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
2582                                 //String prmType = getSimpleType(getEnumType(paramTypeC));
2583                                 String paramTypeC = checkAndGetCplusArgClsType(methPrmTypes.get(i), methParams.get(i));
2584                                 String prmType = getEnumType(paramTypeC);
2585                                 print("\"" + prmType + "\"");
2586                         }
2587                         if (i != methParams.size() - 1) // Check if this is the last element
2588                                 print(", ");
2589                 }
2590                 println(" };");
2591                 print("int ___paramCB = ");
2592                 if (isArrayOrList)
2593                         println(callbackParam + ".size();");
2594                 else
2595                         println("1;");
2596                 // Generate array of parameter objects
2597                 print("void* paramObj[] = { ");
2598                 for (int i = 0; i < methParams.size(); i++) {
2599                         String paramType = methPrmTypes.get(i);
2600                         if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
2601                                 print("&___paramCB");
2602                         } else
2603                                 print(getSimpleIdentifier(methParams.get(i)));
2604                         if (i != methParams.size() - 1)
2605                                 print(", ");
2606                 }
2607                 println(" };");
2608                 // Check if this is "void"
2609                 if (retType.equals("void")) {
2610                         println("void* retObj = NULL;");
2611                         println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
2612                 } else { // We do have a return value
2613                         if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
2614                                 println(checkAndGetCplusType(retType) + " retVal;");
2615                         else
2616                                 println(checkAndGetCplusType(retType) + " retVal = " + generateCplusInitializer(retType) + ";");
2617                         println("void* retObj = &retVal;");
2618                         println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
2619                         println("return retVal;");
2620                 }
2621         }
2622
2623
2624         /**
2625          * HELPER: checkAndWriteEnumTypeCplusStub() writes the enum type (convert from enum to int)
2626          */
2627         private void checkAndWriteEnumTypeCplusStub(List<String> methParams, List<String> methPrmTypes) {
2628
2629                 // Iterate and find enum declarations
2630                 for (int i = 0; i < methParams.size(); i++) {
2631                         String paramType = methPrmTypes.get(i);
2632                         String param = methParams.get(i);
2633                         String simpleType = getSimpleType(paramType);
2634                         if (isEnumClass(simpleType)) {
2635                         // Check if this is enum type
2636                                 if (isArrayOrList(paramType, param)) {  // An array or vector
2637                                         println("int len" + i + " = " + param + ".size();");
2638                                         println("vector<int> paramEnum" + i + "(len);");
2639                                         println("for (int i = 0; i < len" + i + "; i++) {");
2640                                         println("paramEnum" + i + "[i] = (int) " + param + "[i];");
2641                                         println("}");
2642                                 } else {        // Just one element
2643                                         println("vector<int> paramEnum" + i + "(1);");
2644                                         println("paramEnum" + i + "[0] = (int) " + param + ";");
2645                                 }
2646                         }
2647                 }
2648         }
2649
2650
2651         /**
2652          * HELPER: checkAndWriteEnumRetTypeCplusStub() writes the enum return type (convert from enum to int)
2653          */
2654         private void checkAndWriteEnumRetTypeCplusStub(String retType) {
2655
2656                 // Strips off array "[]" for return type
2657                 String pureType = getSimpleArrayType(getSimpleType(retType));
2658                 // Take the inner type of generic
2659                 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
2660                         pureType = getTypeOfGeneric(retType)[0];
2661                 if (isEnumClass(pureType)) {
2662                 // Check if this is enum type
2663                         println("vector<int> retEnumInt;");
2664                         println("void* retObj = &retEnumInt;");
2665                         println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
2666                         if (isArrayOrList(retType, retType)) {  // An array or vector
2667                                 println("int retLen = retEnumInt.size();");
2668                                 println("vector<" + pureType + "> retVal(retLen);");
2669                                 println("for (int i = 0; i < retLen; i++) {");
2670                                 println("retVal[i] = (" + pureType + ") retEnumInt[i];");
2671                                 println("}");
2672                         } else {        // Just one element
2673                                 println(pureType + " retVal = (" + pureType + ") retEnumInt[0];");
2674                         }
2675                         println("return retVal;");
2676                 }
2677         }
2678
2679
2680         /**
2681          * HELPER: checkAndWriteStructSetupCplusStub() writes the struct type setup
2682          */
2683         private void checkAndWriteStructSetupCplusStub(List<String> methParams, List<String> methPrmTypes, 
2684                         InterfaceDecl intDecl, String method) {
2685                 
2686                 // Iterate and find struct declarations
2687                 for (int i = 0; i < methParams.size(); i++) {
2688                         String paramType = methPrmTypes.get(i);
2689                         String param = methParams.get(i);
2690                         String simpleType = getSimpleType(paramType);
2691                         if (isStructClass(simpleType)) {
2692                         // Check if this is enum type
2693                                 println("int numParam" + i + " = 1;");
2694                                 int methodNumId = intDecl.getMethodNumId(method);
2695                                 String helperMethod = methodNumId + "struct" + i;
2696                                 println("int methodIdStruct" + i + " = " + intDecl.getHelperMethodNumId(helperMethod) + ";");
2697                                 println("string retTypeStruct" + i + " = \"void\";");
2698                                 println("string paramClsStruct" + i + "[] = { \"int\" };");
2699                                 print("int structLen" + i + " = ");
2700                                 if (isArrayOrList(param, paramType)) {  // An array
2701                                         println(getSimpleArrayType(param) + ".size();");
2702                                 } else {        // Just one element
2703                                         println("1;");
2704                                 }
2705                                 println("void* paramObjStruct" + i + "[] = { &structLen" + i + " };");
2706                                 println("void* retStructLen" + i + " = NULL;");
2707                                 println("rmiCall->remoteCall(objectId, methodIdStruct" + i + 
2708                                                 ", retTypeStruct" + i + ", paramClsStruct" + i + ", paramObjStruct" + i + 
2709                                                 ", numParam" + i + ", retStructLen" + i + ");\n");
2710                         }
2711                 }
2712         }
2713
2714
2715         /**
2716          * HELPER: writeLengthStructParamClassCplusStub() writes lengths of params
2717          */
2718         private void writeLengthStructParamClassCplusStub(List<String> methParams, List<String> methPrmTypes) {
2719
2720                 // Iterate and find struct declarations - count number of params
2721                 for (int i = 0; i < methParams.size(); i++) {
2722                         String paramType = methPrmTypes.get(i);
2723                         String param = methParams.get(i);
2724                         String simpleType = getGenericType(paramType);
2725                         if (isStructClass(simpleType)) {
2726                                 int members = getNumOfMembers(simpleType);
2727                                 if (isArrayOrList(param, paramType)) {                  // An array
2728                                         String structLen = param + ".size()";
2729                                         print(members + "*" + structLen);
2730                                 } else
2731                                         print(Integer.toString(members));
2732                         } else
2733                                 print("1");
2734                         if (i != methParams.size() - 1) {
2735                                 print("+");
2736                         }
2737                 }
2738         }
2739
2740
2741         /**
2742          * HELPER: writeStructMembersCplusStub() writes member parameters of struct
2743          */
2744         private void writeStructMembersCplusStub(String simpleType, String paramType, String param) {
2745
2746                 // Get the struct declaration for this struct and generate initialization code
2747                 StructDecl structDecl = getStructDecl(simpleType);
2748                 List<String> memTypes = structDecl.getMemberTypes(simpleType);
2749                 List<String> members = structDecl.getMembers(simpleType);
2750                 if (isArrayOrList(param, paramType)) {  // An array or list
2751                         println("for(int i = 0; i < " + param + ".size(); i++) {");
2752                 }
2753                 if (isArrayOrList(param, paramType)) {  // An array or list
2754                         for (int i = 0; i < members.size(); i++) {
2755                                 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
2756                                 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
2757                                 println("paramCls[pos] = \"" + getSimpleType(getEnumType(prmType)) + "\";");
2758                                 print("paramObj[pos++] = &" + param + "[i].");
2759                                 print(getSimpleIdentifier(members.get(i)));
2760                                 println(";");
2761                         }
2762                         println("}");
2763                 } else {        // Just one struct element
2764                         for (int i = 0; i < members.size(); i++) {
2765                                 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
2766                                 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
2767                                 println("paramCls[pos] = \"" + getSimpleType(getEnumType(prmType)) + "\";");
2768                                 print("paramObj[pos++] = &" + param + ".");
2769                                 print(getSimpleIdentifier(members.get(i)));
2770                                 println(";");
2771                         }
2772                 }
2773         }
2774
2775
2776         /**
2777          * HELPER: writeStructParamClassCplusStub() writes member parameters of struct
2778          */
2779         private void writeStructParamClassCplusStub(List<String> methParams, List<String> methPrmTypes) {
2780
2781                 print("int numParam = ");
2782                 writeLengthStructParamClassCplusStub(methParams, methPrmTypes);
2783                 println(";");
2784                 println("void* paramObj[numParam];");
2785                 println("string paramCls[numParam];");
2786                 println("int pos = 0;");
2787                 // Iterate again over the parameters
2788                 for (int i = 0; i < methParams.size(); i++) {
2789                         String paramType = methPrmTypes.get(i);
2790                         String param = methParams.get(i);
2791                         String simpleType = getGenericType(paramType);
2792                         if (isStructClass(simpleType)) {
2793                                 writeStructMembersCplusStub(simpleType, paramType, param);
2794                         } else {
2795                                 String prmTypeC = checkAndGetCplusType(methPrmTypes.get(i));
2796                                 String prmType = checkAndGetCplusArrayType(prmTypeC, methParams.get(i));
2797                                 println("paramCls[pos] = \"" + getSimpleType(getEnumType(prmType)) + "\";");
2798                                 print("paramObj[pos++] = &");
2799                                 print(getEnumParam(methPrmTypes.get(i), getSimpleIdentifier(methParams.get(i)), i));
2800                                 println(";");
2801                         }
2802                 }
2803                 
2804         }
2805
2806
2807         /**
2808          * HELPER: writeStructRetMembersCplusStub() writes member parameters of struct for return statement
2809          */
2810         private void writeStructRetMembersCplusStub(String simpleType, String retType) {
2811
2812                 // Get the struct declaration for this struct and generate initialization code
2813                 StructDecl structDecl = getStructDecl(simpleType);
2814                 List<String> memTypes = structDecl.getMemberTypes(simpleType);
2815                 List<String> members = structDecl.getMembers(simpleType);
2816                 if (isArrayOrList(retType, retType)) {  // An array or list
2817                         println("for(int i = 0; i < retLen; i++) {");
2818                 }
2819                 if (isArrayOrList(retType, retType)) {  // An array or list
2820                         for (int i = 0; i < members.size(); i++) {
2821                                 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
2822                                 print("structRet[i]." + getSimpleIdentifier(members.get(i)));
2823                                 println(" = retParam" + i + "[i];");
2824                         }
2825                         println("}");
2826                 } else {        // Just one struct element
2827                         for (int i = 0; i < members.size(); i++) {
2828                                 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
2829                                 print("structRet." + getSimpleIdentifier(members.get(i)));
2830                                 println(" = retParam" + i + ";");
2831                         }
2832                 }
2833                 println("return structRet;");
2834         }
2835
2836
2837         /**
2838          * HELPER: writeStructReturnCplusStub() writes member parameters of struct for return statement
2839          */
2840         private void writeStructReturnCplusStub(String simpleType, String retType) {
2841
2842                 // Minimum retLen is 1 if this is a single struct object
2843                 println("int retLen = 0;");
2844                 println("void* retLenObj = { &retLen };");
2845                 // Handle the returned struct!!!
2846                 println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retLenObj);");
2847                 int numMem = getNumOfMembers(simpleType);
2848                 println("int numRet = " + numMem + "*retLen;");
2849                 println("string retCls[numRet];");
2850                 println("void* retObj[numRet];");
2851                 StructDecl structDecl = getStructDecl(simpleType);
2852                 List<String> memTypes = structDecl.getMemberTypes(simpleType);
2853                 List<String> members = structDecl.getMembers(simpleType);
2854                 // Set up variables
2855                 if (isArrayOrList(retType, retType)) {  // An array or list
2856                         for (int i = 0; i < members.size(); i++) {
2857                                 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
2858                                 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
2859                                 println(getSimpleType(getEnumType(prmType)) + " retParam" + i + "[retLen];");
2860                         }
2861                 } else {        // Just one struct element
2862                         for (int i = 0; i < members.size(); i++) {
2863                                 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
2864                                 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
2865                                 println(getSimpleType(getEnumType(prmType)) + " retParam" + i + ";");
2866                         }
2867                 }
2868                 println("int retPos = 0;");
2869                 // Get the struct declaration for this struct and generate initialization code
2870                 if (isArrayOrList(retType, retType)) {  // An array or list
2871                         println("for(int i = 0; i < retLen; i++) {");
2872                         for (int i = 0; i < members.size(); i++) {
2873                                 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
2874                                 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
2875                                 println("retCls[retPos] = \"" + getSimpleType(getEnumType(prmType)) + "\";");
2876                                 println("retObj[retPos++] = &retParam" + i + "[i];");
2877                         }
2878                         println("}");
2879                 } else {        // Just one struct element
2880                         for (int i = 0; i < members.size(); i++) {
2881                                 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
2882                                 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
2883                                 println("retCls[retPos] = \"" + getSimpleType(getEnumType(prmType)) + "\";");
2884                                 println("retObj[retPos++] = &retParam" + i + ";");
2885                         }
2886                 }
2887                 println("rmiCall->getStructObjects(retCls, numRet, retObj);");
2888                 if (isArrayOrList(retType, retType)) {  // An array or list
2889                         println("vector<" + simpleType + "> structRet(retLen);");
2890                 } else
2891                         println(simpleType + " structRet;");
2892                 writeStructRetMembersCplusStub(simpleType, retType);
2893         }
2894
2895
2896         /**
2897          * HELPER: writeStdMethodBodyCplusStub() writes the standard method body in the stub class
2898          */
2899         private void writeStdMethodBodyCplusStub(InterfaceDecl intDecl, List<String> methParams,
2900                         List<String> methPrmTypes, String method) {
2901
2902                 checkAndWriteStructSetupCplusStub(methParams, methPrmTypes, intDecl, method);
2903                 println("int methodId = " + intDecl.getMethodNumId(method) + ";");
2904                 String retType = intDecl.getMethodType(method);
2905                 //String retTypeC = checkAndGetCplusType(retType);
2906                 //println("string retType = \"" + checkAndGetCplusArrayType(getStructType(getEnumType(retTypeC))) + "\";");
2907                 println("string retType = \"" + checkAndGetCplusRetClsType(getStructType(getEnumType(retType))) + "\";");
2908                 // Generate array of parameter types
2909                 if (isStructPresent(methParams, methPrmTypes)) {
2910                         writeStructParamClassCplusStub(methParams, methPrmTypes);
2911                 } else {
2912                         println("int numParam = " + methParams.size() + ";");
2913                         print("string paramCls[] = { ");
2914                         for (int i = 0; i < methParams.size(); i++) {
2915                                 //String paramTypeC = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
2916                                 //String prmType = getSimpleType(getEnumType(paramTypeC));
2917                                 String paramTypeC = checkAndGetCplusArgClsType(methPrmTypes.get(i), methParams.get(i));
2918                                 String prmType = getEnumType(paramTypeC);
2919                                 print("\"" + prmType + "\"");
2920                                 // Check if this is the last element (don't print a comma)
2921                                 if (i != methParams.size() - 1) {
2922                                         print(", ");
2923                                 }