Cleaning up callback code generation; Fixing a few minor issues, e.g. indentation...
[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                 print("}");
512                 println(" else {");
513                 println("throw new Error(\"" + intface + ": Object with Id \" + objId + \" not found!\");");
514                 println("}");
515                 println("}");
516                 print("}");
517                 println(" catch (Exception ex) {");
518                 println("ex.printStackTrace();");
519                 println("throw new Error(\"Error instantiating class " + intface + "_CallbackSkeleton!\");");
520                 println("}");
521                 println("}");
522                 println("};");
523                 println("thread.start();\n");
524                 // Generate info sending part
525                 String method = "___initCallBack()";
526                 println("int methodId = " + intDecl.getHelperMethodNumId(method) + ";");
527                 println("Class<?> retType = void.class;");
528                 println("Class<?>[] paramCls = new Class<?>[] { int.class, String.class, int.class };");
529                 println("Object[] paramObj = new Object[] { ports[0], address, 0 };");
530                 println("rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
531                 println("}\n");
532         }
533
534
535         /**
536          * HELPER: checkAndWriteEnumTypeJavaStub() writes the enum type (convert from enum to int)
537          */
538         private void checkAndWriteEnumTypeJavaStub(List<String> methParams, List<String> methPrmTypes) {
539
540                 // Iterate and find enum declarations
541                 for (int i = 0; i < methParams.size(); i++) {
542                         String paramType = methPrmTypes.get(i);
543                         String param = methParams.get(i);
544                         String simpleType = getSimpleType(paramType);
545                         if (isEnumClass(simpleType)) {
546                         // Check if this is enum type
547                                 if (isArray(param)) {   // An array
548                                         println("int len" + i + " = " + param + ".length;");
549                                         println("int paramEnum" + i + "[] = new int[len];");
550                                         println("for (int i = 0; i < len" + i + "; i++) {");
551                                         println("paramEnum" + i + "[i] = " + param + "[i].ordinal();");
552                                         println("}");
553                                 } else if (isList(paramType)) { // A list
554                                         println("int len" + i + " = " + param + ".size();");
555                                         println("int paramEnum" + i + "[] = new int[len];");
556                                         println("for (int i = 0; i < len" + i + "; i++) {");
557                                         println("paramEnum" + i + "[i] = " + param + ".get(i).ordinal();");
558                                         println("}");
559                                 } else {        // Just one element
560                                         println("int paramEnum" + i + "[] = new int[1];");
561                                         println("paramEnum" + i + "[0] = " + param + ".ordinal();");
562                                 }
563                         }
564                 }
565         }
566
567
568         /**
569          * HELPER: checkAndWriteEnumRetTypeJavaStub() writes the enum return type (convert from enum to int)
570          */
571         private void checkAndWriteEnumRetTypeJavaStub(String retType) {
572
573                 // Strips off array "[]" for return type
574                 String pureType = getSimpleArrayType(getSimpleType(retType));
575                 // Take the inner type of generic
576                 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
577                         pureType = getTypeOfGeneric(retType)[0];
578                 if (isEnumClass(pureType)) {
579                 // Check if this is enum type
580                         // Enum decoder
581                         println("int[] retEnum = (int[]) retObj;");
582                         println(pureType + "[] enumVals = " + pureType + ".values();");
583                         if (isArray(retType)) {                 // An array
584                                 println("int retLen = retEnum.length;");
585                                 println(pureType + "[] enumRetVal = new " + pureType + "[retLen];");
586                                 println("for (int i = 0; i < retLen; i++) {");
587                                 println("enumRetVal[i] = enumVals[retEnum[i]];");
588                                 println("}");
589                         } else if (isList(retType)) {   // A list
590                                 println("int retLen = retEnum.length;");
591                                 println("List<" + pureType + "> enumRetVal = new ArrayList<" + pureType + ">();");
592                                 println("for (int i = 0; i < retLen; i++) {");
593                                 println("enumRetVal.add(enumVals[retEnum[i]]);");
594                                 println("}");
595                         } else {        // Just one element
596                                 println(pureType + " enumRetVal = enumVals[retEnum[0]];");
597                         }
598                         println("return enumRetVal;");
599                 }
600         }
601
602
603         /**
604          * HELPER: checkAndWriteStructSetupJavaStub() writes the struct type setup
605          */
606         private void checkAndWriteStructSetupJavaStub(List<String> methParams, List<String> methPrmTypes, 
607                         InterfaceDecl intDecl, String method) {
608                 
609                 // Iterate and find struct declarations
610                 for (int i = 0; i < methParams.size(); i++) {
611                         String paramType = methPrmTypes.get(i);
612                         String param = methParams.get(i);
613                         String simpleType = getSimpleType(paramType);
614                         if (isStructClass(simpleType)) {
615                         // Check if this is enum type
616                                 int methodNumId = intDecl.getMethodNumId(method);
617                                 String helperMethod = methodNumId + "struct" + i;
618                                 println("int methodIdStruct" + i + " = " + intDecl.getHelperMethodNumId(helperMethod) + ";");
619                                 println("Class<?> retTypeStruct" + i + " = void.class;");
620                                 println("Class<?>[] paramClsStruct" + i + " = new Class<?>[] { int.class };");
621                                 if (isArray(param)) {   // An array
622                                         println("Object[] paramObjStruct" + i + " = new Object[] { " + getSimpleArrayType(param) + ".length };");
623                                 } else if (isList(paramType)) { // A list
624                                         println("Object[] paramObjStruct" + i + " = new Object[] { " + getSimpleArrayType(param) + ".size() };");
625                                 } else {        // Just one element
626                                         println("Object[] paramObjStruct" + i + " = new Object[] { new Integer(1) };");
627                                 }
628                                 println("rmiCall.remoteCall(objectId, methodIdStruct" + i + 
629                                                 ", retTypeStruct" + i + ", null, paramClsStruct" + i + 
630                                                 ", paramObjStruct" + i + ");\n");
631                         }
632                 }
633         }
634
635
636         /**
637          * HELPER: isStructPresent() checks presence of struct
638          */
639         private boolean isStructPresent(List<String> methParams, List<String> methPrmTypes) {
640
641                 // Iterate and find enum declarations
642                 for (int i = 0; i < methParams.size(); i++) {
643                         String paramType = methPrmTypes.get(i);
644                         String param = methParams.get(i);
645                         String simpleType = getSimpleType(paramType);
646                         if (isStructClass(simpleType))
647                                 return true;
648                 }
649                 return false;
650         }
651
652
653         /**
654          * HELPER: writeLengthStructParamClassJavaStub() writes lengths of parameters
655          */
656         private void writeLengthStructParamClassJavaStub(List<String> methParams, List<String> methPrmTypes) {
657
658                 // Iterate and find struct declarations - count number of params
659                 for (int i = 0; i < methParams.size(); i++) {
660                         String paramType = methPrmTypes.get(i);
661                         String param = methParams.get(i);
662                         String simpleType = getGenericType(paramType);
663                         if (isStructClass(simpleType)) {
664                                 int members = getNumOfMembers(simpleType);
665                                 if (isArray(param)) {                   // An array
666                                         String structLen = param + ".length";
667                                         print(members + "*" + structLen);
668                                 } else if (isList(paramType)) { // A list
669                                         String structLen = param + ".size()";
670                                         print(members + "*" + structLen);
671                                 } else
672                                         print(Integer.toString(members));
673                         } else
674                                 print("1");
675                         if (i != methParams.size() - 1) {
676                                 print("+");
677                         }
678                 }
679         }
680
681
682         /**
683          * HELPER: writeStructMembersJavaStub() writes parameters of struct
684          */
685         private void writeStructMembersJavaStub(String simpleType, String paramType, String param) {
686
687                 // Get the struct declaration for this struct and generate initialization code
688                 StructDecl structDecl = getStructDecl(simpleType);
689                 List<String> memTypes = structDecl.getMemberTypes(simpleType);
690                 List<String> members = structDecl.getMembers(simpleType);
691                 if (isArray(param)) {                   // An array
692                         println("for(int i = 0; i < " + param + ".length; i++) {");
693                 } else if (isList(paramType)) { // A list
694                         println("for(int i = 0; i < " + param + ".size(); i++) {");
695                 }
696                 if (isArrayOrList(param, paramType)) {  // An array or list
697                         for (int i = 0; i < members.size(); i++) {
698                                 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
699                                 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
700                                 print("paramObj[pos++] = " + param + "[i].");
701                                 print(getSimpleIdentifier(members.get(i)));
702                                 println(";");
703                         }
704                         println("}");
705                 } else {        // Just one struct element
706                         for (int i = 0; i < members.size(); i++) {
707                                 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
708                                 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
709                                 print("paramObj[pos++] = " + param + ".");
710                                 print(getSimpleIdentifier(members.get(i)));
711                                 println(";");
712                         }
713                 }
714         }
715
716
717         /**
718          * HELPER: writeStructParamClassJavaStub() writes parameters if struct is present
719          */
720         private void writeStructParamClassJavaStub(List<String> methParams, List<String> methPrmTypes) {
721
722                 print("int paramLen = ");
723                 writeLengthStructParamClassJavaStub(methParams, methPrmTypes);
724                 println(";");
725                 println("Object[] paramObj = new Object[paramLen];");
726                 println("Class<?>[] paramCls = new Class<?>[paramLen];");
727                 println("int pos = 0;");
728                 // Iterate again over the parameters
729                 for (int i = 0; i < methParams.size(); i++) {
730                         String paramType = methPrmTypes.get(i);
731                         String param = methParams.get(i);
732                         String simpleType = getGenericType(paramType);
733                         if (isStructClass(simpleType)) {
734                                 writeStructMembersJavaStub(simpleType, paramType, param);
735                         } else {
736                                 String prmType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
737                                 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
738                                 print("paramObj[pos++] = ");
739                                 print(getEnumParam(methPrmTypes.get(i), getSimpleIdentifier(methParams.get(i)), i));
740                                 println(";");
741                         }
742                 }
743                 
744         }
745
746
747         /**
748          * HELPER: writeStructRetMembersJavaStub() writes parameters of struct for return statement
749          */
750         private void writeStructRetMembersJavaStub(String simpleType, String retType) {
751
752                 // Get the struct declaration for this struct and generate initialization code
753                 StructDecl structDecl = getStructDecl(simpleType);
754                 List<String> memTypes = structDecl.getMemberTypes(simpleType);
755                 List<String> members = structDecl.getMembers(simpleType);
756                 if (isArrayOrList(retType, retType)) {  // An array or list
757                         println("for(int i = 0; i < retLen; i++) {");
758                 }
759                 if (isArray(retType)) { // An array
760                         for (int i = 0; i < members.size(); i++) {
761                                 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
762                                 print("structRet[i]." + getSimpleIdentifier(members.get(i)));
763                                 println(" = (" + getSimpleType(getEnumType(prmType)) + ") retObj[retObjPos++];");
764                         }
765                         println("}");
766                 } else if (isList(retType)) {   // A list
767                         println(simpleType + " structRetMem = new " + simpleType + "();");
768                         for (int i = 0; i < members.size(); i++) {
769                                 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
770                                 print("structRetMem." + getSimpleIdentifier(members.get(i)));
771                                 println(" = (" + getSimpleType(getEnumType(prmType)) + ") retObj[retObjPos++];");
772                         }
773                         println("structRet.add(structRetMem);");
774                         println("}");
775                 } else {        // Just one struct element
776                         for (int i = 0; i < members.size(); i++) {
777                                 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
778                                 print("structRet." + getSimpleIdentifier(members.get(i)));
779                                 println(" = (" + getSimpleType(getEnumType(prmType)) + ") retObj[retObjPos++];");
780                         }
781                 }
782                 println("return structRet;");
783         }
784
785
786         /**
787          * HELPER: writeStructReturnJavaStub() writes parameters if struct is present for return statement
788          */
789         private void writeStructReturnJavaStub(String simpleType, String retType) {
790
791                 // Handle the returned struct!!!
792                 println("Object retLenObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
793                 // Minimum retLen is 1 if this is a single struct object
794                 println("int retLen = (int) retLenObj;");
795                 int numMem = getNumOfMembers(simpleType);
796                 println("Class<?>[] retCls = new Class<?>[" + numMem + "*retLen];");
797                 println("Class<?>[] retClsVal = new Class<?>[" + numMem + "*retLen];");
798                 println("int retPos = 0;");
799                 // Get the struct declaration for this struct and generate initialization code
800                 StructDecl structDecl = getStructDecl(simpleType);
801                 List<String> memTypes = structDecl.getMemberTypes(simpleType);
802                 List<String> members = structDecl.getMembers(simpleType);
803                 if (isArrayOrList(retType, retType)) {  // An array or list
804                         println("for(int i = 0; i < retLen; i++) {");
805                         for (int i = 0; i < members.size(); i++) {
806                                 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
807                                 println("retCls[retPos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
808                                 println("retClsVal[retPos++] = null;");
809                         }
810                         println("}");
811                 } else {        // Just one struct element
812                         for (int i = 0; i < members.size(); i++) {
813                                 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
814                                 println("retCls[retPos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
815                                 println("retClsVal[retPos++] = null;");
816                         }
817                 }
818                 println("Object[] retObj = rmiCall.getStructObjects(retCls, retClsVal);");
819                 if (isArray(retType)) {                 // An array
820                         println(simpleType + "[] structRet = new " + simpleType + "[retLen];");
821                         println("for(int i = 0; i < retLen; i++) {");
822                         println("structRet[i] = new " + simpleType + "();");
823                         println("}");
824                 } else if (isList(retType)) {   // A list
825                         println("List<" + simpleType + "> structRet = new ArrayList<" + simpleType + ">();");
826                 } else
827                         println(simpleType + " structRet = new " + simpleType + "();");
828                 println("int retObjPos = 0;");
829                 writeStructRetMembersJavaStub(simpleType, retType);
830         }
831
832
833         /**
834          * HELPER: writeStdMethodBodyJavaStub() writes the standard method body in the stub class
835          */
836         private void writeStdMethodBodyJavaStub(InterfaceDecl intDecl, List<String> methParams,
837                         List<String> methPrmTypes, String method) {
838
839                 checkAndWriteStructSetupJavaStub(methParams, methPrmTypes, intDecl, method);
840                 println("int methodId = " + intDecl.getMethodNumId(method) + ";");
841                 String retType = intDecl.getMethodType(method);
842                 println("Class<?> retType = " + getSimpleType(getStructType(getEnumType(retType))) + ".class;");
843                 checkAndWriteEnumTypeJavaStub(methParams, methPrmTypes);
844                 // Generate array of parameter types
845                 if (isStructPresent(methParams, methPrmTypes)) {
846                         writeStructParamClassJavaStub(methParams, methPrmTypes);
847                 } else {
848                         print("Class<?>[] paramCls = new Class<?>[] { ");
849                         for (int i = 0; i < methParams.size(); i++) {
850                                 String paramType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
851                                 print(getSimpleType(getEnumType(paramType)) + ".class");
852                                 // Check if this is the last element (don't print a comma)
853                                 if (i != methParams.size() - 1) {
854                                         print(", ");
855                                 }
856                         }
857                         println(" };");
858                         // Generate array of parameter objects
859                         print("Object[] paramObj = new Object[] { ");
860                         for (int i = 0; i < methParams.size(); i++) {
861                                 print(getEnumParam(methPrmTypes.get(i), getSimpleIdentifier(methParams.get(i)), i));
862                                 // Check if this is the last element (don't print a comma)
863                                 if (i != methParams.size() - 1) {
864                                         print(", ");
865                                 }
866                         }
867                         println(" };");
868                 }
869                 // Check if this is "void"
870                 if (retType.equals("void")) {
871                         println("rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
872                 } else { // We do have a return value
873                         // Generate array of parameter types
874                         if (isStructClass(getGenericType(getSimpleArrayType(retType)))) {
875                                 writeStructReturnJavaStub(getGenericType(getSimpleArrayType(retType)), retType);
876                         } else {
877                         // Check if the return value NONPRIMITIVES
878                                 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES) {
879                                         String[] retGenValType = getTypeOfGeneric(retType);
880                                         println("Class<?> retGenValType = " + retGenValType[0] + ".class;");
881                                         println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, retGenValType, paramCls, paramObj);");
882                                         println("return (" + retType + ")retObj;");
883                                 } else if (getParamCategory(retType) == ParamCategory.ENUM) {
884                                 // This is an enum type
885                                         println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
886                                         checkAndWriteEnumRetTypeJavaStub(retType);
887                                 } else {
888                                         println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
889                                         println("return (" + retType + ")retObj;");
890                                 }
891                         }
892                 }
893         }
894
895
896         /**
897          * HELPER: returnGenericCallbackType() returns the callback type
898          */
899         private String returnGenericCallbackType(String paramType) {
900
901                 if (getParamCategory(paramType) == ParamCategory.NONPRIMITIVES)
902                         return getTypeOfGeneric(paramType)[0];
903                 else
904                         return paramType;
905         }
906
907
908         /**
909          * HELPER: checkCallbackType() checks the callback type
910          */
911         private boolean checkCallbackType(String paramType, String callbackType) {
912
913                 String prmType = returnGenericCallbackType(paramType);
914                 return callbackType.equals(prmType);
915         }
916
917
918         /**
919          * HELPER: writeCallbackMethodBodyJavaStub() writes the callback method of the stub class
920          */
921         private void writeCallbackMethodBodyJavaStub(InterfaceDecl intDecl, List<String> methParams,
922                         List<String> methPrmTypes, String method, String callbackType) {
923
924                 println("try {");
925                 // Check if this is single object, array, or list of objects
926                 for (int i = 0; i < methParams.size(); i++) {
927                         String paramType = methPrmTypes.get(i);
928                         if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
929                                 String param = methParams.get(i);
930                                 if (isArrayOrList(paramType, param)) {  // Generate loop
931                                         println("for (" + paramType + " cb : " + getSimpleIdentifier(param) + ") {");
932                                         println(callbackType + "_CallbackSkeleton skel = new " + callbackType + "_CallbackSkeleton(cb, objIdCnt++);");
933                                 } else
934                                         println(callbackType + "_CallbackSkeleton skel = new " + callbackType + "_CallbackSkeleton(" +
935                                                 getSimpleIdentifier(param) + ", objIdCnt++);");
936                                 println("listCallbackObj.add(skel);");
937                                 if (isArrayOrList(paramType, param))
938                                         println("}");
939                         }
940                 }
941                 print("}");
942                 println(" catch (Exception ex) {");
943                 println("ex.printStackTrace();");
944                 println("throw new Error(\"Exception when generating skeleton objects!\");");
945                 println("}\n");
946                 println("int methodId = " + intDecl.getMethodNumId(method) + ";");
947                 String retType = intDecl.getMethodType(method);
948                 println("Class<?> retType = " + getSimpleType(getEnumType(retType)) + ".class;");
949                 // Generate array of parameter types
950                 print("Class<?>[] paramCls = new Class<?>[] { ");
951                 for (int i = 0; i < methParams.size(); i++) {
952                         String paramType = methPrmTypes.get(i);
953                         if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
954                                 print("int.class");
955                         } else { // Generate normal classes if it's not a callback object
956                                 String prmType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
957                                 print(getSimpleType(prmType) + ".class");
958                         }
959                         if (i != methParams.size() - 1) // Check if this is the last element
960                                 print(", ");
961                 }
962                 println(" };");
963                 // Generate array of parameter objects
964                 print("Object[] paramObj = new Object[] { ");
965                 for (int i = 0; i < methParams.size(); i++) {
966                         String paramType = methPrmTypes.get(i);
967                         if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
968                                 //if (isArray(methPrmTypes.get(i), methParams.get(i)))
969                                 if (isArray(methParams.get(i)))
970                                         print(getSimpleIdentifier(methParams.get(i)) + ".length");
971                                 else if (isList(methPrmTypes.get(i)))
972                                         print(getSimpleIdentifier(methParams.get(i)) + ".size()");
973                                 else
974                                         print("new Integer(1)");
975                         } else
976                                 print(getSimpleIdentifier(methParams.get(i)));
977                         if (i != methParams.size() - 1)
978                                 print(", ");
979                 }
980                 println(" };");
981                 // Check if this is "void"
982                 if (retType.equals("void")) {
983                         println("rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
984                 } else { // We do have a return value
985                 // Check if the return value NONPRIMITIVES
986                         if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES) {
987                                 String[] retGenValType = getTypeOfGeneric(retType);
988                                 println("Class<?> retGenValType = " + retGenValType[0] + ".class;");
989                                 println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, retGenValType, paramCls, paramObj);");
990                                 println("return (" + retType + ")retObj;");
991                         } else {
992                                 println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
993                                 println("return (" + retType + ")retObj;");
994                         }
995                 }
996         }
997
998
999         /**
1000          * HELPER: writeMethodJavaStub() writes the methods of the stub class
1001          */
1002         private void writeMethodJavaStub(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
1003
1004                 for (String method : methods) {
1005
1006                         List<String> methParams = intDecl.getMethodParams(method);
1007                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1008                         print("public " + intDecl.getMethodType(method) + " " +
1009                                 intDecl.getMethodId(method) + "(");
1010                         boolean isCallbackMethod = false;
1011                         String callbackType = null;
1012                         for (int i = 0; i < methParams.size(); i++) {
1013
1014                                 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
1015                                 // Check if this has callback object
1016                                 if (callbackClasses.contains(paramType)) {
1017                                         isCallbackMethod = true;
1018                                         callbackType = paramType;       
1019                                         // Even if there're 2 callback arguments, we expect them to be of the same interface
1020                                 }
1021                                 print(methPrmTypes.get(i) + " " + methParams.get(i));
1022                                 // Check if this is the last element (don't print a comma)
1023                                 if (i != methParams.size() - 1) {
1024                                         print(", ");
1025                                 }
1026                         }
1027                         println(") {");
1028                         // Now, write the body of stub!
1029                         if (isCallbackMethod)
1030                                 writeCallbackMethodBodyJavaStub(intDecl, methParams, methPrmTypes, method, callbackType);
1031                         else
1032                                 writeStdMethodBodyJavaStub(intDecl, methParams, methPrmTypes, method);
1033                         println("}\n");
1034                         // Write the init callback helper method
1035                         if (isCallbackMethod)
1036                                 writeInitCallbackJavaStub(callbackType, intDecl);
1037                 }
1038         }
1039
1040
1041         /**
1042          * generateJavaStubClasses() generate stubs based on the methods list in Java
1043          */
1044         public void generateJavaStubClasses() throws IOException {
1045
1046                 // Create a new directory
1047                 String path = createDirectories(dir, subdir);
1048                 for (String intface : mapIntfacePTH.keySet()) {
1049
1050                         Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
1051                         for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
1052
1053                                 // Open a new file to write into
1054                                 String newIntface = intMeth.getKey();
1055                                 String newStubClass = newIntface + "_Stub";
1056                                 FileWriter fw = new FileWriter(path + "/" + newStubClass + ".java");
1057                                 pw = new PrintWriter(new BufferedWriter(fw));
1058                                 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
1059                                 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
1060                                 // Pass in set of methods and get import classes
1061                                 Set<String> methods = intMeth.getValue();
1062                                 Set<String> importClasses = getImportClasses(methods, intDecl);
1063                                 List<String> stdImportClasses = getStandardJavaImportClasses();
1064                                 List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
1065                                 printImportStatements(allImportClasses); println("");
1066                                 // Find out if there are callback objects
1067                                 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
1068                                 boolean callbackExist = !callbackClasses.isEmpty();
1069                                 // Write class header
1070                                 println("public class " + newStubClass + " implements " + newIntface + " {\n");
1071                                 // Write properties
1072                                 writePropertiesJavaStub(intface, newIntface, callbackExist, callbackClasses);
1073                                 // Write constructor
1074                                 writeConstructorJavaStub(intface, newStubClass, callbackExist, callbackClasses);
1075                                 // Write methods
1076                                 writeMethodJavaStub(intMeth.getValue(), intDecl, callbackClasses);
1077                                 println("}");
1078                                 pw.close();
1079                                 System.out.println("IoTCompiler: Generated stub class " + newStubClass + ".java...");
1080                         }
1081                 }
1082         }
1083
1084
1085         /**
1086          * HELPER: writePropertiesJavaCallbackStub() writes the properties of the callback stub class
1087          */
1088         private void writePropertiesJavaCallbackStub(String intface, String newIntface, boolean callbackExist, Set<String> callbackClasses) {
1089
1090                 println("private IoTRMICall rmiCall;");
1091                 println("private String address;");
1092                 println("private int[] ports;\n");
1093                 // Get the object Id
1094                 println("private static int objectId = 0;");
1095                 if (callbackExist) {
1096                 // We assume that each class only has one callback interface for now
1097                         Iterator it = callbackClasses.iterator();
1098                         String callbackType = (String) it.next();
1099                         println("// Callback properties");
1100                         println("private IoTRMIObject rmiObj;");
1101                         println("List<" + callbackType + "> listCallbackObj;");
1102                         println("private static int objIdCnt = 0;");
1103                         // Generate permission stuff for callback stubs
1104                         DeclarationHandler decHandler = mapIntDeclHand.get(callbackType);
1105                         InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(callbackType);
1106                         writePropertiesJavaPermission(callbackType, intDecl);
1107                 }
1108                 println("\n");
1109         }
1110
1111
1112         /**
1113          * HELPER: writeConstructorJavaCallbackStub() writes the constructor of the callback stub class
1114          */
1115         private void writeConstructorJavaCallbackStub(String intface, String newStubClass, boolean callbackExist, Set<String> callbackClasses) {
1116
1117                 // TODO: If we want callback in callback, then we need to add address and port initializations
1118                 println("public " + newStubClass + "(IoTRMICall _rmiCall, int _objectId) throws Exception {");
1119                 println("objectId = _objectId;");
1120                 println("rmiCall = _rmiCall;");
1121                 if (callbackExist) {
1122                         Iterator it = callbackClasses.iterator();
1123                         String callbackType = (String) it.next();
1124                         writeConstructorJavaPermission(intface);
1125                         println("listCallbackObj = new ArrayList<" + callbackType + ">();");
1126                         println("___initCallBack();");
1127                         println("// TODO: Add address and port initialization here if we want callback in callback!");
1128                 }
1129                 println("}\n");
1130         }
1131
1132
1133         /**
1134          * generateJavaCallbackStubClasses() generate callback stubs based on the methods list in Java
1135          * <p>
1136          * Callback stubs gets the IoTRMICall objects from outside of the class as contructor input
1137          * because all these stubs are populated by the class that takes in this object as a callback
1138          * object. In such a class, we only use one socket, hence one IoTRMICall, for all callback objects.
1139          */
1140         public void generateJavaCallbackStubClasses() throws IOException {
1141
1142                 // Create a new directory
1143                 String path = createDirectories(dir, subdir);
1144                 for (String intface : mapIntfacePTH.keySet()) {
1145
1146                         Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
1147                         for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
1148
1149                                 // Open a new file to write into
1150                                 String newIntface = intMeth.getKey();
1151                                 String newStubClass = newIntface + "_CallbackStub";
1152                                 FileWriter fw = new FileWriter(path + "/" + newStubClass + ".java");
1153                                 pw = new PrintWriter(new BufferedWriter(fw));
1154                                 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
1155                                 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
1156                                 // Pass in set of methods and get import classes
1157                                 Set<String> methods = intMeth.getValue();
1158                                 Set<String> importClasses = getImportClasses(methods, intDecl);
1159                                 List<String> stdImportClasses = getStandardJavaImportClasses();
1160                                 List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
1161                                 printImportStatements(allImportClasses); println("");
1162                                 // Find out if there are callback objects
1163                                 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
1164                                 boolean callbackExist = !callbackClasses.isEmpty();
1165                                 // Write class header
1166                                 println("public class " + newStubClass + " implements " + newIntface + " {\n");
1167                                 // Write properties
1168                                 writePropertiesJavaCallbackStub(intface, newIntface, callbackExist, callbackClasses);
1169                                 // Write constructor
1170                                 writeConstructorJavaCallbackStub(intface, newStubClass, callbackExist, callbackClasses);
1171                                 // Write methods
1172                                 // TODO: perhaps need to generate callback for callback
1173                                 writeMethodJavaStub(intMeth.getValue(), intDecl, callbackClasses);
1174                                 println("}");
1175                                 pw.close();
1176                                 System.out.println("IoTCompiler: Generated callback stub class " + newStubClass + ".java...");
1177                         }
1178                 }
1179         }
1180
1181
1182         /**
1183          * HELPER: writePropertiesJavaSkeleton() writes the properties of the skeleton class
1184          */
1185         private void writePropertiesJavaSkeleton(String intface, boolean callbackExist, InterfaceDecl intDecl) {
1186
1187                 println("private " + intface + " mainObj;");
1188                 //println("private int ports;");
1189                 println("private IoTRMIObject rmiObj;\n");
1190                 // Callback
1191                 if (callbackExist) {
1192                         println("private static int objIdCnt = 0;");
1193                         println("private IoTRMICall rmiCall;");
1194                 }
1195                 writePropertiesJavaPermission(intface, intDecl);
1196                 println("\n");
1197         }
1198
1199
1200         /**
1201          * HELPER: writeConstructorJavaSkeleton() writes the constructor of the skeleton class
1202          */
1203         private void writeConstructorJavaSkeleton(String newSkelClass, String intface) {
1204
1205                 println("public " + newSkelClass + "(" + intface + " _mainObj, int _port) throws Exception {");
1206                 println("mainObj = _mainObj;");
1207                 println("rmiObj = new IoTRMIObject(_port);");
1208                 // Generate permission control initialization
1209                 writeConstructorJavaPermission(intface);
1210                 println("___waitRequestInvokeMethod();");
1211                 println("}\n");
1212         }
1213
1214
1215         /**
1216          * HELPER: writeStdMethodBodyJavaSkeleton() writes the standard method body in the skeleton class
1217          */
1218         private void writeStdMethodBodyJavaSkeleton(List<String> methParams, String methodId, String methodType) {
1219
1220                 if (methodType.equals("void"))
1221                         print("mainObj." + methodId + "(");
1222                 else
1223                         print("return mainObj." + methodId + "(");
1224                 for (int i = 0; i < methParams.size(); i++) {
1225
1226                         print(getSimpleIdentifier(methParams.get(i)));
1227                         // Check if this is the last element (don't print a comma)
1228                         if (i != methParams.size() - 1) {
1229                                 print(", ");
1230                         }
1231                 }
1232                 println(");");
1233         }
1234
1235
1236         /**
1237          * HELPER: writeInitCallbackJavaSkeleton() writes the init callback method for skeleton class
1238          */
1239         private void writeInitCallbackJavaSkeleton(boolean callbackSkeleton) {
1240
1241                 // This is a callback skeleton generation
1242                 if (callbackSkeleton)
1243                         println("public void ___regCB(IoTRMIObject rmiObj) throws IOException {");
1244                 else
1245                         println("public void ___regCB() throws IOException {");
1246                 println("Object[] paramObj = rmiObj.getMethodParams(new Class<?>[] { int.class, String.class, int.class },");
1247                 println("\tnew Class<?>[] { null, null, null });");
1248                 println("rmiCall = new IoTRMICall((int) paramObj[0], (String) paramObj[1], (int) paramObj[2]);");
1249                 println("}\n");
1250         }
1251
1252
1253         /**
1254          * HELPER: writeMethodJavaSkeleton() writes the method of the skeleton class
1255          */
1256         private void writeMethodJavaSkeleton(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses, 
1257                         boolean callbackSkeleton) {
1258
1259                 for (String method : methods) {
1260
1261                         List<String> methParams = intDecl.getMethodParams(method);
1262                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1263                         String methodId = intDecl.getMethodId(method);
1264                         print("public " + intDecl.getMethodType(method) + " " + methodId + "(");
1265                         boolean isCallbackMethod = false;
1266                         String callbackType = null;
1267                         for (int i = 0; i < methParams.size(); i++) {
1268
1269                                 String origParamType = methPrmTypes.get(i);
1270                                 String paramType = checkAndGetParamClass(origParamType);
1271                                 if (callbackClasses.contains(origParamType)) { // Check if this has callback object
1272                                         isCallbackMethod = true;
1273                                         callbackType = origParamType;   
1274                                 }
1275                                 print(paramType + " " + methParams.get(i));
1276                                 // Check if this is the last element (don't print a comma)
1277                                 if (i != methParams.size() - 1) {
1278                                         print(", ");
1279                                 }
1280                         }
1281                         println(") {");
1282                         // Now, write the body of skeleton!
1283                         writeStdMethodBodyJavaSkeleton(methParams, methodId, intDecl.getMethodType(method));
1284                         println("}\n");
1285                         if (isCallbackMethod)
1286                                 writeInitCallbackJavaSkeleton(callbackSkeleton);
1287                 }
1288         }
1289
1290
1291         /**
1292          * HELPER: writeCallbackJavaStubGeneration() writes the callback stub generation part
1293          */
1294         private Map<Integer,String> writeCallbackJavaStubGeneration(List<String> methParams, List<String> methPrmTypes, 
1295                         String callbackType) {
1296
1297                 Map<Integer,String> mapStubParam = new HashMap<Integer,String>();
1298                 // Iterate over callback objects
1299                 for (int i = 0; i < methParams.size(); i++) {
1300                         String paramType = methPrmTypes.get(i);
1301                         String param = methParams.get(i);
1302                         //if (callbackType.equals(paramType)) {
1303                         if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
1304                                 println("try {");
1305                                 String exchParamType = checkAndGetParamClass(paramType);
1306                                 // Print array if this is array or list if this is a list of callback objects
1307                                 if (isArray(param)) {
1308                                         println("int numStubs" + i + " = (int) paramObj[" + i + "];");
1309                                         println(exchParamType + "[] stub" + i + " = new " + exchParamType + "[numStubs" + i + "];");
1310                                 } else if (isList(paramType)) {
1311                                         println("int numStubs" + i + " = (int) paramObj[" + i + "];");
1312                                         println("List<" + exchParamType + "> stub" + i + " = new ArrayList<" + exchParamType + ">();");
1313                                 } else {
1314                                         println(exchParamType + " stub" + i + " = new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt);");
1315                                         println("objIdCnt++;");
1316                                 }
1317                         }
1318                         // Generate a loop if needed
1319                         if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
1320                                 String exchParamType = checkAndGetParamClass(paramType);
1321                                 if (isArray(param)) {
1322                                         println("for (int objId = 0; objId < numStubs" + i + "; objId++) {");
1323                                         println("stub" + i + "[objId] = new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt);");
1324                                         println("objIdCnt++;");
1325                                         println("}");
1326                                 } else if (isList(paramType)) {
1327                                         println("for (int objId = 0; objId < numStubs" + i + "; objId++) {");
1328                                         println("stub" + i + ".add(new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt));");
1329                                         println("objIdCnt++;");
1330                                         println("}");
1331                                 }
1332                                 mapStubParam.put(i, "stub" + i);        // List of all stub parameters
1333                         }
1334                 }
1335                 return mapStubParam;
1336         }
1337
1338
1339         /**
1340          * HELPER: checkAndWriteEnumTypeJavaSkeleton() writes the enum type (convert from enum to int)
1341          */
1342         private void checkAndWriteEnumTypeJavaSkeleton(List<String> methParams, List<String> methPrmTypes) {
1343
1344                 // Iterate and find enum declarations
1345                 for (int i = 0; i < methParams.size(); i++) {
1346                         String paramType = methPrmTypes.get(i);
1347                         String param = methParams.get(i);
1348                         String simpleType = getSimpleType(paramType);
1349                         if (isEnumClass(simpleType)) {
1350                         // Check if this is enum type
1351                                 println("int paramInt" + i + "[] = (int[]) paramObj[" + i + "];");
1352                                 println(simpleType + "[] enumVals = " + simpleType + ".values();");
1353                                 if (isArray(param)) {   // An array
1354                                         println("int len" + i + " = paramInt" + i + ".length;");
1355                                         println(simpleType + "[] paramEnum = new " + simpleType + "[len];");
1356                                         println("for (int i = 0; i < len" + i + "; i++) {");
1357                                         println("paramEnum[i] = enumVals[paramInt" + i + "[i]];");
1358                                         println("}");
1359                                 } else if (isList(paramType)) { // A list
1360                                         println("int len" + i + " = paramInt" + i + ".length;");
1361                                         println("List<" + simpleType + "> paramEnum = new ArrayList<" + simpleType + ">();");
1362                                         println("for (int i = 0; i < len" + i + "; i++) {");
1363                                         println("paramEnum.add(enumVals[paramInt" + i + "[i]]);");
1364                                         println("}");
1365                                 } else {        // Just one element
1366                                         println(simpleType + " paramEnum" + i + " = enumVals[paramInt" + i + "[0]];");
1367                                 }
1368                         }
1369                 }
1370         }
1371
1372
1373         /**
1374          * HELPER: checkAndWriteEnumRetTypeJavaSkeleton() writes the enum return type (convert from enum to int)
1375          */
1376         private void checkAndWriteEnumRetTypeJavaSkeleton(String retType, String methodId) {
1377
1378                 // Strips off array "[]" for return type
1379                 String pureType = getSimpleArrayType(getSimpleType(retType));
1380                 // Take the inner type of generic
1381                 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
1382                         pureType = getTypeOfGeneric(retType)[0];
1383                 if (isEnumClass(pureType)) {
1384                 // Check if this is enum type
1385                         // Enum decoder
1386                         if (isArray(retType)) {                 // An array
1387                                 print(pureType + "[] retEnum = " + methodId + "(");
1388                         } else if (isList(retType)) {   // A list
1389                                 print("List<" + pureType + "> retEnum = " + methodId + "(");
1390                         } else {        // Just one element
1391                                 print(pureType + " retEnum = " + methodId + "(");
1392                         }
1393                 }
1394         }
1395
1396
1397         /**
1398          * HELPER: checkAndWriteEnumRetConvJavaSkeleton() writes the enum return type (convert from enum to int)
1399          */
1400         private void checkAndWriteEnumRetConvJavaSkeleton(String retType) {
1401
1402                 // Strips off array "[]" for return type
1403                 String pureType = getSimpleArrayType(getSimpleType(retType));
1404                 // Take the inner type of generic
1405                 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
1406                         pureType = getTypeOfGeneric(retType)[0];
1407                 if (isEnumClass(pureType)) {
1408                 // Check if this is enum type
1409                         if (isArray(retType)) { // An array
1410                                 println("int retLen = retEnum.length;");
1411                                 println("int[] retEnumVal = new int[retLen];");
1412                                 println("for (int i = 0; i < retLen; i++) {");
1413                                 println("retEnumVal[i] = retEnum[i].ordinal();");
1414                                 println("}");
1415                         } else if (isList(retType)) {   // A list
1416                                 println("int retLen = retEnum.size();");
1417                                 println("List<" + pureType + "> retEnumVal = new ArrayList<" + pureType + ">();");
1418                                 println("for (int i = 0; i < retLen; i++) {");
1419                                 println("retEnumVal.add(retEnum[i].ordinal());");
1420                                 println("}");
1421                         } else {        // Just one element
1422                                 println("int[] retEnumVal = new int[1];");
1423                                 println("retEnumVal[0] = retEnum.ordinal();");
1424                         }
1425                         println("Object retObj = retEnumVal;");
1426                 }
1427         }
1428         
1429         
1430         /**
1431          * HELPER: writeLengthStructParamClassSkeleton() writes lengths of params
1432          */
1433         private void writeLengthStructParamClassSkeleton(List<String> methParams, List<String> methPrmTypes, 
1434                         String method, InterfaceDecl intDecl) {
1435
1436                 // Iterate and find struct declarations - count number of params
1437                 for (int i = 0; i < methParams.size(); i++) {
1438                         String paramType = methPrmTypes.get(i);
1439                         String param = methParams.get(i);
1440                         String simpleType = getGenericType(paramType);
1441                         if (isStructClass(simpleType)) {
1442                                 int members = getNumOfMembers(simpleType);
1443                                 print(Integer.toString(members) + "*");
1444                                 int methodNumId = intDecl.getMethodNumId(method);
1445                                 print("struct" + methodNumId + "Size" + i);
1446                         } else
1447                                 print("1");
1448                         if (i != methParams.size() - 1) {
1449                                 print("+");
1450                         }
1451                 }
1452         }
1453
1454         
1455         /**
1456          * HELPER: writeStructMembersJavaSkeleton() writes member parameters of struct
1457          */
1458         private void writeStructMembersJavaSkeleton(String simpleType, String paramType, 
1459                         String param, String method, InterfaceDecl intDecl, int iVar) {
1460
1461                 // Get the struct declaration for this struct and generate initialization code
1462                 StructDecl structDecl = getStructDecl(simpleType);
1463                 List<String> memTypes = structDecl.getMemberTypes(simpleType);
1464                 List<String> members = structDecl.getMembers(simpleType);
1465                 if (isArrayOrList(param, paramType)) {  // An array or list
1466                         int methodNumId = intDecl.getMethodNumId(method);
1467                         String counter = "struct" + methodNumId + "Size" + iVar;
1468                         println("for(int i = 0; i < " + counter + "; i++) {");
1469                 }
1470                 println("int pos = 0;");
1471                 if (isArrayOrList(param, paramType)) {  // An array or list
1472                         println("for(int i = 0; i < retLen; i++) {");
1473                         for (int i = 0; i < members.size(); i++) {
1474                                 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
1475                                 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
1476                                 println("paramClsGen[pos++] = null;");
1477                         }
1478                         println("}");
1479                 } else {        // Just one struct element
1480                         for (int i = 0; i < members.size(); i++) {
1481                                 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
1482                                 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
1483                                 println("paramClsGen[pos++] = null;");
1484                         }
1485                 }
1486         }
1487
1488
1489         /**
1490          * HELPER: writeStructMembersInitJavaSkeleton() writes member parameters initialization of struct
1491          */
1492         private void writeStructMembersInitJavaSkeleton(InterfaceDecl intDecl, List<String> methParams,
1493                         List<String> methPrmTypes, String method) {
1494
1495                 for (int i = 0; i < methParams.size(); i++) {
1496                         String paramType = methPrmTypes.get(i);
1497                         String param = methParams.get(i);
1498                         String simpleType = getGenericType(paramType);
1499                         if (isStructClass(simpleType)) {
1500                                 int methodNumId = intDecl.getMethodNumId(method);
1501                                 String counter = "struct" + methodNumId + "Size" + i;
1502                                 // Declaration
1503                                 if (isArray(param)) {                   // An array
1504                                         println(simpleType + "[] paramStruct" + i + " = new " + simpleType + "[" + counter + "];");
1505                                         println("for(int i = 0; i < " + counter + "; i++) {");
1506                                         println("paramStruct" + i + "[i] = new " + simpleType + "();");
1507                                         println("}");
1508                                 } else if (isList(paramType)) { // A list
1509                                         println("List<" + simpleType + "> paramStruct" + i + " = new ArrayList<" + simpleType + ">();");
1510                                 } else
1511                                         println(simpleType + " paramStruct" + i + " = new " + simpleType + "();");
1512                                 println("int objPos = 0;");
1513                                 // Initialize members
1514                                 StructDecl structDecl = getStructDecl(simpleType);
1515                                 List<String> members = structDecl.getMembers(simpleType);
1516                                 List<String> memTypes = structDecl.getMemberTypes(simpleType);
1517                                 if (isArrayOrList(param, paramType)) {  // An array or list
1518                                         println("for(int i = 0; i < " + counter + "; i++) {");
1519                                 }
1520                                 if (isArray(param)) {   // An array
1521                                         for (int j = 0; j < members.size(); j++) {
1522                                                 String prmType = checkAndGetArray(memTypes.get(j), members.get(j));
1523                                                 print("paramStruct" + i + "[i]." + getSimpleIdentifier(members.get(j)));
1524                                                 println(" = (" + getSimpleType(getEnumType(prmType)) + ") paramObj[objPos++];");
1525                                         }
1526                                         println("}");
1527                                 } else if (isList(paramType)) { // A list
1528                                         println(simpleType + " paramStructMem = new " + simpleType + "();");
1529                                         for (int j = 0; j < members.size(); j++) {
1530                                                 String prmType = checkAndGetArray(memTypes.get(j), members.get(j));
1531                                                 print("paramStructMem." + getSimpleIdentifier(members.get(j)));
1532                                                 println(" = (" + getSimpleType(getEnumType(prmType)) + ") paramObj[objPos++];");
1533                                         }
1534                                         println("paramStruct" + i + ".add(paramStructMem);");
1535                                         println("}");
1536                                 } else {        // Just one struct element
1537                                         for (int j = 0; j < members.size(); j++) {
1538                                                 String prmType = checkAndGetArray(memTypes.get(j), members.get(j));
1539                                                 print("paramStruct" + i + "." + getSimpleIdentifier(members.get(j)));
1540                                                 println(" = (" + getSimpleType(getEnumType(prmType)) + ") paramObj[objPos++];");
1541                                         }
1542                                 }
1543                         } else {
1544                                 // Take offsets of parameters
1545                                 println("int offset" + i +" = objPos;");
1546                         }
1547                 }
1548         }
1549
1550
1551         /**
1552          * HELPER: writeStructReturnJavaSkeleton() writes struct for return statement
1553          */
1554         private void writeStructReturnJavaSkeleton(String simpleType, String retType) {
1555
1556                 // Minimum retLen is 1 if this is a single struct object
1557                 if (isArray(retType))
1558                         println("int retLen = retStruct.length;");
1559                 else if (isList(retType))
1560                         println("int retLen = retStruct.size();");
1561                 else    // Just single struct object
1562                         println("int retLen = 1;");
1563                 println("Object retLenObj = retLen;");
1564                 println("rmiObj.sendReturnObj(retLenObj);");
1565                 int numMem = getNumOfMembers(simpleType);
1566                 println("Class<?>[] retCls = new Class<?>[" + numMem + "*retLen];");
1567                 println("Object[] retObj = new Object[" + numMem + "*retLen];");
1568                 println("int retPos = 0;");
1569                 // Get the struct declaration for this struct and generate initialization code
1570                 StructDecl structDecl = getStructDecl(simpleType);
1571                 List<String> memTypes = structDecl.getMemberTypes(simpleType);
1572                 List<String> members = structDecl.getMembers(simpleType);
1573                 if (isArrayOrList(retType, retType)) {  // An array or list
1574                         println("for(int i = 0; i < retLen; i++) {");
1575                         for (int i = 0; i < members.size(); i++) {
1576                                 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
1577                                 println("retCls[retPos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
1578                                 print("retObj[retPos++] = retStruct[i].");
1579                                 print(getEnumParam(memTypes.get(i), getSimpleIdentifier(members.get(i)), i));
1580                                 println(";");
1581                         }
1582                         println("}");
1583                 } else {        // Just one struct element
1584                         for (int i = 0; i < members.size(); i++) {
1585                                 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
1586                                 println("retCls[retPos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
1587                                 print("retObj[retPos++] = retStruct.");
1588                                 print(getEnumParam(memTypes.get(i), getSimpleIdentifier(members.get(i)), i));
1589                                 println(";");
1590                         }
1591                 }
1592
1593         }
1594
1595
1596         /**
1597          * HELPER: writeMethodHelperReturnJavaSkeleton() writes return statement part in skeleton
1598          */
1599         private void writeMethodHelperReturnJavaSkeleton(InterfaceDecl intDecl, List<String> methParams,
1600                         List<String> methPrmTypes, String method, boolean isCallbackMethod, String callbackType,
1601                         boolean isStructMethod) {
1602
1603                 checkAndWriteEnumTypeJavaSkeleton(methParams, methPrmTypes);
1604                 Map<Integer,String> mapStubParam = null;
1605                 if (isCallbackMethod)
1606                         mapStubParam = writeCallbackJavaStubGeneration(methParams, methPrmTypes, callbackType);
1607                 // Check if this is "void"
1608                 String retType = intDecl.getMethodType(method);
1609                 if (retType.equals("void")) {
1610                         print(intDecl.getMethodId(method) + "(");
1611                 } else if (isEnumClass(getSimpleArrayType(getSimpleType(retType)))) {   // Enum type
1612                         checkAndWriteEnumRetTypeJavaSkeleton(retType, intDecl.getMethodId(method));
1613                 } else if (isStructClass(getSimpleArrayType(getSimpleType(retType)))) { // Struct type
1614                         print(retType + " retStruct = " + intDecl.getMethodId(method) + "(");
1615                 } else { // We do have a return value
1616                         print("Object retObj = " + intDecl.getMethodId(method) + "(");
1617                 }
1618                 for (int i = 0; i < methParams.size(); i++) {
1619
1620                         if (isCallbackMethod) {
1621                                 print(mapStubParam.get(i));     // Get the callback parameter
1622                         } else if (isEnumClass(getSimpleType(methPrmTypes.get(i)))) { // Enum class
1623                                 print(getEnumParam(methPrmTypes.get(i), methParams.get(i), i));
1624                         } else if (isStructClass(getSimpleType(methPrmTypes.get(i)))) {
1625                                 print("paramStruct" + i);
1626                         } else {
1627                                 String prmType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
1628                                 if (isStructMethod)
1629                                         print("(" + prmType + ") paramObj[offset" + i + "]");
1630                                 else
1631                                         print("(" + prmType + ") paramObj[" + i + "]");
1632                         }
1633                         if (i != methParams.size() - 1)
1634                                 print(", ");
1635                 }
1636                 println(");");
1637                 if (!retType.equals("void")) {
1638                         if (isEnumClass(getSimpleArrayType(getSimpleType(retType)))) { // Enum type
1639                                 checkAndWriteEnumRetConvJavaSkeleton(retType);
1640                                 println("rmiObj.sendReturnObj(retObj);");
1641                         } else if (isStructClass(getSimpleArrayType(getSimpleType(retType)))) { // Struct type
1642                                 writeStructReturnJavaSkeleton(getSimpleArrayType(getSimpleType(retType)), retType);
1643                                 println("rmiObj.sendReturnObj(retCls, retObj);");
1644                         } else
1645                                 println("rmiObj.sendReturnObj(retObj);");
1646                 }
1647                 if (isCallbackMethod) { // Catch exception if this is callback
1648                         print("}");
1649                         println(" catch(Exception ex) {");
1650                         println("ex.printStackTrace();");
1651                         println("throw new Error(\"Exception from callback object instantiation!\");");
1652                         println("}");
1653                 }
1654         }
1655
1656
1657         /**
1658          * HELPER: writeMethodHelperStructJavaSkeleton() writes the struct in skeleton
1659          */
1660         private void writeMethodHelperStructJavaSkeleton(InterfaceDecl intDecl, List<String> methParams,
1661                         List<String> methPrmTypes, String method, Set<String> callbackClasses) {
1662
1663                 // Generate array of parameter objects
1664                 boolean isCallbackMethod = false;
1665                 String callbackType = null;
1666                 print("int paramLen = ");
1667                 writeLengthStructParamClassSkeleton(methParams, methPrmTypes, method, intDecl);
1668                 println(";");
1669                 println("Class<?>[] paramCls = new Class<?>[paramLen];");
1670                 println("Class<?>[] paramClsGen = new Class<?>[paramLen];");
1671                 // Iterate again over the parameters
1672                 for (int i = 0; i < methParams.size(); i++) {
1673                         String paramType = methPrmTypes.get(i);
1674                         String param = methParams.get(i);
1675                         String simpleType = getGenericType(paramType);
1676                         if (isStructClass(simpleType)) {
1677                                 writeStructMembersJavaSkeleton(simpleType, paramType, param, method, intDecl, i);
1678                         } else {
1679                                 String prmType = returnGenericCallbackType(methPrmTypes.get(i));
1680                                 if (callbackClasses.contains(prmType)) {
1681                                         isCallbackMethod = true;
1682                                         callbackType = prmType;
1683                                         println("paramCls[pos] = int.class;");
1684                                         println("paramClsGen[pos++] = null;");
1685                                 } else {        // Generate normal classes if it's not a callback object
1686                                         String paramTypeOth = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
1687                                         println("paramCls[pos] = " + getSimpleType(getEnumType(paramTypeOth)) + ".class;");
1688                                         print("paramClsGen[pos++] = ");
1689                                         String prmTypeOth = methPrmTypes.get(i);
1690                                         if (getParamCategory(prmTypeOth) == ParamCategory.NONPRIMITIVES)
1691                                                 println(getTypeOfGeneric(prmType)[0] + ".class;");
1692                                         else
1693                                                 println("null;");
1694                                 }
1695                         }
1696                 }
1697                 println("Object[] paramObj = rmiObj.getMethodParams(paramCls, paramClsGen);");
1698                 writeStructMembersInitJavaSkeleton(intDecl, methParams, methPrmTypes, method);
1699                 // Write the return value part
1700                 writeMethodHelperReturnJavaSkeleton(intDecl, methParams, methPrmTypes, method, isCallbackMethod, callbackType, true);
1701         }
1702
1703
1704         /**
1705          * HELPER: writeStdMethodHelperBodyJavaSkeleton() writes the standard method body helper in the skeleton class
1706          */
1707         private void writeStdMethodHelperBodyJavaSkeleton(InterfaceDecl intDecl, List<String> methParams,
1708                         List<String> methPrmTypes, String method, Set<String> callbackClasses) {
1709
1710                 // Generate array of parameter objects
1711                 boolean isCallbackMethod = false;
1712                 String callbackType = null;
1713                 print("Object[] paramObj = rmiObj.getMethodParams(new Class<?>[] { ");
1714                 for (int i = 0; i < methParams.size(); i++) {
1715
1716                         String paramType = returnGenericCallbackType(methPrmTypes.get(i));
1717                         if (callbackClasses.contains(paramType)) {
1718                                 isCallbackMethod = true;
1719                                 callbackType = paramType;
1720                                 print("int.class");
1721                         } else {        // Generate normal classes if it's not a callback object
1722                                 String prmType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
1723                                 print(getSimpleType(getEnumType(prmType)) + ".class");
1724                         }
1725                         if (i != methParams.size() - 1)
1726                                 print(", ");
1727                 }
1728                 println(" }, ");
1729                 // Generate generic class if it's a generic type.. null otherwise
1730                 print("new Class<?>[] { ");
1731                 for (int i = 0; i < methParams.size(); i++) {
1732                         String prmType = methPrmTypes.get(i);
1733                         if (getParamCategory(prmType) == ParamCategory.NONPRIMITIVES)
1734                                 print(getTypeOfGeneric(prmType)[0] + ".class");
1735                         else
1736                                 print("null");
1737                         if (i != methParams.size() - 1)
1738                                 print(", ");
1739                 }
1740                 println(" });");
1741                 // Write the return value part
1742                 writeMethodHelperReturnJavaSkeleton(intDecl, methParams, methPrmTypes, method, isCallbackMethod, callbackType, false);
1743         }
1744
1745
1746         /**
1747          * HELPER: writeMethodHelperJavaSkeleton() writes the method helper of the skeleton class
1748          */
1749         private void writeMethodHelperJavaSkeleton(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
1750
1751                 // Use this set to handle two same methodIds
1752                 Set<String> uniqueMethodIds = new HashSet<String>();
1753                 for (String method : methods) {
1754
1755                         List<String> methParams = intDecl.getMethodParams(method);
1756                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1757                         if (isStructPresent(methParams, methPrmTypes)) {        // Treat struct differently
1758                                 String methodId = intDecl.getMethodId(method);
1759                                 print("public void ___");
1760                                 String helperMethod = methodId;
1761                                 if (uniqueMethodIds.contains(methodId))
1762                                         helperMethod = helperMethod + intDecl.getMethodNumId(method);
1763                                 else
1764                                         uniqueMethodIds.add(methodId);
1765                                 String retType = intDecl.getMethodType(method);
1766                                 print(helperMethod + "(");
1767                                 boolean begin = true;
1768                                 for (int i = 0; i < methParams.size(); i++) { // Print size variables
1769                                         String paramType = methPrmTypes.get(i);
1770                                         String param = methParams.get(i);
1771                                         String simpleType = getSimpleType(paramType);
1772                                         if (isStructClass(simpleType)) {
1773                                                 if (!begin) {   // Generate comma for not the beginning variable
1774                                                         print(", "); begin = false;
1775                                                 }
1776                                                 int methodNumId = intDecl.getMethodNumId(method);
1777                                                 print("int struct" + methodNumId + "Size" + i);
1778                                         }
1779                                 }
1780                                 // Check if this is "void"
1781                                 if (retType.equals("void"))
1782                                         println(") {");
1783                                 else
1784                                         println(") throws IOException {");
1785                                 writeMethodHelperStructJavaSkeleton(intDecl, methParams, methPrmTypes, method, callbackClasses);
1786                                 println("}\n");
1787                         } else {
1788                                 String methodId = intDecl.getMethodId(method);
1789                                 print("public void ___");
1790                                 String helperMethod = methodId;
1791                                 if (uniqueMethodIds.contains(methodId))
1792                                         helperMethod = helperMethod + intDecl.getMethodNumId(method);
1793                                 else
1794                                         uniqueMethodIds.add(methodId);
1795                                 // Check if this is "void"
1796                                 String retType = intDecl.getMethodType(method);
1797                                 if (retType.equals("void"))
1798                                         println(helperMethod + "() {");
1799                                 else
1800                                         println(helperMethod + "() throws IOException {");
1801                                 // Now, write the helper body of skeleton!
1802                                 writeStdMethodHelperBodyJavaSkeleton(intDecl, methParams, methPrmTypes, method, callbackClasses);
1803                                 println("}\n");
1804                         }
1805                 }
1806                 // Write method helper for structs
1807                 writeMethodHelperStructSetupJavaSkeleton(methods, intDecl);
1808         }
1809
1810
1811         /**
1812          * HELPER: writeMethodHelperStructSetupJavaSkeleton() writes the method helper of struct setup in skeleton class
1813          */
1814         private void writeMethodHelperStructSetupJavaSkeleton(Collection<String> methods, 
1815                         InterfaceDecl intDecl) {
1816
1817                 // Use this set to handle two same methodIds
1818                 for (String method : methods) {
1819
1820                         List<String> methParams = intDecl.getMethodParams(method);
1821                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1822                         // Check for params with structs
1823                         for (int i = 0; i < methParams.size(); i++) {
1824                                 String paramType = methPrmTypes.get(i);
1825                                 String param = methParams.get(i);
1826                                 String simpleType = getSimpleType(paramType);
1827                                 if (isStructClass(simpleType)) {
1828                                         int methodNumId = intDecl.getMethodNumId(method);
1829                                         print("public int ___");
1830                                         String helperMethod = methodNumId + "struct" + i;
1831                                         println(helperMethod + "() {");
1832                                         // Now, write the helper body of skeleton!
1833                                         println("Object[] paramObj = rmiObj.getMethodParams(new Class<?>[] { int.class }, new Class<?>[] { null });");
1834                                         println("return (int) paramObj[0];");
1835                                         println("}\n");
1836                                 }
1837                         }
1838                 }
1839         }
1840
1841
1842         /**
1843          * HELPER: writeMethodHelperStructSetupJavaCallbackSkeleton() writes the method helper of struct setup in callback skeleton class
1844          */
1845         private void writeMethodHelperStructSetupJavaCallbackSkeleton(Collection<String> methods, 
1846                         InterfaceDecl intDecl) {
1847
1848                 // Use this set to handle two same methodIds
1849                 for (String method : methods) {
1850
1851                         List<String> methParams = intDecl.getMethodParams(method);
1852                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1853                         // Check for params with structs
1854                         for (int i = 0; i < methParams.size(); i++) {
1855                                 String paramType = methPrmTypes.get(i);
1856                                 String param = methParams.get(i);
1857                                 String simpleType = getSimpleType(paramType);
1858                                 if (isStructClass(simpleType)) {
1859                                         int methodNumId = intDecl.getMethodNumId(method);
1860                                         print("public int ___");
1861                                         String helperMethod = methodNumId + "struct" + i;
1862                                         println(helperMethod + "(IoTRMIObject rmiObj) {");
1863                                         // Now, write the helper body of skeleton!
1864                                         println("Object[] paramObj = rmiObj.getMethodParams(new Class<?>[] { int.class }, new Class<?>[] { null });");
1865                                         println("return (int) paramObj[0];");
1866                                         println("}\n");
1867                                 }
1868                         }
1869                 }
1870         }
1871
1872
1873         /**
1874          * HELPER: writeCountVarStructSkeleton() writes counter variable of struct for skeleton
1875          */
1876         private void writeCountVarStructSkeleton(Collection<String> methods, InterfaceDecl intDecl) {
1877
1878                 // Use this set to handle two same methodIds
1879                 for (String method : methods) {
1880
1881                         List<String> methParams = intDecl.getMethodParams(method);
1882                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1883                         // Check for params with structs
1884                         for (int i = 0; i < methParams.size(); i++) {
1885                                 String paramType = methPrmTypes.get(i);
1886                                 String param = methParams.get(i);
1887                                 String simpleType = getSimpleType(paramType);
1888                                 if (isStructClass(simpleType)) {
1889                                         int methodNumId = intDecl.getMethodNumId(method);
1890                                         println("int struct" + methodNumId + "Size" + i + " = 0;");
1891                                 }
1892                         }
1893                 }
1894         }
1895         
1896         
1897         /**
1898          * HELPER: writeInputCountVarStructSkeleton() writes input counter variable of struct for skeleton
1899          */
1900         private boolean writeInputCountVarStructSkeleton(String method, InterfaceDecl intDecl) {
1901
1902                 List<String> methParams = intDecl.getMethodParams(method);
1903                 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1904                 boolean structExist = false;
1905                 // Check for params with structs
1906                 for (int i = 0; i < methParams.size(); i++) {
1907                         String paramType = methPrmTypes.get(i);
1908                         String param = methParams.get(i);
1909                         String simpleType = getSimpleType(paramType);
1910                         boolean begin = true;
1911                         if (isStructClass(simpleType)) {
1912                                 structExist = true;
1913                                 if (!begin) {
1914                                         print(", "); begin = false;
1915                                 }
1916                                 int methodNumId = intDecl.getMethodNumId(method);
1917                                 print("struct" + methodNumId + "Size" + i);
1918                         }
1919                 }
1920                 return structExist;
1921         }
1922
1923
1924         /**
1925          * HELPER: writeMethodCallStructSkeleton() writes method call for wait invoke in skeleton
1926          */
1927         private void writeMethodCallStructSkeleton(Collection<String> methods, InterfaceDecl intDecl) {
1928
1929                 // Use this set to handle two same methodIds
1930                 for (String method : methods) {
1931
1932                         List<String> methParams = intDecl.getMethodParams(method);
1933                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1934                         // Check for params with structs
1935                         for (int i = 0; i < methParams.size(); i++) {
1936                                 String paramType = methPrmTypes.get(i);
1937                                 String param = methParams.get(i);
1938                                 String simpleType = getSimpleType(paramType);
1939                                 if (isStructClass(simpleType)) {
1940                                         int methodNumId = intDecl.getMethodNumId(method);
1941                                         print("case ");
1942                                         String helperMethod = methodNumId + "struct" + i;
1943                                         String tempVar = "struct" + methodNumId + "Size" + i;
1944                                         print(intDecl.getHelperMethodNumId(helperMethod) + ": ");
1945                                         print(tempVar + " = ___");
1946                                         println(helperMethod + "(); break;");
1947                                 }
1948                         }
1949                 }
1950         }
1951
1952
1953         /**
1954          * HELPER: writeMethodCallStructCallbackSkeleton() writes method call for wait invoke in skeleton
1955          */
1956         private void writeMethodCallStructCallbackSkeleton(Collection<String> methods, InterfaceDecl intDecl) {
1957
1958                 // Use this set to handle two same methodIds
1959                 for (String method : methods) {
1960
1961                         List<String> methParams = intDecl.getMethodParams(method);
1962                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1963                         // Check for params with structs
1964                         for (int i = 0; i < methParams.size(); i++) {
1965                                 String paramType = methPrmTypes.get(i);
1966                                 String param = methParams.get(i);
1967                                 String simpleType = getSimpleType(paramType);
1968                                 if (isStructClass(simpleType)) {
1969                                         int methodNumId = intDecl.getMethodNumId(method);
1970                                         print("case ");
1971                                         String helperMethod = methodNumId + "struct" + i;
1972                                         String tempVar = "struct" + methodNumId + "Size" + i;
1973                                         print(intDecl.getHelperMethodNumId(helperMethod) + ": ");
1974                                         print(tempVar + " = ___");
1975                                         println(helperMethod + "(rmiObj); break;");
1976                                 }
1977                         }
1978                 }
1979         }
1980
1981
1982         /**
1983          * HELPER: writeJavaMethodPermission() writes permission checks in skeleton
1984          */
1985         private void writeJavaMethodPermission(String intface) {
1986
1987                 // Get all the different stubs
1988                 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
1989                 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
1990                         String newIntface = intMeth.getKey();
1991                         int newObjectId = getNewIntfaceObjectId(newIntface);
1992                         println("if (_objectId == object" + newObjectId + "Id) {");
1993                         println("if (!set" + newObjectId + "Allowed.contains(methodId)) {");
1994                         println("throw new Error(\"Object with object Id: \" + _objectId + \"  is not allowed to access method: \" + methodId);");
1995                         println("}");
1996                         println("}");
1997                         println("else {");
1998                         println("throw new Error(\"Object Id: \" + _objectId + \" not recognized!\");");
1999                         println("}");
2000                 }
2001         }
2002
2003
2004         /**
2005          * HELPER: writeJavaWaitRequestInvokeMethod() writes the main loop of the skeleton class
2006          */
2007         private void writeJavaWaitRequestInvokeMethod(Collection<String> methods, InterfaceDecl intDecl, boolean callbackExist, String intface) {
2008
2009                 // Use this set to handle two same methodIds
2010                 Set<String> uniqueMethodIds = new HashSet<String>();
2011                 println("private void ___waitRequestInvokeMethod() throws IOException {");
2012                 // Write variables here if we have callbacks or enums or structs
2013                 writeCountVarStructSkeleton(methods, intDecl);
2014                 println("while (true) {");
2015                 println("rmiObj.getMethodBytes();");
2016                 println("int _objectId = rmiObj.getObjectId();");
2017                 println("int methodId = rmiObj.getMethodId();");
2018                 // Generate permission check
2019                 writeJavaMethodPermission(intface);
2020                 println("switch (methodId) {");
2021                 // Print methods and method Ids
2022                 for (String method : methods) {
2023                         String methodId = intDecl.getMethodId(method);
2024                         int methodNumId = intDecl.getMethodNumId(method);
2025                         print("case " + methodNumId + ": ___");
2026                         String helperMethod = methodId;
2027                         if (uniqueMethodIds.contains(methodId))
2028                                 helperMethod = helperMethod + methodNumId;
2029                         else
2030                                 uniqueMethodIds.add(methodId);
2031                         print(helperMethod + "(");
2032                         writeInputCountVarStructSkeleton(method, intDecl);
2033                         println("); break;");
2034                 }
2035                 String method = "___initCallBack()";
2036                 // Print case -9999 (callback handler) if callback exists
2037                 if (callbackExist) {
2038                         int methodId = intDecl.getHelperMethodNumId(method);
2039                         println("case " + methodId + ": ___regCB(); break;");
2040                 }
2041                 writeMethodCallStructSkeleton(methods, intDecl);
2042                 println("default: ");
2043                 println("throw new Error(\"Method Id \" + methodId + \" not recognized!\");");
2044                 println("}");
2045                 println("}");
2046                 println("}\n");
2047         }
2048
2049
2050         /**
2051          * generateJavaSkeletonClass() generate skeletons based on the methods list in Java
2052          */
2053         public void generateJavaSkeletonClass() throws IOException {
2054
2055                 // Create a new directory
2056                 String path = createDirectories(dir, subdir);
2057                 for (String intface : mapIntfacePTH.keySet()) {
2058                         // Open a new file to write into
2059                         String newSkelClass = intface + "_Skeleton";
2060                         FileWriter fw = new FileWriter(path + "/" + newSkelClass + ".java");
2061                         pw = new PrintWriter(new BufferedWriter(fw));
2062                         // Pass in set of methods and get import classes
2063                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2064                         InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
2065                         List<String> methods = intDecl.getMethods();
2066                         Set<String> importClasses = getImportClasses(methods, intDecl);
2067                         List<String> stdImportClasses = getStandardJavaImportClasses();
2068                         List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
2069                         printImportStatements(allImportClasses);
2070                         // Find out if there are callback objects
2071                         Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
2072                         boolean callbackExist = !callbackClasses.isEmpty();
2073                         // Write class header
2074                         println("");
2075                         println("public class " + newSkelClass  + " implements " + intface + " {\n");
2076                         // Write properties
2077                         writePropertiesJavaSkeleton(intface, callbackExist, intDecl);
2078                         // Write constructor
2079                         writeConstructorJavaSkeleton(newSkelClass, intface);
2080                         // Write methods
2081                         writeMethodJavaSkeleton(methods, intDecl, callbackClasses, false);
2082                         // Write method helper
2083                         writeMethodHelperJavaSkeleton(methods, intDecl, callbackClasses);
2084                         // Write waitRequestInvokeMethod() - main loop
2085                         writeJavaWaitRequestInvokeMethod(methods, intDecl, callbackExist, intface);
2086                         println("}");
2087                         pw.close();
2088                         System.out.println("IoTCompiler: Generated skeleton class " + newSkelClass + ".java...");
2089                 }
2090         }
2091
2092
2093         /**
2094          * HELPER: writePropertiesJavaCallbackSkeleton() writes the properties of the callback skeleton class
2095          */
2096         private void writePropertiesJavaCallbackSkeleton(String intface, boolean callbackExist) {
2097
2098                 println("private " + intface + " mainObj;");
2099                 // For callback skeletons, this is its own object Id
2100                 println("private static int objectId = 0;");
2101                 // Callback
2102                 if (callbackExist) {
2103                         println("private static int objIdCnt = 0;");
2104                         println("private IoTRMICall rmiCall;");
2105                 }
2106                 println("\n");
2107         }
2108
2109
2110         /**
2111          * HELPER: writeConstructorJavaCallbackSkeleton() writes the constructor of the skeleton class
2112          */
2113         private void writeConstructorJavaCallbackSkeleton(String newSkelClass, String intface) {
2114
2115                 println("public " + newSkelClass + "(" + intface + " _mainObj, int _objectId) throws Exception {");
2116                 println("mainObj = _mainObj;");
2117                 println("objectId = _objectId;");
2118                 println("}\n");
2119         }
2120
2121
2122         /**
2123          * HELPER: writeMethodHelperJavaCallbackSkeleton() writes the method helper of the callback skeleton class
2124          */
2125         private void writeMethodHelperJavaCallbackSkeleton(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
2126
2127                 // Use this set to handle two same methodIds
2128                 Set<String> uniqueMethodIds = new HashSet<String>();
2129                 for (String method : methods) {
2130
2131                         List<String> methParams = intDecl.getMethodParams(method);
2132                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2133                         if (isStructPresent(methParams, methPrmTypes)) {        // Treat struct differently
2134                                 String methodId = intDecl.getMethodId(method);
2135                                 print("public void ___");
2136                                 String helperMethod = methodId;
2137                                 if (uniqueMethodIds.contains(methodId))
2138                                         helperMethod = helperMethod + intDecl.getMethodNumId(method);
2139                                 else
2140                                         uniqueMethodIds.add(methodId);
2141                                 String retType = intDecl.getMethodType(method);
2142                                 print(helperMethod + "(");
2143                                 boolean begin = true;
2144                                 for (int i = 0; i < methParams.size(); i++) { // Print size variables
2145                                         String paramType = methPrmTypes.get(i);
2146                                         String param = methParams.get(i);
2147                                         String simpleType = getSimpleType(paramType);
2148                                         if (isStructClass(simpleType)) {
2149                                                 if (!begin) {   // Generate comma for not the beginning variable
2150                                                         print(", "); begin = false;
2151                                                 }
2152                                                 int methodNumId = intDecl.getMethodNumId(method);
2153                                                 print("int struct" + methodNumId + "Size" + i);
2154                                         }
2155                                 }
2156                                 // Check if this is "void"
2157                                 if (retType.equals("void"))
2158                                         println(", IoTRMIObject rmiObj) {");
2159                                 else
2160                                         println(", IoTRMIObject rmiObj) throws IOException {");
2161                                 writeMethodHelperStructJavaSkeleton(intDecl, methParams, methPrmTypes, method, callbackClasses);
2162                                 println("}\n");
2163                         } else {
2164                                 String methodId = intDecl.getMethodId(method);
2165                                 print("public void ___");
2166                                 String helperMethod = methodId;
2167                                 if (uniqueMethodIds.contains(methodId))
2168                                         helperMethod = helperMethod + intDecl.getMethodNumId(method);
2169                                 else
2170                                         uniqueMethodIds.add(methodId);
2171                                 // Check if this is "void"
2172                                 String retType = intDecl.getMethodType(method);
2173                                 if (retType.equals("void"))
2174                                         println(helperMethod + "(IoTRMIObject rmiObj) {");
2175                                 else
2176                                         println(helperMethod + "(IoTRMIObject rmiObj) throws IOException {");
2177                                 // Now, write the helper body of skeleton!
2178                                 writeStdMethodHelperBodyJavaSkeleton(intDecl, methParams, methPrmTypes, method, callbackClasses);
2179                                 println("}\n");
2180                         }
2181                 }
2182                 // Write method helper for structs
2183                 writeMethodHelperStructSetupJavaCallbackSkeleton(methods, intDecl);
2184         }
2185
2186
2187         /**
2188          * HELPER: writeJavaCallbackWaitRequestInvokeMethod() writes the request invoke method of the callback skeleton class
2189          */
2190         private void writeJavaCallbackWaitRequestInvokeMethod(Collection<String> methods, InterfaceDecl intDecl, boolean callbackExist) {
2191
2192                 // Use this set to handle two same methodIds
2193                 Set<String> uniqueMethodIds = new HashSet<String>();
2194                 println("public void invokeMethod(IoTRMIObject rmiObj) throws IOException {");
2195                 // Write variables here if we have callbacks or enums or structs
2196                 writeCountVarStructSkeleton(methods, intDecl);
2197                 // Write variables here if we have callbacks or enums or structs
2198                 println("int methodId = rmiObj.getMethodId();");
2199                 // TODO: code the permission check here!
2200                 println("switch (methodId) {");
2201                 // Print methods and method Ids
2202                 for (String method : methods) {
2203                         String methodId = intDecl.getMethodId(method);
2204                         int methodNumId = intDecl.getMethodNumId(method);
2205                         print("case " + methodNumId + ": ___");
2206                         String helperMethod = methodId;
2207                         if (uniqueMethodIds.contains(methodId))
2208                                 helperMethod = helperMethod + methodNumId;
2209                         else
2210                                 uniqueMethodIds.add(methodId);
2211                         print(helperMethod + "(");
2212                         if (writeInputCountVarStructSkeleton(method, intDecl))
2213                                 println(", rmiObj); break;");
2214                         else
2215                                 println("rmiObj); break;");
2216                 }
2217                 String method = "___initCallBack()";
2218                 // Print case -9999 (callback handler) if callback exists
2219                 if (callbackExist) {
2220                         int methodId = intDecl.getHelperMethodNumId(method);
2221                         println("case " + methodId + ": ___regCB(rmiObj); break;");
2222                 }
2223                 writeMethodCallStructCallbackSkeleton(methods, intDecl);
2224                 println("default: ");
2225                 println("throw new Error(\"Method Id \" + methodId + \" not recognized!\");");
2226                 println("}");
2227                 println("}\n");
2228         }
2229
2230
2231         /**
2232          * generateJavaCallbackSkeletonClass() generate callback skeletons based on the methods list in Java
2233          */
2234         public void generateJavaCallbackSkeletonClass() throws IOException {
2235
2236                 // Create a new directory
2237                 String path = createDirectories(dir, subdir);
2238                 for (String intface : mapIntfacePTH.keySet()) {
2239                         // Open a new file to write into
2240                         String newSkelClass = intface + "_CallbackSkeleton";
2241                         FileWriter fw = new FileWriter(path + "/" + newSkelClass + ".java");
2242                         pw = new PrintWriter(new BufferedWriter(fw));
2243                         // Pass in set of methods and get import classes
2244                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2245                         InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
2246                         List<String> methods = intDecl.getMethods();
2247                         Set<String> importClasses = getImportClasses(methods, intDecl);
2248                         List<String> stdImportClasses = getStandardJavaImportClasses();
2249                         List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
2250                         printImportStatements(allImportClasses);
2251                         // Find out if there are callback objects
2252                         Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
2253                         boolean callbackExist = !callbackClasses.isEmpty();
2254                         // Write class header
2255                         println("");
2256                         println("public class " + newSkelClass  + " implements " + intface + " {\n");
2257                         // Write properties
2258                         writePropertiesJavaCallbackSkeleton(intface, callbackExist);
2259                         // Write constructor
2260                         writeConstructorJavaCallbackSkeleton(newSkelClass, intface);
2261                         // Write methods
2262                         writeMethodJavaSkeleton(methods, intDecl, callbackClasses, true);
2263                         // Write method helper
2264                         writeMethodHelperJavaCallbackSkeleton(methods, intDecl, callbackClasses);
2265                         // Write waitRequestInvokeMethod() - main loop
2266                         writeJavaCallbackWaitRequestInvokeMethod(methods, intDecl, callbackExist);
2267                         println("}");
2268                         pw.close();
2269                         System.out.println("IoTCompiler: Generated callback skeleton class " + newSkelClass + ".java...");
2270                 }
2271         }
2272
2273
2274         /**
2275          * HELPER: writeMethodCplusLocalInterface() writes the method of the local interface
2276          */
2277         private void writeMethodCplusLocalInterface(Collection<String> methods, InterfaceDecl intDecl) {
2278
2279                 for (String method : methods) {
2280
2281                         List<String> methParams = intDecl.getMethodParams(method);
2282                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2283                         print("virtual " + checkAndGetCplusType(intDecl.getMethodType(method)) + " " +
2284                                 intDecl.getMethodId(method) + "(");
2285                         for (int i = 0; i < methParams.size(); i++) {
2286                                 // Check for params with driver class types and exchange it 
2287                                 //              with its remote interface
2288                                 String paramType = checkAndGetParamClass(methPrmTypes.get(i));
2289                                 paramType = checkAndGetCplusType(paramType);
2290                                 // Check for arrays - translate into vector in C++
2291                                 String paramComplete = checkAndGetCplusArray(paramType, methParams.get(i));
2292                                 print(paramComplete);
2293                                 // Check if this is the last element (don't print a comma)
2294                                 if (i != methParams.size() - 1) {
2295                                         print(", ");
2296                                 }
2297                         }
2298                         println(") = 0;");
2299                 }
2300         }
2301
2302
2303         /**
2304          * HELPER: writeMethodCplusInterface() writes the method of the interface
2305          */
2306         private void writeMethodCplusInterface(Collection<String> methods, InterfaceDecl intDecl) {
2307
2308                 for (String method : methods) {
2309
2310                         List<String> methParams = intDecl.getMethodParams(method);
2311                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2312                         print("virtual " + checkAndGetCplusType(intDecl.getMethodType(method)) + " " +
2313                                 intDecl.getMethodId(method) + "(");
2314                         for (int i = 0; i < methParams.size(); i++) {
2315                                 // Check for params with driver class types and exchange it 
2316                                 //              with its remote interface
2317                                 String paramType = methPrmTypes.get(i);
2318                                 paramType = checkAndGetCplusType(paramType);
2319                                 // Check for arrays - translate into vector in C++
2320                                 String paramComplete = checkAndGetCplusArray(paramType, methParams.get(i));
2321                                 print(paramComplete);
2322                                 // Check if this is the last element (don't print a comma)
2323                                 if (i != methParams.size() - 1) {
2324                                         print(", ");
2325                                 }
2326                         }
2327                         println(") = 0;");
2328                 }
2329         }
2330
2331
2332         /**
2333          * HELPER: generateEnumCplus() writes the enumeration declaration
2334          */
2335         public void generateEnumCplus() throws IOException {
2336
2337                 // Create a new directory
2338                 createDirectory(dir);
2339                 for (String intface : mapIntfacePTH.keySet()) {
2340                         // Get the right StructDecl
2341                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2342                         EnumDecl enumDecl = (EnumDecl) decHandler.getEnumDecl(intface);
2343                         Set<String> enumTypes = enumDecl.getEnumDeclarations();
2344                         // Iterate over enum declarations
2345                         for (String enType : enumTypes) {
2346                                 // Open a new file to write into
2347                                 FileWriter fw = new FileWriter(dir + "/" + enType + ".hpp");
2348                                 pw = new PrintWriter(new BufferedWriter(fw));
2349                                 // Write file headers
2350                                 println("#ifndef _" + enType.toUpperCase() + "_HPP__");
2351                                 println("#define _" + enType.toUpperCase() + "_HPP__");
2352                                 println("enum " + enType + " {");
2353                                 List<String> enumMembers = enumDecl.getMembers(enType);
2354                                 for (int i = 0; i < enumMembers.size(); i++) {
2355
2356                                         String member = enumMembers.get(i);
2357                                         print(member);
2358                                         // Check if this is the last element (don't print a comma)
2359                                         if (i != enumMembers.size() - 1)
2360                                                 println(",");
2361                                         else
2362                                                 println("");
2363                                 }
2364                                 println("};\n");
2365                                 println("#endif");
2366                                 pw.close();
2367                                 System.out.println("IoTCompiler: Generated enum " + enType + ".hpp...");
2368                         }
2369                 }
2370         }
2371
2372
2373         /**
2374          * HELPER: generateStructCplus() writes the struct declaration
2375          */
2376         public void generateStructCplus() throws IOException {
2377
2378                 // Create a new directory
2379                 createDirectory(dir);
2380                 for (String intface : mapIntfacePTH.keySet()) {
2381                         // Get the right StructDecl
2382                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2383                         StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
2384                         List<String> structTypes = structDecl.getStructTypes();
2385                         // Iterate over enum declarations
2386                         for (String stType : structTypes) {
2387                                 // Open a new file to write into
2388                                 FileWriter fw = new FileWriter(dir + "/" + stType + ".hpp");
2389                                 pw = new PrintWriter(new BufferedWriter(fw));
2390                                 // Write file headers
2391                                 println("#ifndef _" + stType.toUpperCase() + "_HPP__");
2392                                 println("#define _" + stType.toUpperCase() + "_HPP__");
2393                                 println("struct " + stType + " {");
2394                                 List<String> structMemberTypes = structDecl.getMemberTypes(stType);
2395                                 List<String> structMembers = structDecl.getMembers(stType);
2396                                 for (int i = 0; i < structMembers.size(); i++) {
2397
2398                                         String memberType = structMemberTypes.get(i);
2399                                         String member = structMembers.get(i);
2400                                         String structTypeC = checkAndGetCplusType(memberType);
2401                                         String structComplete = checkAndGetCplusArray(structTypeC, member);
2402                                         println(structComplete + ";");
2403                                 }
2404                                 println("};\n");
2405                                 println("#endif");
2406                                 pw.close();
2407                                 System.out.println("IoTCompiler: Generated struct " + stType + ".hpp...");
2408                         }
2409                 }
2410         }
2411
2412
2413         /**
2414          * generateCplusLocalInterfaces() writes the local interfaces and provides type-checking.
2415          * <p>
2416          * It needs to rewrite and exchange USERDEFINED types in input parameters of stub
2417          * and original interfaces, e.g. exchange Camera and CameraWithVideoAndRecording.
2418          * The local interface has to be the input parameter for the stub and the stub 
2419          * interface has to be the input parameter for the local class.
2420          */
2421         public void generateCplusLocalInterfaces() throws IOException {
2422
2423                 // Create a new directory
2424                 createDirectory(dir);
2425                 for (String intface : mapIntfacePTH.keySet()) {
2426                         // Open a new file to write into
2427                         FileWriter fw = new FileWriter(dir + "/" + intface + ".hpp");
2428                         pw = new PrintWriter(new BufferedWriter(fw));
2429                         // Write file headers
2430                         println("#ifndef _" + intface.toUpperCase() + "_HPP__");
2431                         println("#define _" + intface.toUpperCase() + "_HPP__");
2432                         println("#include <iostream>");
2433                         // Pass in set of methods and get include classes
2434                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2435                         InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
2436                         List<String> methods = intDecl.getMethods();
2437                         Set<String> includeClasses = getIncludeClasses(methods, intDecl, intface, true);
2438                         printIncludeStatements(includeClasses); println("");
2439                         println("using namespace std;\n");
2440                         //writeStructCplus(structDecl);
2441                         println("class " + intface); println("{");
2442                         println("public:");
2443                         // Write methods
2444                         writeMethodCplusLocalInterface(methods, intDecl);
2445                         println("};");
2446                         println("#endif");
2447                         pw.close();
2448                         System.out.println("IoTCompiler: Generated local interface " + intface + ".hpp...");
2449                 }
2450         }
2451
2452
2453         /**
2454          * generateCPlusInterfaces() generate stub interfaces based on the methods list in C++
2455          * <p>
2456          * For C++ we use virtual classe as interface
2457          */
2458         public void generateCPlusInterfaces() throws IOException {
2459
2460                 // Create a new directory
2461                 String path = createDirectories(dir, subdir);
2462                 for (String intface : mapIntfacePTH.keySet()) {
2463
2464                         Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
2465                         for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
2466
2467                                 // Open a new file to write into
2468                                 String newIntface = intMeth.getKey();
2469                                 FileWriter fw = new FileWriter(path + "/" + newIntface + ".hpp");
2470                                 pw = new PrintWriter(new BufferedWriter(fw));
2471                                 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2472                                 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
2473                                 // Write file headers
2474                                 println("#ifndef _" + newIntface.toUpperCase() + "_HPP__");
2475                                 println("#define _" + newIntface.toUpperCase() + "_HPP__");
2476                                 println("#include <iostream>");
2477                                 // Pass in set of methods and get import classes
2478                                 Set<String> includeClasses = getIncludeClasses(intMeth.getValue(), intDecl, intface, false);
2479                                 List<String> stdIncludeClasses = getStandardCplusIncludeClasses();
2480                                 List<String> allIncludeClasses = getAllLibClasses(stdIncludeClasses, includeClasses);
2481                                 printIncludeStatements(allIncludeClasses); println("");                 
2482                                 println("using namespace std;\n");
2483                                 println("class " + newIntface);
2484                                 println("{");
2485                                 println("public:");
2486                                 // Write methods
2487                                 writeMethodCplusInterface(intMeth.getValue(), intDecl);
2488                                 println("};");
2489                                 println("#endif");
2490                                 pw.close();
2491                                 System.out.println("IoTCompiler: Generated interface " + newIntface + ".hpp...");
2492                         }
2493                 }
2494         }
2495
2496
2497         /**
2498          * HELPER: writeMethodCplusStub() writes the methods of the stub
2499          */
2500         private void writeMethodCplusStub(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
2501
2502                 for (String method : methods) {
2503
2504                         List<String> methParams = intDecl.getMethodParams(method);
2505                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2506
2507                         //System.out.println("\n\nMethod return type: " + checkAndGetCplusType(intDecl.getMethodType(method)) + "\n\n");
2508
2509                         print(checkAndGetCplusType(intDecl.getMethodType(method)) + " " +
2510                                 intDecl.getMethodId(method) + "(");
2511                         boolean isCallbackMethod = false;
2512                         String callbackType = null;
2513                         for (int i = 0; i < methParams.size(); i++) {
2514
2515                                 String paramType = methPrmTypes.get(i);
2516                                 // Check if this has callback object
2517                                 if (callbackClasses.contains(paramType)) {
2518                                         isCallbackMethod = true;
2519                                         callbackType = paramType;       
2520                                         // Even if there're 2 callback arguments, we expect them to be of the same interface
2521                                 }
2522                                 String methPrmType = checkAndGetCplusType(methPrmTypes.get(i));
2523                                 String methParamComplete = checkAndGetCplusArray(methPrmType, methParams.get(i));
2524                                 print(methParamComplete);
2525                                 // Check if this is the last element (don't print a comma)
2526                                 if (i != methParams.size() - 1) {
2527                                         print(", ");
2528                                 }
2529                         }
2530                         println(") { ");
2531                         if (isCallbackMethod)
2532                                 writeCallbackMethodBodyCplusStub(intDecl, methParams, methPrmTypes, method, callbackType);
2533                         else
2534                                 writeStdMethodBodyCplusStub(intDecl, methParams, methPrmTypes, method);
2535                         println("}\n");
2536                         // Write the init callback helper method
2537                         if (isCallbackMethod) {
2538                                 writeInitCallbackCplusStub(callbackType, intDecl);
2539                                 writeInitCallbackSendInfoCplusStub(intDecl);
2540                         }
2541                 }
2542         }
2543
2544
2545         /**
2546          * HELPER: writeCallbackMethodBodyCplusStub() writes the callback method of the stub class
2547          */
2548         private void writeCallbackMethodBodyCplusStub(InterfaceDecl intDecl, List<String> methParams,
2549                         List<String> methPrmTypes, String method, String callbackType) {
2550
2551                 // Check if this is single object, array, or list of objects
2552                 boolean isArrayOrList = false;
2553                 String callbackParam = null;
2554                 for (int i = 0; i < methParams.size(); i++) {
2555
2556                         String paramType = methPrmTypes.get(i);
2557                         if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
2558                                 String param = methParams.get(i);
2559                                 if (isArrayOrList(paramType, param)) {  // Generate loop
2560                                         println("for (" + paramType + "* cb : " + getSimpleIdentifier(param) + ") {");
2561                                         println(callbackType + "_CallbackSkeleton* skel = new " + callbackType + "_CallbackSkeleton(cb, objIdCnt++);");
2562                                         isArrayOrList = true;
2563                                         callbackParam = getSimpleIdentifier(param);
2564                                 } else
2565                                         println(callbackType + "_CallbackSkeleton* skel = new " + callbackType + "_CallbackSkeleton(" +
2566                                                 getSimpleIdentifier(param) + ", objIdCnt++);");
2567                                 println("vecCallbackObj.push_back(skel);");
2568                                 if (isArrayOrList(paramType, param))
2569                                         println("}");
2570                         }
2571                 }
2572                 println("int numParam = " + methParams.size() + ";");
2573                 println("int methodId = " + intDecl.getMethodNumId(method) + ";");
2574                 String retType = intDecl.getMethodType(method);
2575                 //String retTypeC = checkAndGetCplusType(retType);
2576                 //println("string retType = \"" + checkAndGetCplusArrayType(getStructType(getEnumType(retTypeC))) + "\";");
2577                 println("string retType = \"" + checkAndGetCplusRetClsType(getStructType(getEnumType(retType))) + "\";");
2578                 // Generate array of parameter types
2579                 print("string paramCls[] = { ");
2580                 for (int i = 0; i < methParams.size(); i++) {
2581                         String paramType = methPrmTypes.get(i);
2582                         if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
2583                                 print("\"int\"");
2584                         } else { // Generate normal classes if it's not a callback object
2585                                 //String paramTypeC = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
2586                                 //String prmType = getSimpleType(getEnumType(paramTypeC));
2587                                 String paramTypeC = checkAndGetCplusArgClsType(methPrmTypes.get(i), methParams.get(i));
2588                                 String prmType = getEnumType(paramTypeC);
2589                                 print("\"" + prmType + "\"");
2590                         }
2591                         if (i != methParams.size() - 1) // Check if this is the last element
2592                                 print(", ");
2593                 }
2594                 println(" };");
2595                 print("int ___paramCB = ");
2596                 if (isArrayOrList)
2597                         println(callbackParam + ".size();");
2598                 else
2599                         println("1;");
2600                 // Generate array of parameter objects
2601                 print("void* paramObj[] = { ");
2602                 for (int i = 0; i < methParams.size(); i++) {
2603                         String paramType = methPrmTypes.get(i);
2604                         if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
2605                                 print("&___paramCB");