180de2e085ded2b0b1c057f47ccac092b19754f4
[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          * Class constants
64          */
65         private final static String OUTPUT_DIRECTORY = "output_files";
66
67         private enum ParamCategory {
68
69                 PRIMITIVES,             // All the primitive types, e.g. byte, short, int, long, etc.
70                 NONPRIMITIVES,  // Non-primitive types, e.g. Set, Map, List, etc.
71                 ENUM,                   // Enum type
72                 STRUCT,                 // Struct type
73                 USERDEFINED             // Assumed as driver classes
74         }
75
76         /**
77          * Class constructors
78          */
79         public IoTCompiler() {
80
81                 mapIntfacePTH = new HashMap<String,ParseTreeHandler>();
82                 mapIntDeclHand = new HashMap<String,DeclarationHandler>();
83                 mapInt2NewInts = new HashMap<String,Map<String,Set<String>>>();
84                 mapIntfaceObjId = new HashMap<String,Integer>();
85                 mapNewIntfaceObjId = new HashMap<String,Integer>();
86                 mapPrimitives = new HashMap<String,String>();
87                         arraysToMap(mapPrimitives, IoTRMITypes.primitivesJava, IoTRMITypes.primitivesCplus);
88                 mapNonPrimitivesJava = new HashMap<String,String>();
89                         arraysToMap(mapNonPrimitivesJava, IoTRMITypes.nonPrimitivesJava, IoTRMITypes.nonPrimitiveJavaLibs);
90                 mapNonPrimitivesCplus = new HashMap<String,String>();
91                         arraysToMap(mapNonPrimitivesCplus, IoTRMITypes.nonPrimitivesJava, IoTRMITypes.nonPrimitivesCplus);
92                 pw = null;
93                 dir = OUTPUT_DIRECTORY;
94                 subdir = null;
95         }
96
97
98         /**
99          * setDataStructures() sets parse tree and other data structures based on policy files.
100          * <p>
101          * It also generates parse tree (ParseTreeHandler) and
102          * copies useful information from parse tree into
103          * InterfaceDecl, CapabilityDecl, and RequiresDecl 
104          * data structures.
105          * Additionally, the data structure handles are
106          * returned from tree-parsing for further process.
107          *
108          */
109         public void setDataStructures(String origInt, ParseNode pnPol, ParseNode pnReq) {
110
111                 ParseTreeHandler ptHandler = new ParseTreeHandler(origInt, pnPol, pnReq);
112                 DeclarationHandler decHandler = new DeclarationHandler();
113                 // Process ParseNode and generate Declaration objects
114                 // Interface
115                 ptHandler.processInterfaceDecl();
116                 InterfaceDecl intDecl = ptHandler.getInterfaceDecl();
117                 decHandler.addInterfaceDecl(origInt, intDecl);
118                 // Capabilities
119                 ptHandler.processCapabilityDecl();
120                 CapabilityDecl capDecl = ptHandler.getCapabilityDecl();
121                 decHandler.addCapabilityDecl(origInt, capDecl);
122                 // Requires
123                 ptHandler.processRequiresDecl();
124                 RequiresDecl reqDecl = ptHandler.getRequiresDecl();
125                 decHandler.addRequiresDecl(origInt, reqDecl);
126                 // Enumeration
127                 ptHandler.processEnumDecl();
128                 EnumDecl enumDecl = ptHandler.getEnumDecl();
129                 decHandler.addEnumDecl(origInt, enumDecl);
130                 // Struct
131                 ptHandler.processStructDecl();
132                 StructDecl structDecl = ptHandler.getStructDecl();
133                 decHandler.addStructDecl(origInt, structDecl);
134
135                 mapIntfacePTH.put(origInt, ptHandler);
136                 mapIntDeclHand.put(origInt, decHandler);
137                 // Set object Id counter to 0 for each interface
138                 mapIntfaceObjId.put(origInt, new Integer(0));
139         }
140
141
142         /**
143          * getMethodsForIntface() reads for methods in the data structure
144          * <p>
145          * It is going to give list of methods for a certain interface
146          *              based on the declaration of capabilities.
147          */
148         public void getMethodsForIntface(String origInt) {
149
150                 ParseTreeHandler ptHandler = mapIntfacePTH.get(origInt);
151                 Map<String,Set<String>> mapNewIntMethods = new HashMap<String,Set<String>>();
152                 // Get set of new interfaces, e.g. CameraWithCaptureAndData
153                 // Generate this new interface with all the methods it needs
154                 //              from different capabilities it declares
155                 DeclarationHandler decHandler = mapIntDeclHand.get(origInt);
156                 RequiresDecl reqDecl = (RequiresDecl) decHandler.getRequiresDecl(origInt);
157                 Set<String> setIntfaces = reqDecl.getInterfaces();
158                 for (String strInt : setIntfaces) {
159
160                         // Initialize a set of methods
161                         Set<String> setMethods = new HashSet<String>();
162                         // Get list of capabilities, e.g. ImageCapture, VideoRecording, etc.
163                         List<String> listCapab = reqDecl.getCapabList(strInt);
164                         for (String strCap : listCapab) {
165
166                                 // Get list of methods for each capability
167                                 CapabilityDecl capDecl = (CapabilityDecl) decHandler.getCapabilityDecl(origInt);
168                                 List<String> listCapabMeth = capDecl.getMethods(strCap);
169                                 for (String strMeth : listCapabMeth) {
170
171                                         // Add methods into setMethods
172                                         // This is to also handle redundancies (say two capabilities
173                                         //              share the same methods)
174                                         setMethods.add(strMeth);
175                                 }
176                         }
177                         // Add interface and methods information into map
178                         mapNewIntMethods.put(strInt, setMethods);
179                 }
180                 // Map the map of interface-methods to the original interface
181                 mapInt2NewInts.put(origInt, mapNewIntMethods);
182         }
183
184
185         /**
186          * HELPER: writeMethodJavaLocalInterface() writes the method of the interface
187          */
188         private void writeMethodJavaLocalInterface(Collection<String> methods, InterfaceDecl intDecl) {
189
190                 for (String method : methods) {
191
192                         List<String> methParams = intDecl.getMethodParams(method);
193                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
194                         print("public " + intDecl.getMethodType(method) + " " +
195                                 intDecl.getMethodId(method) + "(");
196                         for (int i = 0; i < methParams.size(); i++) {
197                                 // Check for params with driver class types and exchange it 
198                                 //              with its remote interface
199                                 String paramType = checkAndGetParamClass(methPrmTypes.get(i));
200                                 print(paramType + " " + methParams.get(i));
201                                 // Check if this is the last element (don't print a comma)
202                                 if (i != methParams.size() - 1) {
203                                         print(", ");
204                                 }
205                         }
206                         println(");");
207                 }
208         }
209
210
211         /**
212          * HELPER: writeMethodJavaInterface() writes the method of the interface
213          */
214         private void writeMethodJavaInterface(Collection<String> methods, InterfaceDecl intDecl) {
215
216                 for (String method : methods) {
217
218                         List<String> methParams = intDecl.getMethodParams(method);
219                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
220                         print("public " + intDecl.getMethodType(method) + " " +
221                                 intDecl.getMethodId(method) + "(");
222                         for (int i = 0; i < methParams.size(); i++) {
223                                 // Check for params with driver class types and exchange it 
224                                 //              with its remote interface
225                                 String paramType = methPrmTypes.get(i);
226                                 print(paramType + " " + methParams.get(i));
227                                 // Check if this is the last element (don't print a comma)
228                                 if (i != methParams.size() - 1) {
229                                         print(", ");
230                                 }
231                         }
232                         println(");");
233                 }
234         }
235
236
237         /**
238          * HELPER: generateEnumJava() writes the enumeration declaration
239          */
240         private void generateEnumJava() throws IOException {
241
242                 // Create a new directory
243                 createDirectory(dir);
244                 for (String intface : mapIntfacePTH.keySet()) {
245                         // Get the right EnumDecl
246                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
247                         EnumDecl enumDecl = (EnumDecl) decHandler.getEnumDecl(intface);
248                         Set<String> enumTypes = enumDecl.getEnumDeclarations();
249                         // Iterate over enum declarations
250                         for (String enType : enumTypes) {
251                                 // Open a new file to write into
252                                 FileWriter fw = new FileWriter(dir + "/" + enType + ".java");
253                                 pw = new PrintWriter(new BufferedWriter(fw));
254                                 println("public enum " + enType + " {");
255                                 List<String> enumMembers = enumDecl.getMembers(enType);
256                                 for (int i = 0; i < enumMembers.size(); i++) {
257
258                                         String member = enumMembers.get(i);
259                                         print(member);
260                                         // Check if this is the last element (don't print a comma)
261                                         if (i != enumMembers.size() - 1)
262                                                 println(",");
263                                         else
264                                                 println("");
265                                 }
266                                 println("}\n");
267                                 pw.close();
268                                 System.out.println("IoTCompiler: Generated enum class " + enType + ".java...");
269                         }
270                 }
271         }
272
273
274         /**
275          * HELPER: generateStructJava() writes the struct declaration
276          */
277         private void generateStructJava() throws IOException {
278
279                 // Create a new directory
280                 createDirectory(dir);
281                 for (String intface : mapIntfacePTH.keySet()) {
282                         // Get the right StructDecl
283                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
284                         StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
285                         List<String> structTypes = structDecl.getStructTypes();
286                         // Iterate over enum declarations
287                         for (String stType : structTypes) {
288                                 // Open a new file to write into
289                                 FileWriter fw = new FileWriter(dir + "/" + stType + ".java");
290                                 pw = new PrintWriter(new BufferedWriter(fw));
291                                 println("public class " + stType + " {");
292                                 List<String> structMemberTypes = structDecl.getMemberTypes(stType);
293                                 List<String> structMembers = structDecl.getMembers(stType);
294                                 for (int i = 0; i < structMembers.size(); i++) {
295
296                                         String memberType = structMemberTypes.get(i);
297                                         String member = structMembers.get(i);
298                                         println("public static " + memberType + " " + member + ";");
299                                 }
300                                 println("}\n");
301                                 pw.close();
302                                 System.out.println("IoTCompiler: Generated struct class " + stType + ".java...");
303                         }
304                 }
305         }
306
307
308         /**
309          * generateJavaLocalInterface() writes the local interface and provides type-checking.
310          * <p>
311          * It needs to rewrite and exchange USERDEFINED types in input parameters of stub
312          * and original interfaces, e.g. exchange Camera and CameraWithVideoAndRecording.
313          * The local interface has to be the input parameter for the stub and the stub 
314          * interface has to be the input parameter for the local class.
315          */
316         public void generateJavaLocalInterfaces() throws IOException {
317
318                 // Create a new directory
319                 createDirectory(dir);
320                 for (String intface : mapIntfacePTH.keySet()) {
321                         // Open a new file to write into
322                         FileWriter fw = new FileWriter(dir + "/" + intface + ".java");
323                         pw = new PrintWriter(new BufferedWriter(fw));
324                         // Pass in set of methods and get import classes
325                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
326                         InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
327                         List<String> methods = intDecl.getMethods();
328                         Set<String> importClasses = getImportClasses(methods, intDecl);
329                         printImportStatements(importClasses);
330                         // Write interface header
331                         println("");
332                         println("public interface " + intface + " {");
333                         // Write enum if any...
334                         //EnumDecl enumDecl = (EnumDecl) decHandler.getEnumDecl(intface);
335                         //writeEnumJava(enumDecl);
336                         // Write struct if any...
337                         //StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
338                         //writeStructJava(structDecl);
339                         // Write methods
340                         writeMethodJavaLocalInterface(methods, intDecl);
341                         println("}");
342                         pw.close();
343                         System.out.println("IoTCompiler: Generated local interface " + intface + ".java...");
344                 }
345         }
346
347
348         /**
349          * generateJavaInterfaces() generate stub interfaces based on the methods list in Java
350          */
351         public void generateJavaInterfaces() throws IOException {
352
353                 // Create a new directory
354                 String path = createDirectories(dir, subdir);
355                 for (String intface : mapIntfacePTH.keySet()) {
356
357                         Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
358                         for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
359
360                                 // Open a new file to write into
361                                 String newIntface = intMeth.getKey();
362                                 FileWriter fw = new FileWriter(path + "/" + newIntface + ".java");
363                                 pw = new PrintWriter(new BufferedWriter(fw));
364                                 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
365                                 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
366                                 // Pass in set of methods and get import classes
367                                 Set<String> importClasses = getImportClasses(intMeth.getValue(), intDecl);
368                                 printImportStatements(importClasses);
369                                 // Write interface header
370                                 println("");
371                                 println("public interface " + newIntface + " {\n");
372                                 // Write methods
373                                 writeMethodJavaInterface(intMeth.getValue(), 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 = mapNewIntfaceObjId.get(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 = mapNewIntfaceObjId.get(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 = mapNewIntfaceObjId.get(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: writeConstructorJavaStub() writes the constructor of the stub class
495          */
496         private void writeInitCallbackJavaStub(String intface, InterfaceDecl intDecl) {
497
498                 println("public void ___initCallBack() {");
499                 // Generate main thread for callbacks
500                 println("Thread thread = new Thread() {");
501                 println("public void run() {");
502                 println("try {");
503                 println("rmiObj = new IoTRMIObject(ports[0]);");
504                 println("while (true) {");
505                 println("byte[] method = rmiObj.getMethodBytes();");
506                 writeJavaMethodCallbackPermission(intface);
507                 println("int objId = IoTRMIObject.getObjectId(method);");
508                 println(intface + "_CallbackSkeleton skel = (" + intface + "_CallbackSkeleton) listCallbackObj.get(objId);");
509                 println("if (skel != null) {");
510                 println("skel.invokeMethod(rmiObj);");
511                 println("} else {");
512                 println("throw new Error(\"" + intface + ": Object with Id \" + objId + \" not found!\");");
513                 println("}");
514                 println("}");
515                 println("} catch (Exception ex) {");
516                 println("ex.printStackTrace();");
517                 println("throw new Error(\"Error instantiating class " + intface + "_CallbackSkeleton!\");");
518                 println("}");
519                 println("}");
520                 println("};");
521                 println("thread.start();\n");
522                 // Generate info sending part
523                 String method = "___initCallBack()";
524                 println("int methodId = " + intDecl.getHelperMethodNumId(method) + ";");
525                 println("Class<?> retType = void.class;");
526                 println("Class<?>[] paramCls = new Class<?>[] { int.class, String.class, int.class };");
527                 println("Object[] paramObj = new Object[] { ports[0], address, 0 };");
528                 println("rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
529                 println("}\n");
530         }
531
532
533         /**
534          * HELPER: checkAndWriteEnumTypeJavaStub() writes the enum type (convert from enum to int)
535          */
536         private void checkAndWriteEnumTypeJavaStub(List<String> methParams, List<String> methPrmTypes) {
537
538                 // Iterate and find enum declarations
539                 for (int i = 0; i < methParams.size(); i++) {
540                         String paramType = methPrmTypes.get(i);
541                         String param = methParams.get(i);
542                         String simpleType = getSimpleType(paramType);
543                         if (isEnumClass(simpleType)) {
544                         // Check if this is enum type
545                                 if (isArray(param)) {   // An array
546                                         println("int len" + i + " = " + param + ".length;");
547                                         println("int paramEnum" + i + "[] = new int[len];");
548                                         println("for (int i = 0; i < len" + i + "; i++) {");
549                                         println("paramEnum" + i + "[i] = " + param + "[i].ordinal();");
550                                         println("}");
551                                 } else if (isList(paramType)) { // A list
552                                         println("int len" + i + " = " + param + ".size();");
553                                         println("int paramEnum" + i + "[] = new int[len];");
554                                         println("for (int i = 0; i < len" + i + "; i++) {");
555                                         println("paramEnum" + i + "[i] = " + param + ".get(i).ordinal();");
556                                         println("}");
557                                 } else {        // Just one element
558                                         println("int paramEnum" + i + "[] = new int[1];");
559                                         println("paramEnum" + i + "[0] = " + param + ".ordinal();");
560                                 }
561                         }
562                 }
563         }
564
565
566         /**
567          * HELPER: checkAndWriteEnumRetTypeJavaStub() writes the enum return type (convert from enum to int)
568          */
569         private void checkAndWriteEnumRetTypeJavaStub(String retType) {
570
571                 // Strips off array "[]" for return type
572                 String pureType = getSimpleArrayType(getSimpleType(retType));
573                 // Take the inner type of generic
574                 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
575                         pureType = getTypeOfGeneric(retType)[0];
576                 if (isEnumClass(pureType)) {
577                 // Check if this is enum type
578                         // Enum decoder
579                         println("int[] retEnum = (int[]) retObj;");
580                         println(pureType + "[] enumVals = " + pureType + ".values();");
581                         if (isArray(retType)) {                 // An array
582                                 println("int retLen = retEnum.length;");
583                                 println(pureType + "[] enumRetVal = new " + pureType + "[retLen];");
584                                 println("for (int i = 0; i < retLen; i++) {");
585                                 println("enumRetVal[i] = enumVals[retEnum[i]];");
586                                 println("}");
587                         } else if (isList(retType)) {   // A list
588                                 println("int retLen = retEnum.length;");
589                                 println("List<" + pureType + "> enumRetVal = new ArrayList<" + pureType + ">();");
590                                 println("for (int i = 0; i < retLen; i++) {");
591                                 println("enumRetVal.add(enumVals[retEnum[i]]);");
592                                 println("}");
593                         } else {        // Just one element
594                                 println(pureType + " enumRetVal = enumVals[retEnum[0]];");
595                         }
596                         println("return enumRetVal;");
597                 }
598         }
599
600
601         /**
602          * HELPER: checkAndWriteStructSetupJavaStub() writes the struct type setup
603          */
604         private void checkAndWriteStructSetupJavaStub(List<String> methParams, List<String> methPrmTypes, 
605                         InterfaceDecl intDecl, String method) {
606                 
607                 // Iterate and find struct declarations
608                 for (int i = 0; i < methParams.size(); i++) {
609                         String paramType = methPrmTypes.get(i);
610                         String param = methParams.get(i);
611                         String simpleType = getSimpleType(paramType);
612                         if (isStructClass(simpleType)) {
613                         // Check if this is enum type
614                                 int methodNumId = intDecl.getMethodNumId(method);
615                                 String helperMethod = methodNumId + "struct" + i;
616                                 println("int methodIdStruct" + i + " = " + intDecl.getHelperMethodNumId(helperMethod) + ";");
617                                 println("Class<?> retTypeStruct" + i + " = void.class;");
618                                 println("Class<?>[] paramClsStruct" + i + " = new Class<?>[] { int.class };");
619                                 if (isArray(param)) {   // An array
620                                         println("Object[] paramObjStruct" + i + " = new Object[] { " + getSimpleArrayType(param) + ".length };");
621                                 } else if (isList(paramType)) { // A list
622                                         println("Object[] paramObjStruct" + i + " = new Object[] { " + getSimpleArrayType(param) + ".size() };");
623                                 } else {        // Just one element
624                                         println("Object[] paramObjStruct" + i + " = new Object[] { new Integer(1) };");
625                                 }
626                                 println("rmiCall.remoteCall(objectId, methodIdStruct" + i + 
627                                                 ", retTypeStruct" + i + ", null, paramClsStruct" + i + 
628                                                 ", paramObjStruct" + i + ");\n");
629                         }
630                 }
631         }
632
633
634         /**
635          * HELPER: isStructPresent() checks presence of struct
636          */
637         private boolean isStructPresent(List<String> methParams, List<String> methPrmTypes) {
638
639                 // Iterate and find enum declarations
640                 for (int i = 0; i < methParams.size(); i++) {
641                         String paramType = methPrmTypes.get(i);
642                         String param = methParams.get(i);
643                         String simpleType = getSimpleType(paramType);
644                         if (isStructClass(simpleType))
645                                 return true;
646                 }
647                 return false;
648         }
649
650
651         /**
652          * HELPER: writeLengthStructParamClassJavaStub() writes lengths of params
653          */
654         private void writeLengthStructParamClassJavaStub(List<String> methParams, List<String> methPrmTypes) {
655
656                 // Iterate and find struct declarations - count number of params
657                 for (int i = 0; i < methParams.size(); i++) {
658                         String paramType = methPrmTypes.get(i);
659                         String param = methParams.get(i);
660                         String simpleType = getGenericType(paramType);
661                         if (isStructClass(simpleType)) {
662                                 int members = getNumOfMembers(simpleType);
663                                 if (isArray(param)) {                   // An array
664                                         String structLen = param + ".length";
665                                         print(members + "*" + structLen);
666                                 } else if (isList(paramType)) { // A list
667                                         String structLen = param + ".size()";
668                                         print(members + "*" + structLen);
669                                 } else
670                                         print(Integer.toString(members));
671                         } else
672                                 print("1");
673                         if (i != methParams.size() - 1) {
674                                 print("+");
675                         }
676                 }
677         }
678
679
680         /**
681          * HELPER: writeStructMembersJavaStub() writes parameters of struct
682          */
683         private void writeStructMembersJavaStub(String simpleType, String paramType, String param) {
684
685                 // Get the struct declaration for this struct and generate initialization code
686                 StructDecl structDecl = getStructDecl(simpleType);
687                 List<String> memTypes = structDecl.getMemberTypes(simpleType);
688                 List<String> members = structDecl.getMembers(simpleType);
689                 if (isArray(param)) {                   // An array
690                         println("for(int i = 0; i < " + param + ".length; i++) {");
691                 } else if (isList(paramType)) { // A list
692                         println("for(int i = 0; i < " + param + ".size(); i++) {");
693                 }
694                 if (isArrayOrList(param, paramType)) {  // An array or list
695                         for (int i = 0; i < members.size(); i++) {
696                                 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
697                                 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
698                                 print("paramObj[pos++] = " + param + "[i].");
699                                 print(getSimpleIdentifier(members.get(i)));
700                                 println(";");
701                         }
702                         println("}");
703                 } else {        // Just one struct element
704                         for (int i = 0; i < members.size(); i++) {
705                                 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
706                                 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
707                                 print("paramObj[pos++] = " + param + ".");
708                                 print(getSimpleIdentifier(members.get(i)));
709                                 println(";");
710                         }
711                 }
712         }
713
714
715         /**
716          * HELPER: writeStructParamClassJavaStub() writes parameters if struct is present
717          */
718         private void writeStructParamClassJavaStub(List<String> methParams, List<String> methPrmTypes) {
719
720                 print("int paramLen = ");
721                 writeLengthStructParamClassJavaStub(methParams, methPrmTypes);
722                 println(";");
723                 println("Object[] paramObj = new Object[paramLen];");
724                 println("Class<?>[] paramCls = new Class<?>[paramLen];");
725                 println("int pos = 0;");
726                 // Iterate again over the parameters
727                 for (int i = 0; i < methParams.size(); i++) {
728                         String paramType = methPrmTypes.get(i);
729                         String param = methParams.get(i);
730                         String simpleType = getGenericType(paramType);
731                         if (isStructClass(simpleType)) {
732                                 writeStructMembersJavaStub(simpleType, paramType, param);
733                         } else {
734                                 String prmType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
735                                 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
736                                 print("paramObj[pos++] = ");
737                                 print(getEnumParam(methPrmTypes.get(i), getSimpleIdentifier(methParams.get(i)), i));
738                                 println(";");
739                         }
740                 }
741                 
742         }
743
744
745         /**
746          * HELPER: writeStructRetMembersJavaStub() writes parameters of struct
747          */
748         private void writeStructRetMembersJavaStub(String simpleType, String retType) {
749
750                 // Get the struct declaration for this struct and generate initialization code
751                 StructDecl structDecl = getStructDecl(simpleType);
752                 List<String> memTypes = structDecl.getMemberTypes(simpleType);
753                 List<String> members = structDecl.getMembers(simpleType);
754                 if (isArrayOrList(retType, retType)) {  // An array or list
755                         println("for(int i = 0; i < retLen; i++) {");
756                 }
757                 if (isArray(retType)) { // An array
758                         for (int i = 0; i < members.size(); i++) {
759                                 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
760                                 print("structRet[i]." + getSimpleIdentifier(members.get(i)));
761                                 println(" = (" + getSimpleType(getEnumType(prmType)) + ") retObj[retObjPos++];");
762                         }
763                         println("}");
764                 } else if (isList(retType)) {   // A list
765                         println(simpleType + " structRetMem = new " + simpleType + "();");
766                         for (int i = 0; i < members.size(); i++) {
767                                 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
768                                 print("structRetMem." + getSimpleIdentifier(members.get(i)));
769                                 println(" = (" + getSimpleType(getEnumType(prmType)) + ") retObj[retObjPos++];");
770                         }
771                         println("structRet.add(structRetMem);");
772                         println("}");
773                 } else {        // Just one struct element
774                         for (int i = 0; i < members.size(); i++) {
775                                 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
776                                 print("structRet." + getSimpleIdentifier(members.get(i)));
777                                 println(" = (" + getSimpleType(getEnumType(prmType)) + ") retObj[retObjPos++];");
778                         }
779                 }
780                 println("return structRet;");
781         }
782
783
784         /**
785          * HELPER: writeStructReturnJavaStub() writes parameters if struct is present
786          */
787         private void writeStructReturnJavaStub(String simpleType, String retType) {
788
789                 // Handle the returned struct!!!
790                 println("Object retLenObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
791                 // Minimum retLen is 1 if this is a single struct object
792                 println("int retLen = (int) retLenObj;");
793                 int numMem = getNumOfMembers(simpleType);
794                 println("Class<?>[] retCls = new Class<?>[" + numMem + "*retLen];");
795                 println("Class<?>[] retClsVal = new Class<?>[" + numMem + "*retLen];");
796                 println("int retPos = 0;");
797                 // Get the struct declaration for this struct and generate initialization code
798                 StructDecl structDecl = getStructDecl(simpleType);
799                 List<String> memTypes = structDecl.getMemberTypes(simpleType);
800                 List<String> members = structDecl.getMembers(simpleType);
801                 if (isArrayOrList(retType, retType)) {  // An array or list
802                         println("for(int i = 0; i < retLen; i++) {");
803                         for (int i = 0; i < members.size(); i++) {
804                                 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
805                                 println("retCls[retPos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
806                                 println("retClsVal[retPos++] = null;");
807                         }
808                         println("}");
809                 } else {        // Just one struct element
810                         for (int i = 0; i < members.size(); i++) {
811                                 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
812                                 println("retCls[retPos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
813                                 println("retClsVal[retPos++] = null;");
814                         }
815                 }
816                 println("Object[] retObj = rmiCall.getStructObjects(retCls, retClsVal);");
817                 if (isArray(retType)) {                 // An array
818                         println(simpleType + "[] structRet = new " + simpleType + "[retLen];");
819                         println("for(int i = 0; i < retLen; i++) {");
820                         println("structRet[i] = new " + simpleType + "();");
821                         println("}");
822                 } else if (isList(retType)) {   // A list
823                         println("List<" + simpleType + "> structRet = new ArrayList<" + simpleType + ">();");
824                 } else
825                         println(simpleType + " structRet = new " + simpleType + "();");
826                 println("int retObjPos = 0;");
827                 writeStructRetMembersJavaStub(simpleType, retType);
828         }
829
830
831         /**
832          * HELPER: writeStdMethodBodyJavaStub() writes the standard method body in the stub class
833          */
834         private void writeStdMethodBodyJavaStub(InterfaceDecl intDecl, List<String> methParams,
835                         List<String> methPrmTypes, String method) {
836
837                 checkAndWriteStructSetupJavaStub(methParams, methPrmTypes, intDecl, method);
838                 println("int methodId = " + intDecl.getMethodNumId(method) + ";");
839                 String retType = intDecl.getMethodType(method);
840                 println("Class<?> retType = " + getSimpleType(getStructType(getEnumType(retType))) + ".class;");
841                 checkAndWriteEnumTypeJavaStub(methParams, methPrmTypes);
842                 // Generate array of parameter types
843                 if (isStructPresent(methParams, methPrmTypes)) {
844                         writeStructParamClassJavaStub(methParams, methPrmTypes);
845                 } else {
846                         print("Class<?>[] paramCls = new Class<?>[] { ");
847                         for (int i = 0; i < methParams.size(); i++) {
848                                 String paramType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
849                                 print(getSimpleType(getEnumType(paramType)) + ".class");
850                                 // Check if this is the last element (don't print a comma)
851                                 if (i != methParams.size() - 1) {
852                                         print(", ");
853                                 }
854                         }
855                         println(" };");
856                         // Generate array of parameter objects
857                         print("Object[] paramObj = new Object[] { ");
858                         for (int i = 0; i < methParams.size(); i++) {
859                                 print(getEnumParam(methPrmTypes.get(i), getSimpleIdentifier(methParams.get(i)), i));
860                                 // Check if this is the last element (don't print a comma)
861                                 if (i != methParams.size() - 1) {
862                                         print(", ");
863                                 }
864                         }
865                         println(" };");
866                 }
867                 // Check if this is "void"
868                 if (retType.equals("void")) {
869                         println("rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
870                 } else { // We do have a return value
871                         // Generate array of parameter types
872                         if (isStructClass(getGenericType(getSimpleArrayType(retType)))) {
873                                 writeStructReturnJavaStub(getGenericType(getSimpleArrayType(retType)), retType);
874                         } else {
875                         // Check if the return value NONPRIMITIVES
876                                 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES) {
877                                         String[] retGenValType = getTypeOfGeneric(retType);
878                                         println("Class<?> retGenValType = " + retGenValType[0] + ".class;");
879                                         println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, retGenValType, paramCls, paramObj);");
880                                         println("return (" + retType + ")retObj;");
881                                 } else if (getParamCategory(retType) == ParamCategory.ENUM) {
882                                 // This is an enum type
883                                         println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
884                                         checkAndWriteEnumRetTypeJavaStub(retType);
885                                 } else {
886                                         println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
887                                         println("return (" + retType + ")retObj;");
888                                 }
889                         }
890                 }
891         }
892
893
894         /**
895          * HELPER: returnGenericCallbackType() returns the callback type
896          */
897         private String returnGenericCallbackType(String paramType) {
898
899                 if (getParamCategory(paramType) == ParamCategory.NONPRIMITIVES)
900                         return getTypeOfGeneric(paramType)[0];
901                 else
902                         return paramType;
903         }
904
905
906         /**
907          * HELPER: checkCallbackType() checks the callback type
908          */
909         private boolean checkCallbackType(String paramType, String callbackType) {
910
911                 String prmType = returnGenericCallbackType(paramType);
912                 return callbackType.equals(prmType);
913         }
914
915
916         /**
917          * HELPER: writeCallbackMethodBodyJavaStub() writes the callback method of the stub class
918          */
919         private void writeCallbackMethodBodyJavaStub(InterfaceDecl intDecl, List<String> methParams,
920                         List<String> methPrmTypes, String method, String callbackType) {
921
922                 println("try {");
923                 // Check if this is single object, array, or list of objects
924                 for (int i = 0; i < methParams.size(); i++) {
925
926                         String paramType = methPrmTypes.get(i);
927                         if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
928                                 String param = methParams.get(i);
929                                 if (isArrayOrList(paramType, param)) {  // Generate loop
930                                         println("for (" + paramType + " cb : " + getSimpleIdentifier(param) + ") {");
931                                         println(callbackType + "_CallbackSkeleton skel = new " + callbackType + "_CallbackSkeleton(cb, objIdCnt++);");
932                                 } else
933                                         println(callbackType + "_CallbackSkeleton skel = new " + callbackType + "_CallbackSkeleton(" +
934                                                 getSimpleIdentifier(param) + ", objIdCnt++);");
935                                 println("listCallbackObj.add(skel);");
936                                 if (isArrayOrList(paramType, param))
937                                         println("}");
938                         }
939                 }
940                 println("} catch (Exception ex) {");
941                 println("ex.printStackTrace();");
942                 println("throw new Error(\"Exception when generating skeleton objects!\");");
943                 println("}\n");
944                 println("int methodId = " + intDecl.getMethodNumId(method) + ";");
945                 String retType = intDecl.getMethodType(method);
946                 println("Class<?> retType = " + getSimpleType(getEnumType(retType)) + ".class;");
947                 // Generate array of parameter types
948                 print("Class<?>[] paramCls = new Class<?>[] { ");
949                 for (int i = 0; i < methParams.size(); i++) {
950                         String paramType = methPrmTypes.get(i);
951                         if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
952                                 print("int.class");
953                         } else { // Generate normal classes if it's not a callback object
954                                 String prmType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
955                                 print(getSimpleType(prmType) + ".class");
956                         }
957                         if (i != methParams.size() - 1) // Check if this is the last element
958                                 print(", ");
959                 }
960                 println(" };");
961                 // Generate array of parameter objects
962                 print("Object[] paramObj = new Object[] { ");
963                 for (int i = 0; i < methParams.size(); i++) {
964                         String paramType = methPrmTypes.get(i);
965                         if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
966                                 //if (isArray(methPrmTypes.get(i), methParams.get(i)))
967                                 if (isArray(methParams.get(i)))
968                                         print(getSimpleIdentifier(methParams.get(i)) + ".length");
969                                 else if (isList(methPrmTypes.get(i)))
970                                         print(getSimpleIdentifier(methParams.get(i)) + ".size()");
971                                 else
972                                         print("new Integer(1)");
973                         } else
974                                 print(getSimpleIdentifier(methParams.get(i)));
975                         if (i != methParams.size() - 1)
976                                 print(", ");
977                 }
978                 println(" };");
979                 // Check if this is "void"
980                 if (retType.equals("void")) {
981                         println("rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
982                 } else { // We do have a return value
983                 // Check if the return value NONPRIMITIVES
984                         if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES) {
985                                 String[] retGenValType = getTypeOfGeneric(retType);
986                                 println("Class<?> retGenValType = " + retGenValType[0] + ".class;");
987                                 println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, retGenValType, paramCls, paramObj);");
988                                 println("return (" + retType + ")retObj;");
989                         } else {
990                                 println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
991                                 println("return (" + retType + ")retObj;");
992                         }
993                 }
994         }
995
996
997         /**
998          * HELPER: writeMethodJavaStub() writes the method of the stub class
999          */
1000         private void writeMethodJavaStub(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
1001
1002                 for (String method : methods) {
1003
1004                         List<String> methParams = intDecl.getMethodParams(method);
1005                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1006                         print("public " + intDecl.getMethodType(method) + " " +
1007                                 intDecl.getMethodId(method) + "(");
1008                         boolean isCallbackMethod = false;
1009                         String callbackType = null;
1010                         for (int i = 0; i < methParams.size(); i++) {
1011
1012                                 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
1013                                 // Check if this has callback object
1014                                 if (callbackClasses.contains(paramType)) {
1015                                         isCallbackMethod = true;
1016                                         callbackType = paramType;       
1017                                         // Even if there're 2 callback arguments, we expect them to be of the same interface
1018                                 }
1019                                 print(methPrmTypes.get(i) + " " + methParams.get(i));
1020                                 // Check if this is the last element (don't print a comma)
1021                                 if (i != methParams.size() - 1) {
1022                                         print(", ");
1023                                 }
1024                         }
1025                         println(") {");
1026                         // Now, write the body of stub!
1027                         if (isCallbackMethod)
1028                                 writeCallbackMethodBodyJavaStub(intDecl, methParams, methPrmTypes, method, callbackType);
1029                         else
1030                                 writeStdMethodBodyJavaStub(intDecl, methParams, methPrmTypes, method);
1031                         println("}\n");
1032                         // Write the init callback helper method
1033                         if (isCallbackMethod)
1034                                 writeInitCallbackJavaStub(callbackType, intDecl);
1035                 }
1036         }
1037
1038
1039         /**
1040          * generateJavaStubClasses() generate stubs based on the methods list in Java
1041          */
1042         public void generateJavaStubClasses() throws IOException {
1043
1044                 // Create a new directory
1045                 String path = createDirectories(dir, subdir);
1046                 for (String intface : mapIntfacePTH.keySet()) {
1047
1048                         Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
1049                         for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
1050
1051                                 // Open a new file to write into
1052                                 String newIntface = intMeth.getKey();
1053                                 String newStubClass = newIntface + "_Stub";
1054                                 FileWriter fw = new FileWriter(path + "/" + newStubClass + ".java");
1055                                 pw = new PrintWriter(new BufferedWriter(fw));
1056                                 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
1057                                 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
1058                                 // Pass in set of methods and get import classes
1059                                 Set<String> methods = intMeth.getValue();
1060                                 Set<String> importClasses = getImportClasses(methods, intDecl);
1061                                 List<String> stdImportClasses = getStandardJavaImportClasses();
1062                                 List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
1063                                 printImportStatements(allImportClasses); println("");
1064                                 // Find out if there are callback objects
1065                                 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
1066                                 boolean callbackExist = !callbackClasses.isEmpty();
1067                                 // Write class header
1068                                 println("public class " + newStubClass + " implements " + newIntface + " {\n");
1069                                 // Write properties
1070                                 writePropertiesJavaStub(intface, newIntface, callbackExist, callbackClasses);
1071                                 // Write constructor
1072                                 writeConstructorJavaStub(intface, newStubClass, callbackExist, callbackClasses);
1073                                 // Write methods
1074                                 writeMethodJavaStub(intMeth.getValue(), intDecl, callbackClasses);
1075                                 println("}");
1076                                 pw.close();
1077                                 System.out.println("IoTCompiler: Generated stub class " + newStubClass + ".java...");
1078                         }
1079                 }
1080         }
1081
1082
1083         /**
1084          * HELPER: writePropertiesJavaCallbackStub() writes the properties of the callback stub class
1085          */
1086         private void writePropertiesJavaCallbackStub(String intface, String newIntface, boolean callbackExist, Set<String> callbackClasses) {
1087
1088                 println("private IoTRMICall rmiCall;");
1089                 println("private String address;");
1090                 println("private int[] ports;\n");
1091                 // Get the object Id
1092                 println("private static int objectId = 0;");
1093                 if (callbackExist) {
1094                 // We assume that each class only has one callback interface for now
1095                         Iterator it = callbackClasses.iterator();
1096                         String callbackType = (String) it.next();
1097                         println("// Callback properties");
1098                         println("private IoTRMIObject rmiObj;");
1099                         println("List<" + callbackType + "> listCallbackObj;");
1100                         println("private static int objIdCnt = 0;");
1101                         // Generate permission stuff for callback stubs
1102                         DeclarationHandler decHandler = mapIntDeclHand.get(callbackType);
1103                         InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(callbackType);
1104                         writePropertiesJavaPermission(callbackType, intDecl);
1105                 }
1106                 println("\n");
1107         }
1108
1109
1110         /**
1111          * HELPER: writeConstructorJavaCallbackStub() writes the constructor of the callback stub class
1112          */
1113         private void writeConstructorJavaCallbackStub(String intface, String newStubClass, boolean callbackExist, Set<String> callbackClasses) {
1114
1115                 // TODO: If we want callback in callback, then we need to add address and port initializations
1116                 println("public " + newStubClass + "(IoTRMICall _rmiCall, int _objectId) throws Exception {");
1117                 println("objectId = _objectId;");
1118                 println("rmiCall = _rmiCall;");
1119                 if (callbackExist) {
1120                         Iterator it = callbackClasses.iterator();
1121                         String callbackType = (String) it.next();
1122                         writeConstructorJavaPermission(intface);
1123                         println("listCallbackObj = new ArrayList<" + callbackType + ">();");
1124                         println("___initCallBack();");
1125                         println("// TODO: Add address and port initialization here if we want callback in callback!");
1126                 }
1127                 println("}\n");
1128         }
1129
1130
1131         /**
1132          * generateJavaCallbackStubClasses() generate callback stubs based on the methods list in Java
1133          * <p>
1134          * Callback stubs gets the IoTRMICall objects from outside of the class as contructor input
1135          * because all these stubs are populated by the class that takes in this object as a callback
1136          * object. In such a class, we only use one socket, hence one IoTRMICall, for all callback objects.
1137          */
1138         public void generateJavaCallbackStubClasses() throws IOException {
1139
1140                 // Create a new directory
1141                 String path = createDirectories(dir, subdir);
1142                 for (String intface : mapIntfacePTH.keySet()) {
1143
1144                         Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
1145                         for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
1146
1147                                 // Open a new file to write into
1148                                 String newIntface = intMeth.getKey();
1149                                 String newStubClass = newIntface + "_CallbackStub";
1150                                 FileWriter fw = new FileWriter(path + "/" + newStubClass + ".java");
1151                                 pw = new PrintWriter(new BufferedWriter(fw));
1152                                 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
1153                                 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
1154                                 // Pass in set of methods and get import classes
1155                                 Set<String> methods = intMeth.getValue();
1156                                 Set<String> importClasses = getImportClasses(methods, intDecl);
1157                                 List<String> stdImportClasses = getStandardJavaImportClasses();
1158                                 List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
1159                                 printImportStatements(allImportClasses); println("");
1160                                 // Find out if there are callback objects
1161                                 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
1162                                 boolean callbackExist = !callbackClasses.isEmpty();
1163                                 // Write class header
1164                                 println("public class " + newStubClass + " implements " + newIntface + " {\n");
1165                                 // Write properties
1166                                 writePropertiesJavaCallbackStub(intface, newIntface, callbackExist, callbackClasses);
1167                                 // Write constructor
1168                                 writeConstructorJavaCallbackStub(intface, newStubClass, callbackExist, callbackClasses);
1169                                 // Write methods
1170                                 // TODO: perhaps need to generate callback for callback
1171                                 writeMethodJavaStub(intMeth.getValue(), intDecl, callbackClasses);
1172                                 println("}");
1173                                 pw.close();
1174                                 System.out.println("IoTCompiler: Generated callback stub class " + newStubClass + ".java...");
1175                         }
1176                 }
1177         }
1178
1179
1180         /**
1181          * HELPER: writePropertiesJavaSkeleton() writes the properties of the skeleton class
1182          */
1183         private void writePropertiesJavaSkeleton(String intface, boolean callbackExist, InterfaceDecl intDecl) {
1184
1185                 println("private " + intface + " mainObj;");
1186                 //println("private int ports;");
1187                 println("private IoTRMIObject rmiObj;\n");
1188                 // Callback
1189                 if (callbackExist) {
1190                         println("private static int objIdCnt = 0;");
1191                         println("private IoTRMICall rmiCall;");
1192                 }
1193                 writePropertiesJavaPermission(intface, intDecl);
1194                 println("\n");
1195         }
1196
1197
1198         /**
1199          * HELPER: writeConstructorJavaSkeleton() writes the constructor of the skeleton class
1200          */
1201         private void writeConstructorJavaSkeleton(String newSkelClass, String intface) {
1202
1203                 println("public " + newSkelClass + "(" + intface + " _mainObj, int _port) throws Exception {");
1204                 println("mainObj = _mainObj;");
1205                 println("rmiObj = new IoTRMIObject(_port);");
1206                 // Generate permission control initialization
1207                 writeConstructorJavaPermission(intface);
1208                 println("___waitRequestInvokeMethod();");
1209                 println("}\n");
1210         }
1211
1212
1213         /**
1214          * HELPER: writeStdMethodBodyJavaSkeleton() writes the standard method body in the skeleton class
1215          */
1216         private void writeStdMethodBodyJavaSkeleton(List<String> methParams, String methodId, String methodType) {
1217
1218                 if (methodType.equals("void"))
1219                         print("mainObj." + methodId + "(");
1220                 else
1221                         print("return mainObj." + methodId + "(");
1222                 for (int i = 0; i < methParams.size(); i++) {
1223
1224                         print(getSimpleIdentifier(methParams.get(i)));
1225                         // Check if this is the last element (don't print a comma)
1226                         if (i != methParams.size() - 1) {
1227                                 print(", ");
1228                         }
1229                 }
1230                 println(");");
1231         }
1232
1233
1234         /**
1235          * HELPER: writeInitCallbackJavaSkeleton() writes the init callback method for skeleton class
1236          */
1237         private void writeInitCallbackJavaSkeleton(boolean callbackSkeleton) {
1238
1239                 // This is a callback skeleton generation
1240                 if (callbackSkeleton)
1241                         println("public void ___regCB(IoTRMIObject rmiObj) throws IOException {");
1242                 else
1243                         println("public void ___regCB() throws IOException {");
1244                 println("Object[] paramObj = rmiObj.getMethodParams(new Class<?>[] { int.class, String.class, int.class },");
1245                 println("\tnew Class<?>[] { null, null, null });");
1246                 println("rmiCall = new IoTRMICall((int) paramObj[0], (String) paramObj[1], (int) paramObj[2]);");
1247                 println("}\n");
1248         }
1249
1250
1251         /**
1252          * HELPER: writeMethodJavaSkeleton() writes the method of the skeleton class
1253          */
1254         private void writeMethodJavaSkeleton(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses, 
1255                         boolean callbackSkeleton) {
1256
1257                 for (String method : methods) {
1258
1259                         List<String> methParams = intDecl.getMethodParams(method);
1260                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1261                         String methodId = intDecl.getMethodId(method);
1262                         print("public " + intDecl.getMethodType(method) + " " + methodId + "(");
1263                         boolean isCallbackMethod = false;
1264                         String callbackType = null;
1265                         for (int i = 0; i < methParams.size(); i++) {
1266
1267                                 String origParamType = methPrmTypes.get(i);
1268                                 String paramType = checkAndGetParamClass(origParamType);
1269                                 if (callbackClasses.contains(origParamType)) { // Check if this has callback object
1270                                         isCallbackMethod = true;
1271                                         callbackType = origParamType;   
1272                                 }
1273                                 print(paramType + " " + methParams.get(i));
1274                                 // Check if this is the last element (don't print a comma)
1275                                 if (i != methParams.size() - 1) {
1276                                         print(", ");
1277                                 }
1278                         }
1279                         println(") {");
1280                         // Now, write the body of skeleton!
1281                         writeStdMethodBodyJavaSkeleton(methParams, methodId, intDecl.getMethodType(method));
1282                         println("}\n");
1283                         if (isCallbackMethod)
1284                                 writeInitCallbackJavaSkeleton(callbackSkeleton);
1285                 }
1286         }
1287
1288
1289         /**
1290          * HELPER: writeCallbackJavaStubGeneration() writes the callback stub generation part
1291          */
1292         private Map<Integer,String> writeCallbackJavaStubGeneration(List<String> methParams, List<String> methPrmTypes, String callbackType) {
1293
1294                 Map<Integer,String> mapStubParam = new HashMap<Integer,String>();
1295                 // Iterate over callback objects
1296                 for (int i = 0; i < methParams.size(); i++) {
1297                         String paramType = methPrmTypes.get(i);
1298                         String param = methParams.get(i);
1299                         //if (callbackType.equals(paramType)) {
1300                         if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
1301                                 println("try {");
1302                                 String exchParamType = checkAndGetParamClass(paramType);
1303                                 // Print array if this is array or list if this is a list of callback objects
1304                                 if (isArray(param)) {
1305                                         println("int numStubs" + i + " = (int) paramObj[" + i + "];");
1306                                         println(exchParamType + "[] stub" + i + " = new " + exchParamType + "[numStubs" + i + "];");
1307                                 } else if (isList(paramType)) {
1308                                         println("int numStubs" + i + " = (int) paramObj[" + i + "];");
1309                                         println("List<" + exchParamType + "> stub" + i + " = new ArrayList<" + exchParamType + ">();");
1310                                 } else {
1311                                         println(exchParamType + " stub" + i + " = new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt);");
1312                                         println("objIdCnt++;");
1313                                 }
1314                         }
1315                         // Generate a loop if needed
1316                         if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
1317                                 String exchParamType = checkAndGetParamClass(paramType);
1318                                 if (isArray(param)) {
1319                                         println("for (int objId = 0; objId < numStubs" + i + "; objId++) {");
1320                                         println("stub" + i + "[objId] = new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt);");
1321                                         println("objIdCnt++;");
1322                                         println("}");
1323                                 } else if (isList(paramType)) {
1324                                         println("for (int objId = 0; objId < numStubs" + i + "; objId++) {");
1325                                         println("stub" + i + ".add(new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt));");
1326                                         println("objIdCnt++;");
1327                                         println("}");
1328                                 }
1329                                 mapStubParam.put(i, "stub" + i);        // List of all stub parameters
1330                         }
1331                 }
1332                 return mapStubParam;
1333         }
1334
1335
1336         /**
1337          * HELPER: checkAndWriteEnumTypeJavaSkeleton() writes the enum type (convert from enum to int)
1338          */
1339         private void checkAndWriteEnumTypeJavaSkeleton(List<String> methParams, List<String> methPrmTypes) {
1340
1341                 // Iterate and find enum declarations
1342                 for (int i = 0; i < methParams.size(); i++) {
1343                         String paramType = methPrmTypes.get(i);
1344                         String param = methParams.get(i);
1345                         String simpleType = getSimpleType(paramType);
1346                         if (isEnumClass(simpleType)) {
1347                         // Check if this is enum type
1348                                 println("int paramInt" + i + "[] = (int[]) paramObj[" + i + "];");
1349                                 println(simpleType + "[] enumVals = " + simpleType + ".values();");
1350                                 if (isArray(param)) {   // An array
1351                                         println("int len" + i + " = paramInt" + i + ".length;");
1352                                         println(simpleType + "[] paramEnum = new " + simpleType + "[len];");
1353                                         println("for (int i = 0; i < len" + i + "; i++) {");
1354                                         println("paramEnum[i] = enumVals[paramInt" + i + "[i]];");
1355                                         println("}");
1356                                 } else if (isList(paramType)) { // A list
1357                                         println("int len" + i + " = paramInt" + i + ".length;");
1358                                         println("List<" + simpleType + "> paramEnum = new ArrayList<" + simpleType + ">();");
1359                                         println("for (int i = 0; i < len" + i + "; i++) {");
1360                                         println("paramEnum.add(enumVals[paramInt" + i + "[i]]);");
1361                                         println("}");
1362                                 } else {        // Just one element
1363                                         println(simpleType + " paramEnum" + i + " = enumVals[paramInt" + i + "[0]];");
1364                                 }
1365                         }
1366                 }
1367         }
1368
1369
1370         /**
1371          * HELPER: checkAndWriteEnumRetTypeJavaSkeleton() writes the enum return type (convert from enum to int)
1372          */
1373         private void checkAndWriteEnumRetTypeJavaSkeleton(String retType, String methodId) {
1374
1375                 // Strips off array "[]" for return type
1376                 String pureType = getSimpleArrayType(getSimpleType(retType));
1377                 // Take the inner type of generic
1378                 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
1379                         pureType = getTypeOfGeneric(retType)[0];
1380                 if (isEnumClass(pureType)) {
1381                 // Check if this is enum type
1382                         // Enum decoder
1383                         if (isArray(retType)) {                 // An array
1384                                 print(pureType + "[] retEnum = " + methodId + "(");
1385                         } else if (isList(retType)) {   // A list
1386                                 print("List<" + pureType + "> retEnum = " + methodId + "(");
1387                         } else {        // Just one element
1388                                 print(pureType + " retEnum = " + methodId + "(");
1389                         }
1390                 }
1391         }
1392
1393
1394         /**
1395          * HELPER: checkAndWriteEnumRetConvJavaSkeleton() writes the enum return type (convert from enum to int)
1396          */
1397         private void checkAndWriteEnumRetConvJavaSkeleton(String retType) {
1398
1399                 // Strips off array "[]" for return type
1400                 String pureType = getSimpleArrayType(getSimpleType(retType));
1401                 // Take the inner type of generic
1402                 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
1403                         pureType = getTypeOfGeneric(retType)[0];
1404                 if (isEnumClass(pureType)) {
1405                 // Check if this is enum type
1406                         if (isArray(retType)) { // An array
1407                                 println("int retLen = retEnum.length;");
1408                                 println("int[] retEnumVal = new int[retLen];");
1409                                 println("for (int i = 0; i < retLen; i++) {");
1410                                 println("retEnumVal[i] = retEnum[i].ordinal();");
1411                                 println("}");
1412                         } else if (isList(retType)) {   // A list
1413                                 println("int retLen = retEnum.size();");
1414                                 println("List<" + pureType + "> retEnumVal = new ArrayList<" + pureType + ">();");
1415                                 println("for (int i = 0; i < retLen; i++) {");
1416                                 println("retEnumVal.add(retEnum[i].ordinal());");
1417                                 println("}");
1418                         } else {        // Just one element
1419                                 println("int[] retEnumVal = new int[1];");
1420                                 println("retEnumVal[0] = retEnum.ordinal();");
1421                         }
1422                         println("Object retObj = retEnumVal;");
1423                 }
1424         }
1425         
1426         
1427         /**
1428          * HELPER: writeLengthStructParamClassSkeleton() writes lengths of params
1429          */
1430         private void writeLengthStructParamClassSkeleton(List<String> methParams, List<String> methPrmTypes, 
1431                         String method, InterfaceDecl intDecl) {
1432
1433                 // Iterate and find struct declarations - count number of params
1434                 for (int i = 0; i < methParams.size(); i++) {
1435                         String paramType = methPrmTypes.get(i);
1436                         String param = methParams.get(i);
1437                         String simpleType = getGenericType(paramType);
1438                         if (isStructClass(simpleType)) {
1439                                 int members = getNumOfMembers(simpleType);
1440                                 print(Integer.toString(members) + "*");
1441                                 int methodNumId = intDecl.getMethodNumId(method);
1442                                 print("struct" + methodNumId + "Size" + i);
1443                         } else
1444                                 print("1");
1445                         if (i != methParams.size() - 1) {
1446                                 print("+");
1447                         }
1448                 }
1449         }
1450
1451         
1452         /**
1453          * HELPER: writeStructMembersJavaSkeleton() writes parameters of struct
1454          */
1455         private void writeStructMembersJavaSkeleton(String simpleType, String paramType, 
1456                         String param, String method, InterfaceDecl intDecl, int iVar) {
1457
1458                 // Get the struct declaration for this struct and generate initialization code
1459                 StructDecl structDecl = getStructDecl(simpleType);
1460                 List<String> memTypes = structDecl.getMemberTypes(simpleType);
1461                 List<String> members = structDecl.getMembers(simpleType);
1462                 if (isArrayOrList(param, paramType)) {  // An array or list
1463                         int methodNumId = intDecl.getMethodNumId(method);
1464                         String counter = "struct" + methodNumId + "Size" + iVar;
1465                         println("for(int i = 0; i < " + counter + "; i++) {");
1466                 }
1467                 println("int pos = 0;");
1468                 if (isArrayOrList(param, paramType)) {  // An array or list
1469                         println("for(int i = 0; i < retLen; i++) {");
1470                         for (int i = 0; i < members.size(); i++) {
1471                                 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
1472                                 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
1473                                 println("paramClsGen[pos++] = null;");
1474                         }
1475                         println("}");
1476                 } else {        // Just one struct element
1477                         for (int i = 0; i < members.size(); i++) {
1478                                 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
1479                                 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
1480                                 println("paramClsGen[pos++] = null;");
1481                         }
1482                 }
1483         }
1484
1485
1486
1487         /**
1488          * HELPER: writeStructMembersInitJavaSkeleton() writes parameters of struct
1489          */
1490         private void writeStructMembersInitJavaSkeleton(InterfaceDecl intDecl, List<String> methParams,
1491                         List<String> methPrmTypes, String method) {
1492
1493                 for (int i = 0; i < methParams.size(); i++) {
1494                         String paramType = methPrmTypes.get(i);
1495                         String param = methParams.get(i);
1496                         String simpleType = getGenericType(paramType);
1497                         if (isStructClass(simpleType)) {
1498                                 int methodNumId = intDecl.getMethodNumId(method);
1499                                 String counter = "struct" + methodNumId + "Size" + i;
1500                                 // Declaration
1501                                 if (isArray(param)) {                   // An array
1502                                         println(simpleType + "[] paramStruct" + i + " = new " + simpleType + "[" + counter + "];");
1503                                         println("for(int i = 0; i < " + counter + "; i++) {");
1504                                         println("paramStruct" + i + "[i] = new " + simpleType + "();");
1505                                         println("}");
1506                                 } else if (isList(paramType)) { // A list
1507                                         println("List<" + simpleType + "> paramStruct" + i + " = new ArrayList<" + simpleType + ">();");
1508                                 } else
1509                                         println(simpleType + " paramStruct" + i + " = new " + simpleType + "();");
1510                                 println("int objPos = 0;");
1511                                 // Initialize members
1512                                 StructDecl structDecl = getStructDecl(simpleType);
1513                                 List<String> members = structDecl.getMembers(simpleType);
1514                                 List<String> memTypes = structDecl.getMemberTypes(simpleType);
1515                                 if (isArrayOrList(param, paramType)) {  // An array or list
1516                                         println("for(int i = 0; i < " + counter + "; i++) {");
1517                                 }
1518                                 if (isArray(param)) {   // An array
1519                                         for (int j = 0; j < members.size(); j++) {
1520                                                 String prmType = checkAndGetArray(memTypes.get(j), members.get(j));
1521                                                 print("paramStruct" + i + "[i]." + getSimpleIdentifier(members.get(j)));
1522                                                 println(" = (" + getSimpleType(getEnumType(prmType)) + ") paramObj[objPos++];");
1523                                         }
1524                                         println("}");
1525                                 } else if (isList(paramType)) { // A list
1526                                         println(simpleType + " paramStructMem = new " + simpleType + "();");
1527                                         for (int j = 0; j < members.size(); j++) {
1528                                                 String prmType = checkAndGetArray(memTypes.get(j), members.get(j));
1529                                                 print("paramStructMem." + getSimpleIdentifier(members.get(j)));
1530                                                 println(" = (" + getSimpleType(getEnumType(prmType)) + ") paramObj[objPos++];");
1531                                         }
1532                                         println("paramStruct" + i + ".add(paramStructMem);");
1533                                         println("}");
1534                                 } else {        // Just one struct element
1535                                         for (int j = 0; j < members.size(); j++) {
1536                                                 String prmType = checkAndGetArray(memTypes.get(j), members.get(j));
1537                                                 print("paramStruct" + i + "." + getSimpleIdentifier(members.get(j)));
1538                                                 println(" = (" + getSimpleType(getEnumType(prmType)) + ") paramObj[objPos++];");
1539                                         }
1540                                 }
1541                         } else {
1542                                 // Take offsets of parameters
1543                                 println("int offset" + i +" = objPos;");
1544                         }
1545                 }
1546         }
1547
1548
1549         /**
1550          * HELPER: writeStructReturnJavaSkeleton() writes parameters if struct is present
1551          */
1552         private void writeStructReturnJavaSkeleton(String simpleType, String retType) {
1553
1554                 // Minimum retLen is 1 if this is a single struct object
1555                 if (isArray(retType))
1556                         println("int retLen = retStruct.length;");
1557                 else if (isList(retType))
1558                         println("int retLen = retStruct.size();");
1559                 else    // Just single struct object
1560                         println("int retLen = 1;");
1561                 println("Object retLenObj = retLen;");
1562                 println("rmiObj.sendReturnObj(retLenObj);");
1563                 int numMem = getNumOfMembers(simpleType);
1564                 println("Class<?>[] retCls = new Class<?>[" + numMem + "*retLen];");
1565                 println("Object[] retObj = new Object[" + numMem + "*retLen];");
1566                 println("int retPos = 0;");
1567                 // Get the struct declaration for this struct and generate initialization code
1568                 StructDecl structDecl = getStructDecl(simpleType);
1569                 List<String> memTypes = structDecl.getMemberTypes(simpleType);
1570                 List<String> members = structDecl.getMembers(simpleType);
1571                 if (isArrayOrList(retType, retType)) {  // An array or list
1572                         println("for(int i = 0; i < retLen; i++) {");
1573                         for (int i = 0; i < members.size(); i++) {
1574                                 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
1575                                 println("retCls[retPos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
1576                                 print("retObj[retPos++] = retStruct[i].");
1577                                 print(getEnumParam(memTypes.get(i), getSimpleIdentifier(members.get(i)), i));
1578                                 println(";");
1579                         }
1580                         println("}");
1581                 } else {        // Just one struct element
1582                         for (int i = 0; i < members.size(); i++) {
1583                                 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
1584                                 println("retCls[retPos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
1585                                 print("retObj[retPos++] = retStruct.");
1586                                 print(getEnumParam(memTypes.get(i), getSimpleIdentifier(members.get(i)), i));
1587                                 println(";");
1588                         }
1589                 }
1590
1591         }
1592
1593
1594         /**
1595          * HELPER: writeMethodHelperReturnJavaSkeleton() writes the return value part in skeleton
1596          */
1597         private void writeMethodHelperReturnJavaSkeleton(InterfaceDecl intDecl, List<String> methParams,
1598                         List<String> methPrmTypes, String method, boolean isCallbackMethod, String callbackType) {
1599
1600                 checkAndWriteEnumTypeJavaSkeleton(methParams, methPrmTypes);
1601                 Map<Integer,String> mapStubParam = null;
1602                 if (isCallbackMethod)
1603                         mapStubParam = writeCallbackJavaStubGeneration(methParams, methPrmTypes, callbackType);
1604                 // Check if this is "void"
1605                 String retType = intDecl.getMethodType(method);
1606                 if (retType.equals("void")) {
1607                         print(intDecl.getMethodId(method) + "(");
1608                 } else if (isEnumClass(getSimpleArrayType(getSimpleType(retType)))) {   // Enum type
1609                         checkAndWriteEnumRetTypeJavaSkeleton(retType, intDecl.getMethodId(method));
1610                 } else if (isStructClass(getSimpleArrayType(getSimpleType(retType)))) { // Struct type
1611                         print(retType + " retStruct = " + intDecl.getMethodId(method) + "(");
1612                 } else { // We do have a return value
1613                         print("Object retObj = " + intDecl.getMethodId(method) + "(");
1614                 }
1615                 for (int i = 0; i < methParams.size(); i++) {
1616
1617                         if (isCallbackMethod) {
1618                                 print(mapStubParam.get(i));     // Get the callback parameter
1619                         } else if (isEnumClass(getSimpleType(methPrmTypes.get(i)))) { // Enum class
1620                                 print(getEnumParam(methPrmTypes.get(i), methParams.get(i), i));
1621                         } else if (isStructClass(getSimpleType(methPrmTypes.get(i)))) {
1622                                 print("paramStruct" + i);
1623                         } else {
1624                                 String prmType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
1625                                 print("(" + prmType + ") paramObj[offset" + i + "]");
1626                         }
1627                         if (i != methParams.size() - 1)
1628                                 print(", ");
1629                 }
1630                 println(");");
1631                 if (!retType.equals("void")) {
1632                         if (isEnumClass(getSimpleArrayType(getSimpleType(retType)))) { // Enum type
1633                                 checkAndWriteEnumRetConvJavaSkeleton(retType);
1634                                 println("rmiObj.sendReturnObj(retObj);");
1635                         } else if (isStructClass(getSimpleArrayType(getSimpleType(retType)))) { // Struct type
1636                                 writeStructReturnJavaSkeleton(getSimpleArrayType(getSimpleType(retType)), retType);
1637                                 println("rmiObj.sendReturnObj(retCls, retObj);");
1638                         } else
1639                                 println("rmiObj.sendReturnObj(retObj);");
1640                 }
1641                 if (isCallbackMethod) { // Catch exception if this is callback
1642                         println("} catch(Exception ex) {");
1643                         println("ex.printStackTrace();");
1644                         println("throw new Error(\"Exception from callback object instantiation!\");");
1645                         println("}");
1646                 }
1647         }
1648
1649
1650         /**
1651          * HELPER: writeMethodHelperStructJavaSkeleton() writes the struct in skeleton
1652          */
1653         private void writeMethodHelperStructJavaSkeleton(InterfaceDecl intDecl, List<String> methParams,
1654                         List<String> methPrmTypes, String method, Set<String> callbackClasses) {
1655
1656                 // Generate array of parameter objects
1657                 boolean isCallbackMethod = false;
1658                 String callbackType = null;
1659                 print("int paramLen = ");
1660                 writeLengthStructParamClassSkeleton(methParams, methPrmTypes, method, intDecl);
1661                 println(";");
1662                 println("Class<?>[] paramCls = new Class<?>[paramLen];");
1663                 println("Class<?>[] paramClsGen = new Class<?>[paramLen];");
1664                 // Iterate again over the parameters
1665                 for (int i = 0; i < methParams.size(); i++) {
1666                         String paramType = methPrmTypes.get(i);
1667                         String param = methParams.get(i);
1668                         String simpleType = getGenericType(paramType);
1669                         if (isStructClass(simpleType)) {
1670                                 writeStructMembersJavaSkeleton(simpleType, paramType, param, method, intDecl, i);
1671                         } else {
1672                                 String prmType = returnGenericCallbackType(methPrmTypes.get(i));
1673                                 if (callbackClasses.contains(prmType)) {
1674                                         isCallbackMethod = true;
1675                                         callbackType = prmType;
1676                                         println("paramCls[pos] = int.class;");
1677                                         println("paramClsGen[pos++] = null;");
1678                                 } else {        // Generate normal classes if it's not a callback object
1679                                         String paramTypeOth = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
1680                                         println("paramCls[pos] = " + getSimpleType(getEnumType(paramTypeOth)) + ".class;");
1681                                         print("paramClsGen[pos++] = ");
1682                                         String prmTypeOth = methPrmTypes.get(i);
1683                                         if (getParamCategory(prmTypeOth) == ParamCategory.NONPRIMITIVES)
1684                                                 println(getTypeOfGeneric(prmType)[0] + ".class;");
1685                                         else
1686                                                 println("null;");
1687                                 }
1688                         }
1689                 }
1690                 println("Object[] paramObj = rmiObj.getMethodParams(paramCls, paramClsGen);");
1691                 writeStructMembersInitJavaSkeleton(intDecl, methParams, methPrmTypes, method);
1692                 // Write the return value part
1693                 writeMethodHelperReturnJavaSkeleton(intDecl, methParams, methPrmTypes, method, isCallbackMethod, callbackType);
1694         }
1695
1696
1697         /**
1698          * HELPER: writeStdMethodHelperBodyJavaSkeleton() writes the standard method body helper in the skeleton class
1699          */
1700         private void writeStdMethodHelperBodyJavaSkeleton(InterfaceDecl intDecl, List<String> methParams,
1701                         List<String> methPrmTypes, String method, Set<String> callbackClasses) {
1702
1703                 // Generate array of parameter objects
1704                 boolean isCallbackMethod = false;
1705                 String callbackType = null;
1706                 print("Object[] paramObj = rmiObj.getMethodParams(new Class<?>[] { ");
1707                 for (int i = 0; i < methParams.size(); i++) {
1708
1709                         String paramType = returnGenericCallbackType(methPrmTypes.get(i));
1710                         if (callbackClasses.contains(paramType)) {
1711                                 isCallbackMethod = true;
1712                                 callbackType = paramType;
1713                                 print("int.class");
1714                         } else {        // Generate normal classes if it's not a callback object
1715                                 String prmType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
1716                                 print(getSimpleType(getEnumType(prmType)) + ".class");
1717                         }
1718                         if (i != methParams.size() - 1)
1719                                 print(", ");
1720                 }
1721                 println(" }, ");
1722                 // Generate generic class if it's a generic type.. null otherwise
1723                 print("new Class<?>[] { ");
1724                 for (int i = 0; i < methParams.size(); i++) {
1725                         String prmType = methPrmTypes.get(i);
1726                         if (getParamCategory(prmType) == ParamCategory.NONPRIMITIVES)
1727                                 print(getTypeOfGeneric(prmType)[0] + ".class");
1728                         else
1729                                 print("null");
1730                         if (i != methParams.size() - 1)
1731                                 print(", ");
1732                 }
1733                 println(" });");
1734                 // Write the return value part
1735                 writeMethodHelperReturnJavaSkeleton(intDecl, methParams, methPrmTypes, method, isCallbackMethod, callbackType);
1736         }
1737
1738
1739         /**
1740          * HELPER: writeMethodHelperJavaSkeleton() writes the method helper of the skeleton class
1741          */
1742         private void writeMethodHelperJavaSkeleton(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
1743
1744                 // Use this set to handle two same methodIds
1745                 Set<String> uniqueMethodIds = new HashSet<String>();
1746                 for (String method : methods) {
1747
1748                         List<String> methParams = intDecl.getMethodParams(method);
1749                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1750                         if (isStructPresent(methParams, methPrmTypes)) {        // Treat struct differently
1751                                 String methodId = intDecl.getMethodId(method);
1752                                 print("public void ___");
1753                                 String helperMethod = methodId;
1754                                 if (uniqueMethodIds.contains(methodId))
1755                                         helperMethod = helperMethod + intDecl.getMethodNumId(method);
1756                                 else
1757                                         uniqueMethodIds.add(methodId);
1758                                 String retType = intDecl.getMethodType(method);
1759                                 print(helperMethod + "(");
1760                                 boolean begin = true;
1761                                 for (int i = 0; i < methParams.size(); i++) { // Print size variables
1762                                         String paramType = methPrmTypes.get(i);
1763                                         String param = methParams.get(i);
1764                                         String simpleType = getSimpleType(paramType);
1765                                         if (isStructClass(simpleType)) {
1766                                                 if (!begin) {   // Generate comma for not the beginning variable
1767                                                         print(", "); begin = false;
1768                                                 }
1769                                                 int methodNumId = intDecl.getMethodNumId(method);
1770                                                 print("int struct" + methodNumId + "Size" + i);
1771                                         }
1772                                 }
1773                                 // Check if this is "void"
1774                                 if (retType.equals("void"))
1775                                         println(") {");
1776                                 else
1777                                         println(") throws IOException {");
1778                                 writeMethodHelperStructJavaSkeleton(intDecl, methParams, methPrmTypes, method, callbackClasses);
1779                                 println("}\n");
1780                         } else {
1781                                 String methodId = intDecl.getMethodId(method);
1782                                 print("public void ___");
1783                                 String helperMethod = methodId;
1784                                 if (uniqueMethodIds.contains(methodId))
1785                                         helperMethod = helperMethod + intDecl.getMethodNumId(method);
1786                                 else
1787                                         uniqueMethodIds.add(methodId);
1788                                 // Check if this is "void"
1789                                 String retType = intDecl.getMethodType(method);
1790                                 if (retType.equals("void"))
1791                                         println(helperMethod + "() {");
1792                                 else
1793                                         println(helperMethod + "() throws IOException {");
1794                                 // Now, write the helper body of skeleton!
1795                                 writeStdMethodHelperBodyJavaSkeleton(intDecl, methParams, methPrmTypes, method, callbackClasses);
1796                                 println("}\n");
1797                         }
1798                 }
1799                 // Write method helper for structs
1800                 writeMethodHelperStructSetupJavaSkeleton(methods, intDecl);
1801         }
1802
1803
1804         /**
1805          * HELPER: writeMethodHelperStructSetupJavaSkeleton() writes the method helper of the struct in skeleton class
1806          */
1807         private void writeMethodHelperStructSetupJavaSkeleton(Collection<String> methods, 
1808                         InterfaceDecl intDecl) {
1809
1810                 // Use this set to handle two same methodIds
1811                 for (String method : methods) {
1812
1813                         List<String> methParams = intDecl.getMethodParams(method);
1814                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1815                         // Check for params with structs
1816                         for (int i = 0; i < methParams.size(); i++) {
1817                                 String paramType = methPrmTypes.get(i);
1818                                 String param = methParams.get(i);
1819                                 String simpleType = getSimpleType(paramType);
1820                                 if (isStructClass(simpleType)) {
1821                                         int methodNumId = intDecl.getMethodNumId(method);
1822                                         print("public int ___");
1823                                         String helperMethod = methodNumId + "struct" + i;
1824                                         println(helperMethod + "() {");
1825                                         // Now, write the helper body of skeleton!
1826                                         println("Object[] paramObj = rmiObj.getMethodParams(new Class<?>[] { int.class }, new Class<?>[] { null });");
1827                                         println("return (int) paramObj[0];");
1828                                         println("}\n");
1829                                 }
1830                         }
1831                 }
1832         }
1833
1834
1835         /**
1836          * HELPER: writeMethodHelperStructSetupJavaCallbackSkeleton() writes the method helper of the struct in skeleton class
1837          */
1838         private void writeMethodHelperStructSetupJavaCallbackSkeleton(Collection<String> methods, 
1839                         InterfaceDecl intDecl) {
1840
1841                 // Use this set to handle two same methodIds
1842                 for (String method : methods) {
1843
1844                         List<String> methParams = intDecl.getMethodParams(method);
1845                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1846                         // Check for params with structs
1847                         for (int i = 0; i < methParams.size(); i++) {
1848                                 String paramType = methPrmTypes.get(i);
1849                                 String param = methParams.get(i);
1850                                 String simpleType = getSimpleType(paramType);
1851                                 if (isStructClass(simpleType)) {
1852                                         int methodNumId = intDecl.getMethodNumId(method);
1853                                         print("public int ___");
1854                                         String helperMethod = methodNumId + "struct" + i;
1855                                         println(helperMethod + "(IoTRMIObject rmiObj) {");
1856                                         // Now, write the helper body of skeleton!
1857                                         println("Object[] paramObj = rmiObj.getMethodParams(new Class<?>[] { int.class }, new Class<?>[] { null });");
1858                                         println("return (int) paramObj[0];");
1859                                         println("}\n");
1860                                 }
1861                         }
1862                 }
1863         }
1864
1865
1866         /**
1867          * HELPER: writeCountVarStructSkeleton() writes counter variable of struct for skeleton
1868          */
1869         private void writeCountVarStructSkeleton(Collection<String> methods, InterfaceDecl intDecl) {
1870
1871                 // Use this set to handle two same methodIds
1872                 for (String method : methods) {
1873
1874                         List<String> methParams = intDecl.getMethodParams(method);
1875                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1876                         // Check for params with structs
1877                         for (int i = 0; i < methParams.size(); i++) {
1878                                 String paramType = methPrmTypes.get(i);
1879                                 String param = methParams.get(i);
1880                                 String simpleType = getSimpleType(paramType);
1881                                 if (isStructClass(simpleType)) {
1882                                         int methodNumId = intDecl.getMethodNumId(method);
1883                                         println("int struct" + methodNumId + "Size" + i + " = 0;");
1884                                 }
1885                         }
1886                 }
1887         }
1888         
1889         
1890         /**
1891          * HELPER: writeInputCountVarStructSkeleton() writes counter variable of struct for skeleton
1892          */
1893         private boolean writeInputCountVarStructSkeleton(String method, InterfaceDecl intDecl) {
1894
1895                 List<String> methParams = intDecl.getMethodParams(method);
1896                 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1897                 boolean structExist = false;
1898                 // Check for params with structs
1899                 for (int i = 0; i < methParams.size(); i++) {
1900                         String paramType = methPrmTypes.get(i);
1901                         String param = methParams.get(i);
1902                         String simpleType = getSimpleType(paramType);
1903                         boolean begin = true;
1904                         if (isStructClass(simpleType)) {
1905                                 structExist = true;
1906                                 if (!begin) {
1907                                         print(", "); begin = false;
1908                                 }
1909                                 int methodNumId = intDecl.getMethodNumId(method);
1910                                 print("struct" + methodNumId + "Size" + i);
1911                         }
1912                 }
1913                 return structExist;
1914         }
1915
1916
1917         /**
1918          * HELPER: writeMethodCallStructSkeleton() writes method call for wait invoke in skeleton
1919          */
1920         private void writeMethodCallStructSkeleton(Collection<String> methods, InterfaceDecl intDecl) {
1921
1922                 // Use this set to handle two same methodIds
1923                 for (String method : methods) {
1924
1925                         List<String> methParams = intDecl.getMethodParams(method);
1926                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1927                         // Check for params with structs
1928                         for (int i = 0; i < methParams.size(); i++) {
1929                                 String paramType = methPrmTypes.get(i);
1930                                 String param = methParams.get(i);
1931                                 String simpleType = getSimpleType(paramType);
1932                                 if (isStructClass(simpleType)) {
1933                                         int methodNumId = intDecl.getMethodNumId(method);
1934                                         print("case ");
1935                                         String helperMethod = methodNumId + "struct" + i;
1936                                         String tempVar = "struct" + methodNumId + "Size" + i;
1937                                         print(intDecl.getHelperMethodNumId(helperMethod) + ": ");
1938                                         print(tempVar + " = ___");
1939                                         println(helperMethod + "(); break;");
1940                                 }
1941                         }
1942                 }
1943         }
1944
1945
1946         /**
1947          * HELPER: writeMethodCallStructCallbackSkeleton() writes method call for wait invoke in skeleton
1948          */
1949         private void writeMethodCallStructCallbackSkeleton(Collection<String> methods, InterfaceDecl intDecl) {
1950
1951                 // Use this set to handle two same methodIds
1952                 for (String method : methods) {
1953
1954                         List<String> methParams = intDecl.getMethodParams(method);
1955                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1956                         // Check for params with structs
1957                         for (int i = 0; i < methParams.size(); i++) {
1958                                 String paramType = methPrmTypes.get(i);
1959                                 String param = methParams.get(i);
1960                                 String simpleType = getSimpleType(paramType);
1961                                 if (isStructClass(simpleType)) {
1962                                         int methodNumId = intDecl.getMethodNumId(method);
1963                                         print("case ");
1964                                         String helperMethod = methodNumId + "struct" + i;
1965                                         String tempVar = "struct" + methodNumId + "Size" + i;
1966                                         print(intDecl.getHelperMethodNumId(helperMethod) + ": ");
1967                                         print(tempVar + " = ___");
1968                                         println(helperMethod + "(rmiObj); break;");
1969                                 }
1970                         }
1971                 }
1972         }
1973
1974
1975         /**
1976          * HELPER: writeJavaMethodPermission() writes permission checks in skeleton
1977          */
1978         private void writeJavaMethodPermission(String intface) {
1979
1980                 // Get all the different stubs
1981                 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
1982                 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
1983                         String newIntface = intMeth.getKey();
1984                         int newObjectId = mapNewIntfaceObjId.get(newIntface);
1985                         println("if (_objectId == object" + newObjectId + "Id) {");
1986                         println("if (!set" + newObjectId + "Allowed.contains(methodId)) {");
1987                         println("throw new Error(\"Object with object Id: \" + _objectId + \"  is not allowed to access method: \" + methodId);");
1988                         println("}");
1989                         println("else {");
1990                         println("throw new Error(\"Object Id: \" + _objectId + \" not recognized!\");");
1991                         println("}");
1992                         println("}");
1993                 }
1994         }
1995
1996
1997         /**
1998          * HELPER: writeJavaWaitRequestInvokeMethod() writes the main loop of the skeleton class
1999          */
2000         private void writeJavaWaitRequestInvokeMethod(Collection<String> methods, InterfaceDecl intDecl, boolean callbackExist, String intface) {
2001
2002                 // Use this set to handle two same methodIds
2003                 Set<String> uniqueMethodIds = new HashSet<String>();
2004                 println("private void ___waitRequestInvokeMethod() throws IOException {");
2005                 // Write variables here if we have callbacks or enums or structs
2006                 writeCountVarStructSkeleton(methods, intDecl);
2007                 println("while (true) {");
2008                 println("rmiObj.getMethodBytes();");
2009                 println("int _objectId = rmiObj.getObjectId();");
2010                 println("int methodId = rmiObj.getMethodId();");
2011                 // Generate permission check
2012                 writeJavaMethodPermission(intface);
2013                 println("switch (methodId) {");
2014                 // Print methods and method Ids
2015                 for (String method : methods) {
2016                         String methodId = intDecl.getMethodId(method);
2017                         int methodNumId = intDecl.getMethodNumId(method);
2018                         print("case " + methodNumId + ": ___");
2019                         String helperMethod = methodId;
2020                         if (uniqueMethodIds.contains(methodId))
2021                                 helperMethod = helperMethod + methodNumId;
2022                         else
2023                                 uniqueMethodIds.add(methodId);
2024                         print(helperMethod + "(");
2025                         writeInputCountVarStructSkeleton(method, intDecl);
2026                         println("); break;");
2027                 }
2028                 String method = "___initCallBack()";
2029                 // Print case -9999 (callback handler) if callback exists
2030                 if (callbackExist) {
2031                         int methodId = intDecl.getHelperMethodNumId(method);
2032                         println("case " + methodId + ": ___regCB(); break;");
2033                 }
2034                 writeMethodCallStructSkeleton(methods, intDecl);
2035                 println("default: ");
2036                 println("throw new Error(\"Method Id \" + methodId + \" not recognized!\");");
2037                 println("}");
2038                 println("}");
2039                 println("}\n");
2040         }
2041
2042
2043         /**
2044          * generateJavaSkeletonClass() generate skeletons based on the methods list in Java
2045          */
2046         public void generateJavaSkeletonClass() throws IOException {
2047
2048                 // Create a new directory
2049                 String path = createDirectories(dir, subdir);
2050                 for (String intface : mapIntfacePTH.keySet()) {
2051                         // Open a new file to write into
2052                         String newSkelClass = intface + "_Skeleton";
2053                         FileWriter fw = new FileWriter(path + "/" + newSkelClass + ".java");
2054                         pw = new PrintWriter(new BufferedWriter(fw));
2055                         // Pass in set of methods and get import classes
2056                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2057                         InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
2058                         List<String> methods = intDecl.getMethods();
2059                         Set<String> importClasses = getImportClasses(methods, intDecl);
2060                         List<String> stdImportClasses = getStandardJavaImportClasses();
2061                         List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
2062                         printImportStatements(allImportClasses);
2063                         // Find out if there are callback objects
2064                         Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
2065                         boolean callbackExist = !callbackClasses.isEmpty();
2066                         // Write class header
2067                         println("");
2068                         println("public class " + newSkelClass  + " implements " + intface + " {\n");
2069                         // Write properties
2070                         writePropertiesJavaSkeleton(intface, callbackExist, intDecl);
2071                         // Write constructor
2072                         writeConstructorJavaSkeleton(newSkelClass, intface);
2073                         // Write methods
2074                         writeMethodJavaSkeleton(methods, intDecl, callbackClasses, false);
2075                         // Write method helper
2076                         writeMethodHelperJavaSkeleton(methods, intDecl, callbackClasses);
2077                         // Write waitRequestInvokeMethod() - main loop
2078                         writeJavaWaitRequestInvokeMethod(methods, intDecl, callbackExist, intface);
2079                         println("}");
2080                         pw.close();
2081                         System.out.println("IoTCompiler: Generated skeleton class " + newSkelClass + ".java...");
2082                 }
2083         }
2084
2085
2086         /**
2087          * HELPER: writePropertiesJavaCallbackSkeleton() writes the properties of the callback skeleton class
2088          */
2089         private void writePropertiesJavaCallbackSkeleton(String intface, boolean callbackExist) {
2090
2091                 println("private " + intface + " mainObj;");
2092                 // For callback skeletons, this is its own object Id
2093                 println("private static int objectId = 0;");
2094                 // Callback
2095                 if (callbackExist) {
2096                         println("private static int objIdCnt = 0;");
2097                         println("private IoTRMICall rmiCall;");
2098                 }
2099                 println("\n");
2100         }
2101
2102
2103         /**
2104          * HELPER: writeConstructorJavaCallbackSkeleton() writes the constructor of the skeleton class
2105          */
2106         private void writeConstructorJavaCallbackSkeleton(String newSkelClass, String intface) {
2107
2108                 println("public " + newSkelClass + "(" + intface + " _mainObj, int _objectId) throws Exception {");
2109                 println("mainObj = _mainObj;");
2110                 println("objectId = _objectId;");
2111                 println("}\n");
2112         }
2113
2114
2115         /**
2116          * HELPER: writeMethodHelperJavaCallbackSkeleton() writes the method helper of the callback skeleton class
2117          */
2118         private void writeMethodHelperJavaCallbackSkeleton(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
2119
2120                 // Use this set to handle two same methodIds
2121                 Set<String> uniqueMethodIds = new HashSet<String>();
2122                 for (String method : methods) {
2123
2124                         List<String> methParams = intDecl.getMethodParams(method);
2125                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2126                         if (isStructPresent(methParams, methPrmTypes)) {        // Treat struct differently
2127                                 String methodId = intDecl.getMethodId(method);
2128                                 print("public void ___");
2129                                 String helperMethod = methodId;
2130                                 if (uniqueMethodIds.contains(methodId))
2131                                         helperMethod = helperMethod + intDecl.getMethodNumId(method);
2132                                 else
2133                                         uniqueMethodIds.add(methodId);
2134                                 String retType = intDecl.getMethodType(method);
2135                                 print(helperMethod + "(");
2136                                 boolean begin = true;
2137                                 for (int i = 0; i < methParams.size(); i++) { // Print size variables
2138                                         String paramType = methPrmTypes.get(i);
2139                                         String param = methParams.get(i);
2140                                         String simpleType = getSimpleType(paramType);
2141                                         if (isStructClass(simpleType)) {
2142                                                 if (!begin) {   // Generate comma for not the beginning variable
2143                                                         print(", "); begin = false;
2144                                                 }
2145                                                 int methodNumId = intDecl.getMethodNumId(method);
2146                                                 print("int struct" + methodNumId + "Size" + i);
2147                                         }
2148                                 }
2149                                 // Check if this is "void"
2150                                 if (retType.equals("void"))
2151                                         println(", IoTRMIObject rmiObj) {");
2152                                 else
2153                                         println(", IoTRMIObject rmiObj) throws IOException {");
2154                                 writeMethodHelperStructJavaSkeleton(intDecl, methParams, methPrmTypes, method, callbackClasses);
2155                                 println("}\n");
2156                         } else {
2157                                 String methodId = intDecl.getMethodId(method);
2158                                 print("public void ___");
2159                                 String helperMethod = methodId;
2160                                 if (uniqueMethodIds.contains(methodId))
2161                                         helperMethod = helperMethod + intDecl.getMethodNumId(method);
2162                                 else
2163                                         uniqueMethodIds.add(methodId);
2164                                 // Check if this is "void"
2165                                 String retType = intDecl.getMethodType(method);
2166                                 if (retType.equals("void"))
2167                                         println(helperMethod + "(IoTRMIObject rmiObj) {");
2168                                 else
2169                                         println(helperMethod + "(IoTRMIObject rmiObj) throws IOException {");
2170                                 // Now, write the helper body of skeleton!
2171                                 writeStdMethodHelperBodyJavaSkeleton(intDecl, methParams, methPrmTypes, method, callbackClasses);
2172                                 println("}\n");
2173                         }
2174                 }
2175                 // Write method helper for structs
2176                 writeMethodHelperStructSetupJavaCallbackSkeleton(methods, intDecl);
2177         }
2178
2179
2180         /**
2181          * HELPER: writeJavaCallbackWaitRequestInvokeMethod() writes the main loop of the skeleton class
2182          */
2183         private void writeJavaCallbackWaitRequestInvokeMethod(Collection<String> methods, InterfaceDecl intDecl, boolean callbackExist) {
2184
2185                 // Use this set to handle two same methodIds
2186                 Set<String> uniqueMethodIds = new HashSet<String>();
2187                 println("public void invokeMethod(IoTRMIObject rmiObj) throws IOException {");
2188                 // Write variables here if we have callbacks or enums or structs
2189                 writeCountVarStructSkeleton(methods, intDecl);
2190                 // Write variables here if we have callbacks or enums or structs
2191                 println("int methodId = rmiObj.getMethodId();");
2192                 // TODO: code the permission check here!
2193                 println("switch (methodId) {");
2194                 // Print methods and method Ids
2195                 for (String method : methods) {
2196                         String methodId = intDecl.getMethodId(method);
2197                         int methodNumId = intDecl.getMethodNumId(method);
2198                         print("case " + methodNumId + ": ___");
2199                         String helperMethod = methodId;
2200                         if (uniqueMethodIds.contains(methodId))
2201                                 helperMethod = helperMethod + methodNumId;
2202                         else
2203                                 uniqueMethodIds.add(methodId);
2204                         print(helperMethod + "(");
2205                         if (writeInputCountVarStructSkeleton(method, intDecl))
2206                                 println(", rmiObj); break;");
2207                         else
2208                                 println("rmiObj); break;");
2209                 }
2210                 String method = "___initCallBack()";
2211                 // Print case -9999 (callback handler) if callback exists
2212                 if (callbackExist) {
2213                         int methodId = intDecl.getHelperMethodNumId(method);
2214                         println("case " + methodId + ": ___regCB(rmiObj); break;");
2215                 }
2216                 writeMethodCallStructCallbackSkeleton(methods, intDecl);
2217                 println("default: ");
2218                 println("throw new Error(\"Method Id \" + methodId + \" not recognized!\");");
2219                 println("}");
2220                 println("}\n");
2221         }
2222
2223
2224         /**
2225          * generateJavaCallbackSkeletonClass() generate callback skeletons based on the methods list in Java
2226          */
2227         public void generateJavaCallbackSkeletonClass() throws IOException {
2228
2229                 // Create a new directory
2230                 String path = createDirectories(dir, subdir);
2231                 for (String intface : mapIntfacePTH.keySet()) {
2232                         // Open a new file to write into
2233                         String newSkelClass = intface + "_CallbackSkeleton";
2234                         FileWriter fw = new FileWriter(path + "/" + newSkelClass + ".java");
2235                         pw = new PrintWriter(new BufferedWriter(fw));
2236                         // Pass in set of methods and get import classes
2237                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2238                         InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
2239                         List<String> methods = intDecl.getMethods();
2240                         Set<String> importClasses = getImportClasses(methods, intDecl);
2241                         List<String> stdImportClasses = getStandardJavaImportClasses();
2242                         List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
2243                         printImportStatements(allImportClasses);
2244                         // Find out if there are callback objects
2245                         Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
2246                         boolean callbackExist = !callbackClasses.isEmpty();
2247                         // Write class header
2248                         println("");
2249                         println("public class " + newSkelClass  + " implements " + intface + " {\n");
2250                         // Write properties
2251                         writePropertiesJavaCallbackSkeleton(intface, callbackExist);
2252                         // Write constructor
2253                         writeConstructorJavaCallbackSkeleton(newSkelClass, intface);
2254                         // Write methods
2255                         writeMethodJavaSkeleton(methods, intDecl, callbackClasses, true);
2256                         // Write method helper
2257                         writeMethodHelperJavaCallbackSkeleton(methods, intDecl, callbackClasses);
2258                         // Write waitRequestInvokeMethod() - main loop
2259                         writeJavaCallbackWaitRequestInvokeMethod(methods, intDecl, callbackExist);
2260                         println("}");
2261                         pw.close();
2262                         System.out.println("IoTCompiler: Generated callback skeleton class " + newSkelClass + ".java...");
2263                 }
2264         }
2265
2266
2267         /**
2268          * HELPER: writeMethodCplusLocalInterface() writes the method of the interface
2269          */
2270         private void writeMethodCplusLocalInterface(Collection<String> methods, InterfaceDecl intDecl) {
2271
2272                 for (String method : methods) {
2273
2274                         List<String> methParams = intDecl.getMethodParams(method);
2275                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2276                         print("virtual " + checkAndGetCplusType(intDecl.getMethodType(method)) + " " +
2277                                 intDecl.getMethodId(method) + "(");
2278                         for (int i = 0; i < methParams.size(); i++) {
2279                                 // Check for params with driver class types and exchange it 
2280                                 //              with its remote interface
2281                                 String paramType = checkAndGetParamClass(methPrmTypes.get(i));
2282                                 paramType = checkAndGetCplusType(paramType);
2283                                 // Check for arrays - translate into vector in C++
2284                                 String paramComplete = checkAndGetCplusArray(paramType, methParams.get(i));
2285                                 print(paramComplete);
2286                                 // Check if this is the last element (don't print a comma)
2287                                 if (i != methParams.size() - 1) {
2288                                         print(", ");
2289                                 }
2290                         }
2291                         println(") = 0;");
2292                 }
2293         }
2294
2295
2296         /**
2297          * HELPER: writeMethodCplusInterface() writes the method of the interface
2298          */
2299         private void writeMethodCplusInterface(Collection<String> methods, InterfaceDecl intDecl) {
2300
2301                 for (String method : methods) {
2302
2303                         List<String> methParams = intDecl.getMethodParams(method);
2304                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2305                         print("virtual " + checkAndGetCplusType(intDecl.getMethodType(method)) + " " +
2306                                 intDecl.getMethodId(method) + "(");
2307                         for (int i = 0; i < methParams.size(); i++) {
2308                                 // Check for params with driver class types and exchange it 
2309                                 //              with its remote interface
2310                                 String paramType = methPrmTypes.get(i);
2311                                 paramType = checkAndGetCplusType(paramType);
2312                                 // Check for arrays - translate into vector in C++
2313                                 String paramComplete = checkAndGetCplusArray(paramType, methParams.get(i));
2314                                 print(paramComplete);
2315                                 // Check if this is the last element (don't print a comma)
2316                                 if (i != methParams.size() - 1) {
2317                                         print(", ");
2318                                 }
2319                         }
2320                         println(") = 0;");
2321                 }
2322         }
2323
2324
2325         /**
2326          * HELPER: generateEnumCplus() writes the enumeration declaration
2327          */
2328         public void generateEnumCplus() throws IOException {
2329
2330                 // Create a new directory
2331                 createDirectory(dir);
2332                 for (String intface : mapIntfacePTH.keySet()) {
2333                         // Get the right StructDecl
2334                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2335                         EnumDecl enumDecl = (EnumDecl) decHandler.getEnumDecl(intface);
2336                         Set<String> enumTypes = enumDecl.getEnumDeclarations();
2337                         // Iterate over enum declarations
2338                         for (String enType : enumTypes) {
2339                                 // Open a new file to write into
2340                                 FileWriter fw = new FileWriter(dir + "/" + enType + ".hpp");
2341                                 pw = new PrintWriter(new BufferedWriter(fw));
2342                                 // Write file headers
2343                                 println("#ifndef _" + enType.toUpperCase() + "_HPP__");
2344                                 println("#define _" + enType.toUpperCase() + "_HPP__");
2345                                 println("enum " + enType + " {");
2346                                 List<String> enumMembers = enumDecl.getMembers(enType);
2347                                 for (int i = 0; i < enumMembers.size(); i++) {
2348
2349                                         String member = enumMembers.get(i);
2350                                         print(member);
2351                                         // Check if this is the last element (don't print a comma)
2352                                         if (i != enumMembers.size() - 1)
2353                                                 println(",");
2354                                         else
2355                                                 println("");
2356                                 }
2357                                 println("};\n");
2358                                 println("#endif");
2359                                 pw.close();
2360                                 System.out.println("IoTCompiler: Generated enum " + enType + ".hpp...");
2361                         }
2362                 }
2363         }
2364
2365
2366         /**
2367          * HELPER: generateStructCplus() writes the struct declaration
2368          */
2369         public void generateStructCplus() throws IOException {
2370
2371                 // Create a new directory
2372                 createDirectory(dir);
2373                 for (String intface : mapIntfacePTH.keySet()) {
2374                         // Get the right StructDecl
2375                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2376                         StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
2377                         List<String> structTypes = structDecl.getStructTypes();
2378                         // Iterate over enum declarations
2379                         for (String stType : structTypes) {
2380                                 // Open a new file to write into
2381                                 FileWriter fw = new FileWriter(dir + "/" + stType + ".hpp");
2382                                 pw = new PrintWriter(new BufferedWriter(fw));
2383                                 // Write file headers
2384                                 println("#ifndef _" + stType.toUpperCase() + "_HPP__");
2385                                 println("#define _" + stType.toUpperCase() + "_HPP__");
2386                                 println("struct " + stType + " {");
2387                                 List<String> structMemberTypes = structDecl.getMemberTypes(stType);
2388                                 List<String> structMembers = structDecl.getMembers(stType);
2389                                 for (int i = 0; i < structMembers.size(); i++) {
2390
2391                                         String memberType = structMemberTypes.get(i);
2392                                         String member = structMembers.get(i);
2393                                         String structTypeC = checkAndGetCplusType(memberType);
2394                                         String structComplete = checkAndGetCplusArray(structTypeC, member);
2395                                         println(structComplete + ";");
2396                                 }
2397                                 println("};\n");
2398                                 println("#endif");
2399                                 pw.close();
2400                                 System.out.println("IoTCompiler: Generated struct " + stType + ".hpp...");
2401                         }
2402                 }
2403         }
2404
2405
2406         /**
2407          * generateCplusLocalInterfaces() writes the local interfaces and provides type-checking.
2408          * <p>
2409          * It needs to rewrite and exchange USERDEFINED types in input parameters of stub
2410          * and original interfaces, e.g. exchange Camera and CameraWithVideoAndRecording.
2411          * The local interface has to be the input parameter for the stub and the stub 
2412          * interface has to be the input parameter for the local class.
2413          */
2414         public void generateCplusLocalInterfaces() throws IOException {
2415
2416                 // Create a new directory
2417                 createDirectory(dir);
2418                 for (String intface : mapIntfacePTH.keySet()) {
2419                         // Open a new file to write into
2420                         FileWriter fw = new FileWriter(dir + "/" + intface + ".hpp");
2421                         pw = new PrintWriter(new BufferedWriter(fw));
2422                         // Write file headers
2423                         println("#ifndef _" + intface.toUpperCase() + "_HPP__");
2424                         println("#define _" + intface.toUpperCase() + "_HPP__");
2425                         println("#include <iostream>");
2426                         // Pass in set of methods and get include classes
2427                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2428                         InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
2429                         List<String> methods = intDecl.getMethods();
2430                         Set<String> includeClasses = getIncludeClasses(methods, intDecl, intface, true);
2431                         printIncludeStatements(includeClasses); println("");
2432                         println("using namespace std;\n");
2433                         // Write enum if any...
2434                         //EnumDecl enumDecl = (EnumDecl) decHandler.getEnumDecl(intface);
2435                         //writeEnumCplus(enumDecl);
2436                         // Write struct if any...
2437                         //StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
2438                         //writeStructCplus(structDecl);
2439                         println("class " + intface); println("{");
2440                         println("public:");
2441                         // Write methods
2442                         writeMethodCplusLocalInterface(methods, intDecl);
2443                         println("};");
2444                         println("#endif");
2445                         pw.close();
2446                         System.out.println("IoTCompiler: Generated local interface " + intface + ".hpp...");
2447                 }
2448         }
2449
2450
2451         /**
2452          * generateCPlusInterfaces() generate stub interfaces based on the methods list in C++
2453          * <p>
2454          * For C++ we use virtual classe as interface
2455          */
2456         public void generateCPlusInterfaces() throws IOException {
2457
2458                 // Create a new directory
2459                 String path = createDirectories(dir, subdir);
2460                 for (String intface : mapIntfacePTH.keySet()) {
2461
2462                         Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
2463                         for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
2464
2465                                 // Open a new file to write into
2466                                 String newIntface = intMeth.getKey();
2467                                 FileWriter fw = new FileWriter(path + "/" + newIntface + ".hpp");
2468                                 pw = new PrintWriter(new BufferedWriter(fw));
2469                                 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2470                                 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
2471                                 // Write file headers
2472                                 println("#ifndef _" + newIntface.toUpperCase() + "_HPP__");
2473                                 println("#define _" + newIntface.toUpperCase() + "_HPP__");
2474                                 println("#include <iostream>");
2475                                 // Pass in set of methods and get import classes
2476                                 Set<String> includeClasses = getIncludeClasses(intMeth.getValue(), intDecl, intface, false);
2477                                 List<String> stdIncludeClasses = getStandardCplusIncludeClasses();
2478                                 List<String> allIncludeClasses = getAllLibClasses(stdIncludeClasses, includeClasses);
2479                                 printIncludeStatements(allIncludeClasses); println("");                 
2480                                 println("using namespace std;\n");
2481                                 println("class " + newIntface);
2482                                 println("{");
2483                                 println("public:");
2484                                 // Write methods
2485                                 writeMethodCplusInterface(intMeth.getValue(), intDecl);
2486                                 println("};");
2487                                 println("#endif");
2488                                 pw.close();
2489                                 System.out.println("IoTCompiler: Generated interface " + newIntface + ".hpp...");
2490                         }
2491                 }
2492         }
2493
2494
2495         /**
2496          * HELPER: writeMethodCplusStub() writes the method of the stub
2497          */
2498         private void writeMethodCplusStub(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
2499
2500                 for (String method : methods) {
2501
2502                         List<String> methParams = intDecl.getMethodParams(method);
2503                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2504                         print(checkAndGetCplusType(intDecl.getMethodType(method)) + " " +
2505                                 intDecl.getMethodId(method) + "(");
2506                         boolean isCallbackMethod = false;
2507                         String callbackType = null;
2508                         for (int i = 0; i < methParams.size(); i++) {
2509
2510                                 String paramType = methPrmTypes.get(i);
2511                                 // Check if this has callback object
2512                                 if (callbackClasses.contains(paramType)) {
2513                                         isCallbackMethod = true;
2514                                         callbackType = paramType;       
2515                                         // Even if there're 2 callback arguments, we expect them to be of the same interface
2516                                 }
2517                                 String methPrmType = checkAndGetCplusType(methPrmTypes.get(i));
2518                                 String methParamComplete = checkAndGetCplusArray(methPrmType, methParams.get(i));
2519                                 print(methParamComplete);
2520                                 // Check if this is the last element (don't print a comma)
2521                                 if (i != methParams.size() - 1) {
2522                                         print(", ");
2523                                 }
2524                         }
2525                         println(") { ");
2526                         if (isCallbackMethod)
2527                                 writeCallbackMethodBodyCplusStub(intDecl, methParams, methPrmTypes, method, callbackType);
2528                         else
2529                                 writeStdMethodBodyCplusStub(intDecl, methParams, methPrmTypes, method);
2530                         println("}\n");
2531                         // Write the init callback helper method
2532                         if (isCallbackMethod) {
2533                                 writeInitCallbackCplusStub(callbackType, intDecl);
2534                                 writeInitCallbackSendInfoCplusStub(intDecl);
2535                         }
2536                 }
2537         }
2538
2539
2540         /**
2541          * HELPER: writeCallbackMethodBodyCplusStub() writes the callback method of the stub class
2542          */
2543         private void writeCallbackMethodBodyCplusStub(InterfaceDecl intDecl, List<String> methParams,
2544                         List<String> methPrmTypes, String method, String callbackType) {
2545
2546                 // Check if this is single object, array, or list of objects
2547                 boolean isArrayOrList = false;
2548                 String callbackParam = null;
2549                 for (int i = 0; i < methParams.size(); i++) {
2550
2551                         String paramType = methPrmTypes.get(i);
2552                         if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
2553                                 String param = methParams.get(i);
2554                                 if (isArrayOrList(paramType, param)) {  // Generate loop
2555                                         println("for (" + paramType + "* cb : " + getSimpleIdentifier(param) + ") {");
2556                                         println(callbackType + "_CallbackSkeleton* skel = new " + callbackType + "_CallbackSkeleton(cb, objIdCnt++);");
2557                                         isArrayOrList = true;
2558                                         callbackParam = getSimpleIdentifier(param);
2559                                 } else
2560                                         println(callbackType + "_CallbackSkeleton* skel = new " + callbackType + "_CallbackSkeleton(" +
2561                                                 getSimpleIdentifier(param) + ", objIdCnt++);");
2562                                 println("vecCallbackObj.push_back(skel);");
2563                                 if (isArrayOrList(paramType, param))
2564                                         println("}");
2565                         }
2566                 }
2567                 println("int numParam = " + methParams.size() + ";");
2568                 println("int methodId = " + intDecl.getMethodNumId(method) + ";");
2569                 String retType = intDecl.getMethodType(method);
2570                 String retTypeC = checkAndGetCplusType(retType);
2571                 println("string retType = \"" + checkAndGetCplusArrayType(retTypeC) + "\";");
2572                 // Generate array of parameter types
2573                 print("string paramCls[] = { ");
2574                 for (int i = 0; i < methParams.size(); i++) {
2575                         String paramType = methPrmTypes.get(i);
2576                         if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
2577                                 print("\"int\"");
2578                         } else { // Generate normal classes if it's not a callback object
2579                                 String paramTypeC = checkAndGetCplusType(methPrmTypes.get(i));
2580                                 String prmType = checkAndGetCplusArrayType(paramTypeC, methParams.get(i));
2581                                 print("\"" + prmType + "\"");
2582                         }
2583                         if (i != methParams.size() - 1) // Check if this is the last element
2584                                 print(", ");
2585                 }
2586                 println(" };");
2587                 print("int ___paramCB = ");
2588                 if (isArrayOrList)
2589                         println(callbackParam + ".size();");
2590                 else
2591                         println("1;");
2592                 // Generate array of parameter objects
2593                 print("void* paramObj[] = { ");
2594                 for (int i = 0; i < methParams.size(); i++) {
2595                         String paramType = methPrmTypes.get(i);
2596                         if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
2597                                 print("&___paramCB");
2598                         } else
2599                                 print(getSimpleIdentifier(methParams.get(i)));
2600                         if (i != methParams.size() - 1)
2601                                 print(", ");
2602                 }
2603                 println(" };");
2604                 // Check if this is "void"
2605                 if (retType.equals("void")) {
2606                         println("void* retObj = NULL;");
2607                         println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
2608                 } else { // We do have a return value
2609                         if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
2610                                 println(checkAndGetCplusType(retType) + " retVal;");
2611                         else
2612                                 println(checkAndGetCplusType(retType) + " retVal = " + generateCplusInitializer(retType) + ";");
2613                         println("void* retObj = &retVal;");
2614                         println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
2615                         println("return retVal;");
2616                 }
2617         }
2618
2619
2620         /**
2621          * HELPER: checkAndWriteEnumTypeCplusStub() writes the enum type (convert from enum to int)
2622          */
2623         private void checkAndWriteEnumTypeCplusStub(List<String> methParams, List<String> methPrmTypes) {
2624
2625                 // Iterate and find enum declarations
2626                 for (int i = 0; i < methParams.size(); i++) {
2627                         String paramType = methPrmTypes.get(i);
2628                         String param = methParams.get(i);
2629                         String simpleType = getSimpleType(paramType);
2630                         if (isEnumClass(simpleType)) {
2631                         // Check if this is enum type
2632                                 if (isArrayOrList(paramType, param)) {  // An array or vector
2633                                         println("int len" + i + " = " + param + ".size();");
2634                                         println("vector<int> paramEnum" + i + "(len);");
2635                                         println("for (int i = 0; i < len" + i + "; i++) {");
2636                                         println("paramEnum" + i + "[i] = (int) " + param + "[i];");
2637                                         println("}");
2638                                 } else {        // Just one element
2639                                         println("vector<int> paramEnum" + i + "(1);");
2640                                         println("paramEnum" + i + "[0] = (int) " + param + ";");
2641                                 }
2642                         }
2643                 }
2644         }
2645
2646
2647         /**
2648          * HELPER: checkAndWriteEnumRetTypeCplusStub() writes the enum return type (convert from enum to int)
2649          */
2650         private void checkAndWriteEnumRetTypeCplusStub(String retType) {
2651
2652                 // Strips off array "[]" for return type
2653                 String pureType = getSimpleArrayType(getSimpleType(retType));
2654                 // Take the inner type of generic
2655                 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
2656                         pureType = getTypeOfGeneric(retType)[0];
2657                 if (isEnumClass(pureType)) {
2658                 // Check if this is enum type
2659                         println("vector<int> retEnumInt;");
2660                         println("void* retObj = &retEnumInt;");
2661                         println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
2662                         if (isArrayOrList(retType, retType)) {  // An array or vector
2663                                 println("int retLen = retEnumInt.size();");
2664                                 println("vector<" + pureType + "> retVal(retLen);");
2665                                 println("for (int i = 0; i < retLen; i++) {");
2666                                 println("retVal[i] = (" + pureType + ") retEnumInt[i];");
2667                                 println("}");
2668                         } else {        // Just one element
2669                                 println(pureType + " retVal = (" + pureType + ") retEnumInt[0];");
2670                         }
2671                         println("return retVal;");
2672                 }
2673         }
2674
2675
2676         /**
2677          * HELPER: checkAndWriteStructSetupCplusStub() writes the struct type setup
2678          */
2679         private void checkAndWriteStructSetupCplusStub(List<String> methParams, List<String> methPrmTypes, 
2680                         InterfaceDecl intDecl, String method) {
2681                 
2682                 // Iterate and find struct declarations
2683                 for (int i = 0; i < methParams.size(); i++) {
2684                         String paramType = methPrmTypes.get(i);
2685                         String param = methParams.get(i);
2686                         String simpleType = getSimpleType(paramType);
2687                         if (isStructClass(simpleType)) {
2688                         // Check if this is enum type
2689                                 println("int numParam" + i + " = 1;");
2690                                 int methodNumId = intDecl.getMethodNumId(method);
2691                                 String helperMethod = methodNumId + "struct" + i;
2692                                 println("int methodIdStruct" + i + " = " + intDecl.getHelperMethodNumId(helperMethod) + ";");
2693                                 println("string retTypeStruct" + i + " = \"void\";");
2694                                 println("string paramClsStruct" + i + "[] = { \"int\" };");
2695                                 print("int structLen" + i + " = ");
2696                                 if (isArrayOrList(param, paramType)) {  // An array
2697                                         println(getSimpleArrayType(param) + ".size();");
2698                                 } else {        // Just one element
2699                                         println("1;");
2700                                 }
2701                                 println("void* paramObjStruct" + i + "[] = { &structLen" + i + " };");
2702                                 println("void* retStructLen" + i + " = NULL;");
2703                                 println("rmiCall->remoteCall(objectId, methodIdStruct" + i + 
2704                                                 ", retTypeStruct" + i + ", paramClsStruct" + i + ", paramObjStruct" + i + 
2705                                                 ", numParam" + i + ", retStructLen" + i + ");\n");
2706                         }
2707                 }
2708         }
2709
2710
2711         /**
2712          * HELPER: writeLengthStructParamClassCplusStub() writes lengths of params
2713          */
2714         private void writeLengthStructParamClassCplusStub(List<String> methParams, List<String> methPrmTypes) {
2715
2716                 // Iterate and find struct declarations - count number of params
2717                 for (int i = 0; i < methParams.size(); i++) {
2718                         String paramType = methPrmTypes.get(i);
2719                         String param = methParams.get(i);
2720                         String simpleType = getGenericType(paramType);
2721                         if (isStructClass(simpleType)) {
2722                                 int members = getNumOfMembers(simpleType);
2723                                 if (isArrayOrList(param, paramType)) {                  // An array
2724                                         String structLen = param + ".size()";
2725                                         print(members + "*" + structLen);
2726                                 } else
2727                                         print(Integer.toString(members));
2728                         } else
2729                                 print("1");
2730                         if (i != methParams.size() - 1) {
2731                                 print("+");
2732                         }
2733                 }
2734         }
2735
2736
2737         /**
2738          * HELPER: writeStructMembersCplusStub() writes parameters of struct
2739          */
2740         private void writeStructMembersCplusStub(String simpleType, String paramType, String param) {
2741
2742                 // Get the struct declaration for this struct and generate initialization code
2743                 StructDecl structDecl = getStructDecl(simpleType);
2744                 List<String> memTypes = structDecl.getMemberTypes(simpleType);
2745                 List<String> members = structDecl.getMembers(simpleType);
2746                 if (isArrayOrList(param, paramType)) {  // An array or list
2747                         println("for(int i = 0; i < " + param + ".size(); i++) {");
2748                 }
2749                 if (isArrayOrList(param, paramType)) {  // An array or list
2750                         for (int i = 0; i < members.size(); i++) {
2751                                 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
2752                                 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
2753                                 println("paramCls[pos] = \"" + getSimpleType(getEnumType(prmType)) + "\";");
2754                                 print("paramObj[pos++] = &" + param + "[i].");
2755                                 print(getSimpleIdentifier(members.get(i)));
2756                                 println(";");
2757                         }
2758                         println("}");
2759                 } else {        // Just one struct element
2760                         for (int i = 0; i < members.size(); i++) {
2761                                 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
2762                                 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
2763                                 println("paramCls[pos] = \"" + getSimpleType(getEnumType(prmType)) + "\";");
2764                                 print("paramObj[pos++] = &" + param + ".");
2765                                 print(getSimpleIdentifier(members.get(i)));
2766                                 println(";");
2767                         }
2768                 }
2769         }
2770
2771
2772         /**
2773          * HELPER: writeStructParamClassCplusStub() writes parameters if struct is present
2774          */
2775         private void writeStructParamClassCplusStub(List<String> methParams, List<String> methPrmTypes) {
2776
2777                 print("int numParam = ");
2778                 writeLengthStructParamClassCplusStub(methParams, methPrmTypes);
2779                 println(";");
2780                 println("void* paramObj[numParam];");
2781                 println("string paramCls[numParam];");
2782                 println("int pos = 0;");
2783                 // Iterate again over the parameters
2784                 for (int i = 0; i < methParams.size(); i++) {
2785                         String paramType = methPrmTypes.get(i);
2786                         String param = methParams.get(i);
2787                         String simpleType = getGenericType(paramType);
2788                         if (isStructClass(simpleType)) {
2789                                 writeStructMembersCplusStub(simpleType, paramType, param);
2790                         } else {
2791                                 String prmTypeC = checkAndGetCplusType(methPrmTypes.get(i));
2792                                 String prmType = checkAndGetCplusArrayType(prmTypeC, methParams.get(i));
2793                                 println("paramCls[pos] = \"" + getSimpleType(getEnumType(prmType)) + "\";");
2794                                 print("paramObj[pos++] = &");
2795                                 print(getEnumParam(methPrmTypes.get(i), getSimpleIdentifier(methParams.get(i)), i));
2796                                 println(";");
2797                         }
2798                 }
2799                 
2800         }
2801
2802
2803         /**
2804          * HELPER: writeStructRetMembersCplusStub() writes parameters of struct
2805          */
2806         private void writeStructRetMembersCplusStub(String simpleType, String retType) {
2807
2808                 // Get the struct declaration for this struct and generate initialization code
2809                 StructDecl structDecl = getStructDecl(simpleType);
2810                 List<String> memTypes = structDecl.getMemberTypes(simpleType);
2811                 List<String> members = structDecl.getMembers(simpleType);
2812                 if (isArrayOrList(retType, retType)) {  // An array or list
2813                         println("for(int i = 0; i < retLen; i++) {");
2814                 }
2815                 if (isArrayOrList(retType, retType)) {  // An array or list
2816                         for (int i = 0; i < members.size(); i++) {
2817                                 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
2818                                 print("structRet[i]." + getSimpleIdentifier(members.get(i)));
2819                                 println(" = retParam" + i + "[i];");
2820                         }
2821                         println("}");
2822                 } else {        // Just one struct element
2823                         for (int i = 0; i < members.size(); i++) {
2824                                 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
2825                                 print("structRet." + getSimpleIdentifier(members.get(i)));
2826                                 println(" = retParam" + i + ";");
2827                         }
2828                 }
2829                 println("return structRet;");
2830         }
2831
2832
2833         /**
2834          * HELPER: writeStructReturnCplusStub() writes parameters if struct is present
2835          */
2836         private void writeStructReturnCplusStub(String simpleType, String retType) {
2837
2838                 // Minimum retLen is 1 if this is a single struct object
2839                 println("int retLen = 0;");
2840                 println("void* retLenObj = { &retLen };");
2841                 // Handle the returned struct!!!
2842                 println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retLenObj);");
2843                 int numMem = getNumOfMembers(simpleType);
2844                 println("int numRet = " + numMem + "*retLen;");
2845                 println("string retCls[numRet];");
2846                 println("void* retObj[numRet];");
2847                 StructDecl structDecl = getStructDecl(simpleType);
2848                 List<String> memTypes = structDecl.getMemberTypes(simpleType);
2849                 List<String> members = structDecl.getMembers(simpleType);
2850                 // Set up variables
2851                 if (isArrayOrList(retType, retType)) {  // An array or list
2852                         for (int i = 0; i < members.size(); i++) {
2853                                 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
2854                                 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
2855                                 println(getSimpleType(getEnumType(prmType)) + " retParam" + i + "[retLen];");
2856                         }
2857                 } else {        // Just one struct element
2858                         for (int i = 0; i < members.size(); i++) {
2859                                 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
2860                                 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
2861                                 println(getSimpleType(getEnumType(prmType)) + " retParam" + i + ";");
2862                         }
2863                 }
2864                 println("int retPos = 0;");
2865                 // Get the struct declaration for this struct and generate initialization code
2866                 if (isArrayOrList(retType, retType)) {  // An array or list
2867                         println("for(int i = 0; i < retLen; i++) {");
2868                         for (int i = 0; i < members.size(); i++) {
2869                                 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
2870                                 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
2871                                 println("retCls[retPos] = \"" + getSimpleType(getEnumType(prmType)) + "\";");
2872                                 println("retObj[retPos++] = &retParam" + i + "[i];");
2873                         }
2874                         println("}");
2875                 } else {        // Just one struct element
2876                         for (int i = 0; i < members.size(); i++) {
2877                                 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
2878                                 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
2879                                 println("retCls[retPos] = \"" + getSimpleType(getEnumType(prmType)) + "\";");
2880                                 println("retObj[retPos++] = &retParam" + i + ";");
2881                         }
2882                 }
2883                 println("rmiCall->getStructObjects(retCls, numRet, retObj);");
2884                 if (isArrayOrList(retType, retType)) {  // An array or list
2885                         println("vector<" + simpleType + "> structRet(retLen);");
2886                 } else
2887                         println(simpleType + " structRet;");
2888                 writeStructRetMembersCplusStub(simpleType, retType);
2889         }
2890
2891
2892         /**
2893          * HELPER: writeStdMethodBodyCplusStub() writes the standard method body in the stub class
2894          */
2895         private void writeStdMethodBodyCplusStub(InterfaceDecl intDecl, List<String> methParams,
2896                         List<String> methPrmTypes, String method) {
2897
2898                 checkAndWriteStructSetupCplusStub(methParams, methPrmTypes, intDecl, method);
2899                 println("int methodId = " + intDecl.getMethodNumId(method) + ";");
2900                 String retType = intDecl.getMethodType(method);
2901                 String retTypeC = checkAndGetCplusType(retType);
2902                 println("string retType = \"" + checkAndGetCplusArrayType(getStructType(getEnumType(retTypeC))) + "\";");
2903                 // Generate array of parameter types
2904                 if (isStructPresent(methParams, methPrmTypes)) {
2905                         writeStructParamClassCplusStub(methParams, methPrmTypes);
2906                 } else {
2907                         println("int numParam = " + methParams.size() + ";");
2908                         print("string paramCls[] = { ");
2909                         for (int i = 0; i < methParams.size(); i++) {
2910                                 String paramTypeC = checkAndGetCplusType(methPrmTypes.get(i));
2911                                 String paramType = checkAndGetCplusArrayType(paramTypeC, methParams.get(i));
2912                                 print("\"" + getEnumType(paramType) + "\"");
2913                                 // Check if this is the last element (don't print a comma)
2914                                 if (i != methParams.size() - 1) {
2915                                         print(", ");
2916                                 }
2917                         }
2918                         println(" };");
2919                         checkAndWriteEnumTypeCplusStub(methParams, methPrmTypes);
2920                         // Generate array of parameter objects
2921                         print("void* paramObj[] = { ");
2922                         for (int i = 0; i < methParams.size(); i++) {
2923                                 print("&" + getEnumParam(methPrmTypes.get(i), getSimpleIdentifier(methParams.get(i)), i));
2924                                 // Check if this is the last element (don't print a comma)
2925                                 if (i != methParams.size() - 1) {
2926                                         print(", ");
2927                                 }
2928                         }
2929                         println(" };");
2930                 }
2931                 // Check if this is "void"
2932                 if (retType.equals("void")) {
2933                         println("void* retObj = NULL;");
2934                         println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
2935                 } else { // We do have a return value
2936                         // Generate array of parameter types
2937                         if (isStructClass(getGenericType(getSimpleArrayType(retType)))) {
2938                                 writeStructReturnCplusStub(getGenericType(getSimpleArrayType(retType)), retType);
2939                         } else {
2940                         // Check if the return value NONPRIMITIVES
2941                                 if (getParamCategory(retType) == ParamCategory.ENUM) {
2942                                         checkAndWriteEnumRetTypeCplusStub(retType);
2943                                 } else {
2944                                         if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
2945                                                 println(checkAndGetCplusType(retType) + " retVal;");
2946                                         else
2947                                                 println(checkAndGetCplusType(retType) + " retVal = " + generateCplusInitializer(retType) + ";");
2948                                         println("void* retObj = &retVal;");
2949                                         println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
2950                                         println("return retVal;");
2951                                 }
2952                         }
2953                 }
2954         }
2955
2956
2957         /**
2958          * HELPER: writePropertiesCplusStub() writes the properties of the stub class
2959          */
2960         private void writePropertiesCplusPermission(String intface) {
2961
2962                 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
2963                 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
2964                         String newIntface = intMeth.getKey();
2965                         int newObjectId = mapNewIntfaceObjId.get(newIntface);
2966                         println("const static int object" + newObjectId + "Id = " + newObjectId + ";");
2967                         println("const static set<int> set" + newObjectId + "Allowed;");
2968                 }
2969         }       
2970
2971         /**
2972          * HELPER: writePropertiesCplusStub() writes the properties of the stub class
2973          */
2974         private void writePropertiesCplusStub(String intface, String newIntface, boolean callbackExist, Set<String> callbackClasses) {
2975
2976                 println("IoTRMICall *rmiCall;");
2977                 //println("IoTRMIObject\t\t\t*rmiObj;");
2978                 println("string address;");
2979                 println("vector<int> ports;\n");
2980                 // Get the object Id
2981                 Integer objId = mapIntfaceObjId.get(intface);
2982                 println("const static int objectId = " + objId + ";");
2983                 mapNewIntfaceObjId.put(newIntface, objId);
2984                 mapIntfaceObjId.put(intface, objId++);
2985                 if (callbackExist) {
2986                 // We assume that each class only has one callback interface for now
2987                         Iterator it = callbackClasses.iterator();
2988                         String callbackType = (String) it.next();
2989                         println("// Callback properties");
2990                         println("IoTRMIObject *rmiObj;");
2991                         println("vector<" + callbackType + "*> vecCallbackObj;");
2992                         println("static int objIdCnt;");
2993                         // Generate permission stuff for callback stubs
2994                         writePropertiesCplusPermission(callbackType);
2995                 }
2996                 println("\n");
2997         }
2998
2999
3000         /**
3001          * HELPER: writeConstructorCplusStub() writes the constructor of the stub class
3002          */
3003         private void writeConstructorCplusStub(String newStubClass, boolean callbackExist, Set<String> callbackClasses) {
3004
3005                 println(newStubClass + 
3006                         "(int _port, const char* _address, int _rev, bool* _bResult, vector<int> _ports) {");
3007                 println("address = _address;");
3008                 println("ports = _ports;");
3009                 println("rmiCall = new IoTRMICall(_port, _address, _rev, _bResult);");
3010                 if (callbackExist) {
3011                         println("objIdCnt = 0;");
3012                         Iterator it = callbackClasses.iterator();
3013                         String callbackType = (String) it.next();
3014                         println("thread th1 (&" + newStubClass + "::___initCallBack, this);");
3015                         println("th1.detach();");
3016                         println("___regCB();");
3017                 }
3018                 println("}\n");
3019         }
3020
3021
3022         /**
3023          * HELPER: writeDeconstructorCplusStub() writes the deconstructor of the stub class
3024          */
3025         private void writeDeconstructorCplusStub(String newStubClass, boolean callbackExist, Set<String> callbackClasses) {
3026
3027                 println("~" + newStubClass + "() {");
3028                 println("if (rmiCall != NULL) {");
3029                 println("delete rmiCall;");
3030                 println("rmiCall = NULL;");
3031                 println("}");
3032                 if (callbackExist) {
3033                 // We assume that each class only has one callback interface for now
3034                         println("if (rmiObj != NULL) {");
3035                         println("delete rmiObj;");
3036                         println("rmiObj = NULL;");
3037                         println("}");
3038                         Iterator it = callbackClasses.iterator();
3039                         String callbackType = (String) it.next();
3040                         println("for(" + callbackType + "* cb : vecCallbackObj) {");
3041                         println("delete cb;");
3042                         println("cb = NULL;");
3043                         println("}");
3044                 }
3045                 println("}");
3046                 println("");
3047         }
3048
3049
3050         /**
3051          * HELPER: writeCplusMethodCallbackPermission() writes permission checks in stub for callbacks
3052          */
3053         private void writeCplusMethodCallbackPermission(String intface) {
3054
3055                 println("int methodId = IoTRMIObject::getMethodId(method);");
3056                 // Get all the different stubs
3057                 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3058                 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3059                         String newIntface = intMeth.getKey();
3060                         int newObjectId = mapNewIntfaceObjId.get(newIntface);
3061                         println("if (set" + newObjectId + "Allowed.find(methodId) == set" + newObjectId + "Allowed.end()) {");
3062                         println("cerr << \"Callback object for " + intface + " is not allowed to access method: \" << methodId;");
3063                         println("exit(-1);");
3064                         println("}");
3065                 }
3066         }
3067
3068
3069         /**
3070          * HELPER: writeInitCallbackCplusStub() writes the initialization of callback
3071          */
3072         private void writeInitCallbackCplusStub(String intface, InterfaceDecl intDecl) {
3073
3074                 println("void ___initCallBack() {");
3075                 println("bool bResult = false;");
3076                 println("rmiObj = new IoTRMIObject(ports[0], &bResult);");
3077                 println("while (true) {");
3078                 println("char* method = rmiObj->getMethodBytes();");
3079                 writeCplusMethodCallbackPermission(intface);
3080                 println("int objId = IoTRMIObject::getObjectId(method);");
3081                 println("if (objId < vecCallbackObj.size()) {   // Check if still within range");
3082                 println(intface + "_CallbackSkeleton* skel = dynamic_cast<" + intface + 
3083                         "_CallbackSkeleton*> (vecCallbackObj.at(objId));");
3084                 println("skel->invokeMethod(rmiObj);");
3085                 println("} else {");
3086                 println("cerr << \"Illegal object Id: \" << to_string(objId);");
3087                 // TODO: perhaps need to change this into "throw" to make it cleaner (allow stack unfolding)
3088                 println("exit(-1);");
3089                 println("}");
3090                 println("}");
3091                 println("}\n");
3092         }
3093
3094
3095         /**
3096          * HELPER: writeInitCallbackSendInfoCplusStub() writes the initialization of callback
3097          */
3098         private void writeInitCallbackSendInfoCplusStub(InterfaceDecl intDecl) {
3099
3100                 // Generate info sending part
3101                 println("void ___regCB() {");
3102                 println("int numParam = 3;");
3103                 String method = "___initCallBack()";
3104                 println("int methodId = " + intDecl.getHelperMethodNumId(method) + ";");
3105                 println("string retType = \"void\";");
3106                 println("string paramCls[] = { \"int\", \"string\", \"int\" };");
3107                 println("int rev = 0;");
3108                 println("void* paramObj[] = { &ports[0], &address, &rev };");
3109                 println("void* retObj = NULL;");
3110                 println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
3111                 println("}\n");
3112         }
3113
3114
3115         /**
3116          * generateCPlusStubClasses() generate stubs based on the methods list in C++
3117          */
3118         public void generateCPlusStubClasses() throws IOException {
3119
3120                 // Create a new directory
3121                 String path = createDirectories(dir, subdir);
3122                 for (String intface : mapIntfacePTH.keySet()) {
3123
3124                         Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3125                         for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3126                                 // Open a new file to write into
3127                                 String newIntface = intMeth.getKey();
3128                                 String newStubClass = newIntface + "_Stub";
3129                                 FileWriter fw = new FileWriter(path + "/" + newStubClass + ".hpp");
3130                                 pw = new PrintWriter(new BufferedWriter(fw));
3131                                 // Write file headers
3132                                 println("#ifndef _" + newStubClass.toUpperCase() + "_HPP__");
3133                                 println("#define _" + newStubClass.toUpperCase() + "_HPP__");
3134                                 println("#include <iostream>");
3135                                 // Find out if there are callback objects
3136                                 Set<String> methods = intMeth.getValue();
3137                                 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
3138                                 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
3139                                 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
3140                                 boolean callbackExist = !callbackClasses.isEmpty();
3141                                 if (callbackExist)      // Need thread library if this has callback
3142                                         println("#include <thread>");
3143                                 println("#include \"" + newIntface + ".hpp\""); println("");            
3144                                 println("using namespace std;"); println("");
3145                                 println("class " + newStubClass + " : public " + newIntface); println("{");
3146                                 println("private:\n");
3147                                 writePropertiesCplusStub(intface, newIntface, callbackExist, callbackClasses);
3148                                 println("public:\n");
3149                                 // Add default constructor and destructor
3150                                 println(newStubClass + "() { }"); println("");
3151                                 writeConstructorCplusStub(newStubClass, callbackExist, callbackClasses);
3152                                 writeDeconstructorCplusStub(newStubClass, callbackExist, callbackClasses);
3153                                 // Write methods
3154                                 writeMethodCplusStub(methods, intDecl, callbackClasses);
3155                                 print("}"); println(";");
3156                                 if (callbackExist)
3157                                         writePermissionInitializationCplus(intface, newStubClass, intDecl);
3158                                 println("#endif");
3159                                 pw.close();
3160                                 System.out.println("IoTCompiler: Generated stub class " + newStubClass + ".hpp...");
3161                         }
3162                 }
3163         }
3164
3165
3166         /**
3167          * HELPER: writePropertiesCplusCallbackStub() writes the properties of the stub class
3168          */
3169         private void writePropertiesCplusCallbackStub(String intface, String newIntface, boolean callbackExist, Set<String> callbackClasses) {
3170
3171                 println("IoTRMICall *rmiCall;");
3172                 // Get the object Id
3173                 println("static int objectId;");
3174                 if (callbackExist) {
3175                 // We assume that each class only has one callback interface for now
3176                         Iterator it = callbackClasses.iterator();
3177                         String callbackType = (String) it.next();
3178                         println("// Callback properties");
3179                         println("IoTRMIObject *rmiObj;");
3180                         println("vector<" + callbackType + "*> vecCallbackObj;");
3181                         println("static int objIdCnt;");
3182                         // TODO: Need to initialize address and ports if we want to have callback-in-callback
3183                         println("string address;");
3184                         println("vector<int> ports;\n");
3185                         writePropertiesCplusPermission(callbackType);
3186                 }
3187                 println("\n");
3188         }
3189
3190
3191         /**
3192          * HELPER: writeConstructorCplusCallbackStub() writes the constructor of the stub class
3193          */
3194         private void writeConstructorCplusCallbackStub(String newStubClass, boolean callbackExist, Set<String> callbackClasses) {
3195
3196                 println(newStubClass + "(IoTRMICall* _rmiCall, int _objectId) {");
3197                 println("objectId = _objectId;");
3198                 println("rmiCall = _rmiCall;");
3199                 if (callbackExist) {
3200                         Iterator it = callbackClasses.iterator();
3201                         String callbackType = (String) it.next();
3202                         println("thread th1 (&" + newStubClass + "::___initCallBack, this);");
3203                         println("th1.detach();");
3204                         println("___regCB();");
3205                 }
3206                 println("}\n");
3207         }
3208
3209
3210         /**
3211          * generateCPlusCallbackStubClasses() generate callback stubs based on the methods list in C++
3212          */
3213         public void generateCPlusCallbackStubClasses() throws IOException {
3214
3215                 // Create a new directory
3216                 String path = createDirectories(dir, subdir);
3217                 for (String intface : mapIntfacePTH.keySet()) {
3218
3219                         Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3220                         for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3221                                 // Open a new file to write into
3222                                 String newIntface = intMeth.getKey();
3223                                 String newStubClass = newIntface + "_CallbackStub";
3224                                 FileWriter fw = new FileWriter(path + "/" + newStubClass + ".hpp");
3225                                 pw = new PrintWriter(new BufferedWriter(fw));
3226                                 // Find out if there are callback objects
3227                                 Set<String> methods = intMeth.getValue();
3228                                 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
3229                                 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
3230                                 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
3231                                 boolean callbackExist = !callbackClasses.isEmpty();
3232                                 // Write file headers
3233                                 println("#ifndef _" + newStubClass.toUpperCase() + "_HPP__");
3234                                 println("#define _" + newStubClass.toUpperCase() + "_HPP__");
3235                                 println("#include <iostream>");
3236                                 if (callbackExist)
3237                                         println("#include <thread>");
3238                                 println("#include \"" + newIntface + ".hpp\""); println("");            
3239                                 println("using namespace std;"); println("");
3240                                 println("class " + newStubClass + " : public " + newIntface); println("{");
3241                                 println("private:\n");
3242                                 writePropertiesCplusCallbackStub(intface, newIntface, callbackExist, callbackClasses);
3243                                 println("public:\n");
3244                                 // Add default constructor and destructor
3245                                 println(newStubClass + "() { }"); println("");
3246                                 writeConstructorCplusCallbackStub(newStubClass, callbackExist, callbackClasses);
3247                                 writeDeconstructorCplusStub(newStubClass, callbackExist, callbackClasses);
3248                                 // Write methods
3249                                 writeMethodCplusStub(methods, intDecl, callbackClasses);
3250                                 println("};");
3251                                 if (callbackExist)
3252                                         writePermissionInitializationCplus(intface, newStubClass, intDecl);
3253                                 println("#endif");
3254                                 pw.close();
3255                                 System.out.println("IoTCompiler: Generated callback stub class " + newIntface + ".hpp...");
3256                         }
3257                 }
3258         }
3259
3260
3261         /**
3262          * HELPER: writePropertiesCplusSkeleton() writes the properties of the skeleton class
3263          */
3264         private void writePropertiesCplusSkeleton(String intface, boolean callbackExist, Set<String> callbackClasses) {
3265
3266                 println(intface + " *mainObj;");
3267                 // Callback
3268                 if (callbackExist) {
3269                         Iterator it = callbackClasses.iterator();
3270                         String callbackType = (String) it.next();
3271                         String exchangeType = checkAndGetParamClass(callbackType);
3272                         println("// Callback properties");
3273                         println("static int objIdCnt;");
3274                         println("vector<" + exchangeType + "*> vecCallbackObj;");
3275                         println("IoTRMICall *rmiCall;");
3276                 }
3277                 println("IoTRMIObject *rmiObj;\n");
3278                 // Keep track of object Ids of all stubs registered to this interface
3279                 writePropertiesCplusPermission(intface);
3280                 println("\n");
3281         }
3282
3283
3284         /**
3285          * HELPER: writePermissionInitializationCplus() writes the initialization of permission set
3286          */
3287         private void writePermissionInitializationCplus(String intface, String newSkelClass, InterfaceDecl intDecl) {
3288
3289                 // Keep track of object Ids of all stubs registered to this interface
3290                 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3291                 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3292                         String newIntface = intMeth.getKey();
3293                         int newObjectId = mapNewIntfaceObjId.get(newIntface);
3294                         print("const set<int> " + newSkelClass + "::set" + newObjectId + "Allowed {");
3295                         Set<String> methodIds = intMeth.getValue();
3296                         int i = 0;
3297                         for (String methodId : methodIds) {
3298                                 int methodNumId = intDecl.getMethodNumId(methodId);
3299                                 print(Integer.toString(methodNumId));
3300                                 // Check if this is the last element (don't print a comma)
3301                                 if (i != methodIds.size() - 1) {
3302                                         print(", ");
3303                                 }
3304                                 i++;
3305                         }
3306                         println(" };");
3307                 }       
3308         }
3309
3310
3311         /**
3312          * HELPER: writeConstructorCplusSkeleton() writes the constructor of the skeleton class
3313          */
3314         private void writeConstructorCplusSkeleton(String newSkelClass, String intface, boolean callbackExist) {
3315
3316                 println(newSkelClass + "(" + intface + " *_mainObj, int _port) {");
3317                 println("bool _bResult = false;");
3318                 println("mainObj = _mainObj;");
3319                 println("rmiObj = new IoTRMIObject(_port, &_bResult);");
3320                 // Callback
3321                 if (callbackExist) {
3322                         println("objIdCnt = 0;");
3323                 }
3324                 //println("set0Allowed = Arrays.asList(object0Permission);");
3325                 println("___waitRequestInvokeMethod();");
3326                 println("}\n");
3327         }
3328
3329
3330         /**
3331          * HELPER: writeDeconstructorCplusSkeleton() writes the deconstructor of the skeleton class
3332          */
3333         private void writeDeconstructorCplusSkeleton(String newSkelClass, boolean callbackExist, Set<String> callbackClasses) {
3334
3335                 println("~" + newSkelClass + "() {");
3336                 println("if (rmiObj != NULL) {");
3337                 println("delete rmiObj;");
3338                 println("rmiObj = NULL;");
3339                 println("}");
3340                 if (callbackExist) {
3341                 // We assume that each class only has one callback interface for now
3342                         println("if (rmiCall != NULL) {");
3343                         println("delete rmiCall;");
3344                         println("rmiCall = NULL;");
3345                         println("}");
3346                         Iterator it = callbackClasses.iterator();
3347                         String callbackType = (String) it.next();
3348                         String exchangeType = checkAndGetParamClass(callbackType);
3349                         println("for(" + exchangeType + "* cb : vecCallbackObj) {");
3350                         println("delete cb;");
3351                         println("cb = NULL;");
3352                         println("}");
3353                 }
3354                 println("}");
3355                 println("");
3356         }
3357
3358
3359         /**
3360          * HELPER: writeStdMethodBodyCplusSkeleton() writes the standard method body in the skeleton class
3361          */
3362         private void writeStdMethodBodyCplusSkeleton(List<String> methParams, String methodId, String methodType) {
3363
3364                 if (methodType.equals("void"))
3365                         print("mainObj->" + methodId + "(");
3366                 else
3367                         print("return mainObj->" + methodId + "(");
3368                 for (int i = 0; i < methParams.size(); i++) {
3369
3370                         print(getSimpleIdentifier(methParams.get(i)));
3371                         // Check if this is the last element (don't print a comma)
3372                         if (i != methParams.size() - 1) {
3373                                 print(", ");
3374                         }
3375                 }
3376                 println(");");
3377         }
3378
3379
3380         /**
3381          * HELPER: writeInitCallbackCplusSkeleton() writes the init callback method for skeleton class
3382          */
3383         private void writeInitCallbackCplusSkeleton(boolean callbackSkeleton) {
3384
3385                 // This is a callback skeleton generation
3386                 if (callbackSkeleton)
3387                         println("void ___regCB(IoTRMIObject* rmiObj) {");
3388                 else
3389                         println("void ___regCB() {");
3390                 println("int numParam = 3;");
3391                 println("int param1 = 0;");
3392                 println("string param2 = \"\";");
3393                 println("int param3 = 0;");
3394                 println("void* paramObj[] = { &param1, &param2, &param3 };");
3395                 println("bool bResult = false;");
3396                 println("rmiCall = new IoTRMICall(param1, param2.c_str(), param3, &bResult);");
3397                 println("}\n");
3398         }
3399
3400
3401         /**
3402          * HELPER: writeMethodCplusSkeleton() writes the method of the skeleton class
3403          */
3404         private void writeMethodCplusSkeleton(Collection<String> methods, InterfaceDecl intDecl, 
3405                         Set<String> callbackClasses, boolean callbackSkeleton) {
3406
3407                 for (String method : methods) {
3408
3409                         List<String> methParams = intDecl.getMethodParams(method);
3410                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
3411                         String methodId = intDecl.getMethodId(method);
3412                         String methodType = checkAndGetCplusType(intDecl.getMethodType(method));
3413                         print(methodType + " " + methodId + "(");
3414                         boolean isCallbackMethod = false;
3415                         String callbackType = null;
3416                         for (int i = 0; i < methParams.size(); i++) {
3417
3418                                 String origParamType = methPrmTypes.get(i);
3419                                 if (callbackClasses.contains(origParamType)) { // Check if this has callback object
3420                                         isCallbackMethod = true;
3421                                         callbackType = origParamType;   
3422                                 }
3423                                 String paramType = checkAndGetParamClass(methPrmTypes.get(i));
3424                                 String methPrmType = checkAndGetCplusType(paramType);
3425                                 String methParamComplete = checkAndGetCplusArray(methPrmType, methParams.get(i));
3426                                 print(methParamComplete);
3427                                 // Check if this is the last element (don't print a comma)
3428                                 if (i != methParams.size() - 1) {
3429                                         print(", ");
3430                                 }
3431                         }
3432                         println(") {");
3433                         // Now, write the body of skeleton!
3434                         writeStdMethodBodyCplusSkeleton(methParams, methodId, intDecl.getMethodType(method));
3435                         println("}\n");
3436                         if (isCallbackMethod)
3437                                 writeInitCallbackCplusSkeleton(callbackSkeleton);
3438                 }
3439         }
3440
3441
3442         /**
3443          * HELPER: writeCallbackCplusNumStubs() writes the numStubs variable
3444          */
3445         private void writeCallbackCplusNumStubs(List<String> methParams, List<String> methPrmTypes, String callbackType) {
3446
3447                 for (int i = 0; i < methParams.size(); i++) {
3448                         String paramType = methPrmTypes.get(i);
3449                         String param = methParams.get(i);
3450                         //if (callbackType.equals(paramType)) {
3451                         if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
3452                                 String exchParamType = checkAndGetParamClass(paramType);
3453                                 // Print array if this is array or list if this is a list of callback objects
3454                                 println("int numStubs" + i + " = 0;");
3455                         }
3456                 }
3457         }
3458
3459
3460         /**
3461          * HELPER: writeCallbackCplusStubGeneration() writes the callback stub generation part
3462          */
3463         private void writeCallbackCplusStubGeneration(List<String> methParams, List<String> methPrmTypes, String callbackType) {
3464
3465                 // Iterate over callback objects
3466                 for (int i = 0; i < methParams.size(); i++) {
3467                         String paramType = methPrmTypes.get(i);
3468                         String param = methParams.get(i);
3469                         // Generate a loop if needed
3470                         if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
3471                                 String exchParamType = checkAndGetParamClass(paramType);
3472                                 if (isArrayOrList(paramType, param)) {
3473                                         println("vector<" + exchParamType + "> stub;");
3474                                         println("for (int objId = 0; objId < numStubs" + i + "; objId++) {");
3475                                         println(exchParamType + "* cb" + i + " = new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt);");
3476                                         println("stub" + i + ".push_back(cb);");
3477                                         println("vecCallbackObj.push_back(cb);");
3478                                         println("objIdCnt++;");
3479                                         println("}");
3480                                 } else {
3481                                         println(exchParamType + "* stub" + i + " = new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt);");
3482                                         println("vecCallbackObj.push_back(stub" + i + ");");
3483                                         println("objIdCnt++;");
3484                                 }
3485                         }
3486                 }
3487         }
3488
3489
3490         /**
3491          * HELPER: checkAndWriteEnumTypeCplusSkeleton() writes the enum type (convert from enum to int)
3492          */
3493         private void checkAndWriteEnumTypeCplusSkeleton(List<String> methParams, List<String> methPrmTypes) {
3494
3495                 // Iterate and find enum declarations
3496                 for (int i = 0; i < methParams.size(); i++) {
3497                         String paramType = methPrmTypes.get(i);
3498                         String param = methParams.get(i);
3499                         String simpleType = getSimpleType(paramType);
3500                         if (isEnumClass(simpleType)) {
3501                         // Check if this is enum type
3502                                 if (isArrayOrList(paramType, param)) {  // An array
3503                                         println("int len" + i + " = paramEnumInt" + i + ".size();");
3504                                         println("vector<" + simpleType + "> paramEnum" + i + "(len" + i + ");");
3505                                         println("for (int i=0; i < len" + i + "; i++) {");
3506                                         println("paramEnum" + i + "[i] = (" + simpleType + ") paramEnumInt" + i + "[i];");
3507                                         println("}");
3508                                 } else {        // Just one element
3509                                         println(simpleType + " paramEnum" + i + ";");
3510                                         println("paramEnum" + i + " = (" + simpleType + ") paramEnumInt" + i + "[0];");
3511                                 }
3512                         }
3513                 }
3514         }
3515
3516
3517         /**
3518          * HELPER: checkAndWriteEnumRetTypeCplusSkeleton() writes the enum return type (convert from enum to int)
3519          */
3520         private void checkAndWriteEnumRetTypeCplusSkeleton(String retType) {
3521
3522                 // Strips off array "[]" for return type
3523                 String pureType = getSimpleArrayType(getSimpleType(retType));
3524                 // Take the inner type of generic
3525                 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
3526                         pureType = getTypeOfGeneric(retType)[0];
3527                 if (isEnumClass(pureType)) {
3528                 // Check if this is enum type
3529                         // Enum decoder
3530                         if (isArrayOrList(retType, retType)) {  // An array
3531                                 println("int retLen = retEnum.size();");
3532                                 println("vector<int> retEnumInt(retLen);");
3533                                 println("for (int i=0; i < retLen; i++) {");
3534                                 println("retEnumInt[i] = (int) retEnum[i];");
3535                                 println("}");
3536                         } else {        // Just one element
3537                                 println("vector<int> retEnumInt(1);");
3538                                 println("retEnumInt[0] = (int) retEnum;");
3539                         }
3540                 }
3541         }
3542
3543
3544         /**
3545          * HELPER: writeMethodHelperReturnCplusSkeleton() writes the return value part in skeleton
3546          */
3547         private void writeMethodInputParameters(List<String> methParams, List<String> methPrmTypes, 
3548                         Set<String> callbackClasses, String methodId) {
3549
3550                 print(methodId + "(");
3551                 for (int i = 0; i < methParams.size(); i++) {
3552                         String paramType = returnGenericCallbackType(methPrmTypes.get(i));
3553                         if (callbackClasses.contains(paramType))
3554                                 print("stub" + i);
3555                         else if (isEnumClass(getSimpleType(paramType))) // Check if this is enum type
3556                                 print("paramEnum" + i);
3557                         else if (isStructClass(getSimpleType(paramType)))       // Struct type
3558                                 print("paramStruct" + i);
3559                         else
3560                                 print(getSimpleIdentifier(methParams.get(i)));
3561                         if (i != methParams.size() - 1) {
3562                                 print(", ");
3563                         }
3564                 }
3565                 println(");");
3566         }
3567
3568
3569         /**
3570          * HELPER: writeMethodHelperReturnCplusSkeleton() writes the return value part in skeleton
3571          */
3572         private void writeMethodHelperReturnCplusSkeleton(InterfaceDecl intDecl, List<String> methParams,
3573                         List<String> methPrmTypes, String method, boolean isCallbackMethod, String callbackType,
3574                         String methodId, Set<String> callbackClasses) {
3575
3576                 println("rmiObj->getMethodParams(paramCls, numParam, paramObj);");
3577                 if (isCallbackMethod)
3578                         writeCallbackCplusStubGeneration(methParams, methPrmTypes, callbackType);
3579                 checkAndWriteEnumTypeCplusSkeleton(methParams, methPrmTypes);
3580                 writeStructMembersInitCplusSkeleton(intDecl, methParams, methPrmTypes, method);
3581                 // Check if this is "void"
3582                 String retType = intDecl.getMethodType(method);
3583                 // Check if this is "void"
3584                 if (retType.equals("void")) {
3585                         writeMethodInputParameters(methParams, methPrmTypes, callbackClasses, methodId);
3586                 } else { // We do have a return value
3587                         if (isEnumClass(getSimpleArrayType(getSimpleType(retType)))) // Enum type
3588                                 print(checkAndGetCplusType(retType) + " retEnum = ");
3589                         else if (isStructClass(getSimpleArrayType(getSimpleType(retType)))) // Struct type
3590                                 print(checkAndGetCplusType(retType) + " retStruct = ");
3591                         else
3592                                 print(checkAndGetCplusType(retType) + " retVal = ");
3593                         writeMethodInputParameters(methParams, methPrmTypes, callbackClasses, methodId);
3594                         checkAndWriteEnumRetTypeCplusSkeleton(retType);
3595                         if (isStructClass(getSimpleArrayType(getSimpleType(retType)))) // Struct type
3596                                 writeStructReturnCplusSkeleton(getSimpleArrayType(getSimpleType(retType)), retType);
3597                         if (isEnumClass(getSimpleArrayType(getSimpleType(retType)))) // Enum type
3598                                 println("void* retObj = &retEnumInt;");
3599                         else
3600                                 if (!isStructClass(getSimpleArrayType(getSimpleType(retType)))) // Struct type
3601                                         println("void* retObj = &retVal;");
3602                         String retTypeC = checkAndGetCplusType(retType);
3603                         if (isStructClass(getSimpleArrayType(getSimpleType(retType)))) // Struct type
3604                                 println("rmiObj->sendReturnObj(retObj, retCls, numRetObj);");
3605                         else
3606                                 println("rmiObj->sendReturnObj(retObj, \"" + getEnumType(checkAndGetCplusArrayType(retTypeC)) + "\");");
3607                 }
3608         }
3609
3610
3611         /**
3612          * HELPER: writeStdMethodHelperBodyCplusSkeleton() writes the standard method body helper in the skeleton class
3613          */
3614         private void writeStdMethodHelperBodyCplusSkeleton(InterfaceDecl intDecl, List<String> methParams,
3615                         List<String> methPrmTypes, String method, String methodId, Set<String> callbackClasses) {
3616
3617                 // Generate array of parameter types
3618                 boolean isCallbackMethod = false;
3619                 String callbackType = null;
3620                 print("string paramCls[] = { ");
3621                 for (int i = 0; i < methParams.size(); i++) {
3622                         String paramType = returnGenericCallbackType(methPrmTypes.get(i));
3623                         if (callbackClasses.contains(paramType)) {
3624                                 isCallbackMethod = true;
3625                                 callbackType = paramType;
3626                                 print("\"int\"");
3627                         } else {        // Generate normal classes if it's not a callback object
3628                                 String paramTypeC = checkAndGetCplusType(methPrmTypes.get(i));
3629                                 String prmType = checkAndGetCplusArrayType(paramTypeC, methParams.get(i));
3630                                 print("\"" + getEnumType(prmType) + "\"");
3631                         }
3632                         if (i != methParams.size() - 1) {
3633                                 print(", ");
3634                         }
3635                 }
3636                 println(" };");
3637                 println("int numParam = " + methParams.size() + ";");
3638                 if (isCallbackMethod)
3639                         writeCallbackCplusNumStubs(methParams, methPrmTypes, callbackType);
3640                 // Generate parameters
3641                 for (int i = 0; i < methParams.size(); i++) {
3642                         String paramType = returnGenericCallbackType(methPrmTypes.get(i));
3643                         if (!callbackClasses.contains(paramType)) {
3644                                 String methPrmType = checkAndGetCplusType(methPrmTypes.get(i));
3645                                 if (isEnumClass(getSimpleType(methPrmType))) {  // Check if this is enum type
3646                                         println("vector<int> paramEnumInt" + i + ";");
3647                                 } else {
3648                                         String methParamComplete = checkAndGetCplusArray(methPrmType, methParams.get(i));
3649                                         println(methParamComplete + ";");
3650                                 }
3651                         }
3652                 }
3653                 // Generate array of parameter objects
3654                 print("void* paramObj[] = { ");
3655                 for (int i = 0; i < methParams.size(); i++) {
3656                         String paramType = returnGenericCallbackType(methPrmTypes.get(i));
3657                         if (callbackClasses.contains(paramType))
3658                                 print("&numStubs" + i);
3659                         else if (isEnumClass(getSimpleType(paramType))) // Check if this is enum type
3660                                 print("&paramEnumInt" + i);
3661                         else
3662                                 print("&" + getSimpleIdentifier(methParams.get(i)));
3663                         if (i != methParams.size() - 1) {
3664                                 print(", ");
3665                         }
3666                 }
3667                 println(" };");
3668                 // Write the return value part
3669                 writeMethodHelperReturnCplusSkeleton(intDecl, methParams, methPrmTypes, method, isCallbackMethod, 
3670                         callbackType, methodId, callbackClasses);
3671         }
3672
3673
3674         /**
3675          * HELPER: writeStructMembersCplusSkeleton() writes parameters of struct
3676          */
3677         private void writeStructMembersCplusSkeleton(String simpleType, String paramType, 
3678                         String param, String method, InterfaceDecl intDecl, int iVar) {
3679
3680                 // Get the struct declaration for this struct and generate initialization code
3681                 StructDecl structDecl = getStructDecl(simpleType);
3682                 List<String> memTypes = structDecl.getMemberTypes(simpleType);
3683                 List<String> members = structDecl.getMembers(simpleType);
3684                 int methodNumId = intDecl.getMethodNumId(method);
3685                 String counter = "struct" + methodNumId + "Size" + iVar;
3686                 if (isArrayOrList(param, paramType)) {  // An array or list
3687                         println("for(int i = 0; i < " + counter + "; i++) {");
3688                 }
3689                 // Set up variables
3690                 if (isArrayOrList(param, paramType)) {  // An array or list
3691                         for (int i = 0; i < members.size(); i++) {
3692                                 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
3693                                 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
3694                                 println(getSimpleType(getEnumType(prmType)) + " param" + i + "[" + counter + "];");
3695                         }
3696                 } else {        // Just one struct element
3697                         for (int i = 0; i < members.size(); i++) {
3698                                 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
3699                                 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
3700                                 println(getSimpleType(getEnumType(prmType)) + " param" + i + ";");
3701                         }
3702                 }
3703                 println("int pos = 0;");
3704                 if (isArrayOrList(param, paramType)) {  // An array or list
3705                         println("for(int i = 0; i < retLen; i++) {");
3706                         for (int i = 0; i < members.size(); i++) {
3707                                 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
3708                                 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
3709                                 println("paramCls[pos] = \"" + getSimpleType(getEnumType(prmType)) + "\";");
3710                                 println("paramObj[pos++] = &param" + i + "[i];");
3711                         }
3712                         println("}");
3713                 } else {        // Just one struct element
3714                         for (int i = 0; i < members.size(); i++) {
3715                                 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
3716                                 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
3717                                 println("paramCls[pos] = \"" + getSimpleType(getEnumType(prmType)) + "\";");
3718                                 println("paramObj[pos++] = &param" + i + ";");
3719                         }
3720                 }
3721         }
3722
3723
3724         /**
3725          * HELPER: writeStructMembersInitCplusSkeleton() writes parameters of struct
3726          */
3727         private void writeStructMembersInitCplusSkeleton(InterfaceDecl intDecl, List<String> methParams,
3728                         List<String> methPrmTypes, String method) {
3729
3730                 for (int i = 0; i < methParams.size(); i++) {
3731                         String paramType = methPrmTypes.get(i);
3732                         String param = methParams.get(i);
3733                         String simpleType = getGenericType(paramType);
3734                         if (isStructClass(simpleType)) {
3735                                 int methodNumId = intDecl.getMethodNumId(method);
3736                                 String counter = "struct" + methodNumId + "Size" + i;
3737                                 // Declaration
3738                                 if (isArrayOrList(param, paramType)) {  // An array or list
3739                                         println("vector<" + simpleType + "> paramStruct" + i + ";");
3740                                 } else
3741                                         println(simpleType + " paramStruct" + i + ";");
3742                                 // Initialize members
3743                                 StructDecl structDecl = getStructDecl(simpleType);
3744                                 List<String> members = structDecl.getMembers(simpleType);
3745                                 List<String> memTypes = structDecl.getMemberTypes(simpleType);
3746                                 if (isArrayOrList(param, paramType)) {  // An array or list
3747                                         println("for(int i = 0; i < " + counter + "; i++) {");
3748                                         for (int j = 0; j < members.size(); j++) {
3749                                                 print("paramStruct" + i + "[i]." + getSimpleIdentifier(members.get(j)));
3750                                                 println(" = param" + j + "[i];");
3751                                         }
3752                                         println("}");
3753                                 } else {        // Just one struct element
3754                                         for (int j = 0; j < members.size(); j++) {
3755                                                 print("paramStruct" + i + "." + getSimpleIdentifier(members.get(j)));
3756                                                 println(" = param" + j + ";");
3757                                         }
3758                                 }
3759                         }
3760                 }
3761         }
3762
3763
3764         /**
3765          * HELPER: writeStructReturnCplusSkeleton() writes parameters if struct is present
3766          */
3767         private void writeStructReturnCplusSkeleton(String simpleType, String retType) {
3768
3769                 // Minimum retLen is 1 if this is a single struct object
3770                 if (isArrayOrList(retType, retType))
3771                         println("int retLen = retStruct.size();");
3772                 else    // Just single struct object
3773                         println("int retLen = 1;");
3774                 println("void* retLenObj = &retLen;");
3775                 println("rmiObj->sendReturnObj(retLenObj, \"int\");");
3776                 int numMem = getNumOfMembers(simpleType);
3777                 println("int numRetObj = " + numMem + "*retLen;");
3778                 println("string retCls[numRetObj];");
3779                 println("void* retObj[numRetObj];");
3780                 println("int retPos = 0;");
3781                 // Get the struct declaration for this struct and generate initialization code
3782                 StructDecl structDecl = getStructDecl(simpleType);
3783                 List<String> memTypes = structDecl.getMemberTypes(simpleType);
3784                 List<String> members = structDecl.getMembers(simpleType);
3785                 if (isArrayOrList(retType, retType)) {  // An array or list
3786                         println("for(int i = 0; i < retLen; i++) {");
3787                         for (int i = 0; i < members.size(); i++) {
3788                                 String paramTypeC = checkAndGetCplusType(memTypes.get(i));
3789                                 String prmType = checkAndGetCplusArrayType(paramTypeC, members.get(i));
3790                                 println("retCls[retPos] = \"" + getSimpleType(getEnumType(prmType)) + "\";");
3791                                 print("retObj[retPos++] = &retStruct[i].");
3792                                 print(getEnumParam(memTypes.get(i), getSimpleIdentifier(members.get(i)), i));
3793                                 println(";");
3794                         }
3795                         println("}");
3796                 } else {        // Just one struct element
3797                         for (int i = 0; i < members.size(); i++) {
3798                                 String paramTypeC = checkAndGetCplusType(memTypes.get(i));
3799                                 String prmType = checkAndGetCplusArrayType(paramTypeC, members.get(i));
3800                                 println("retCls[retPos] = \"" + getSimpleType(getEnumType(prmType)) + "\";");
3801                                 print("retObj[retPos++] = &retStruct.");
3802                                 print(getEnumParam(memTypes.get(i), getSimpleIdentifier(members.get(i)), i));
3803                                 println(";");
3804                         }
3805                 }
3806
3807         }
3808
3809
3810         /**
3811          * HELPER: writeMethodHelperStructCplusSkeleton() writes the struct in skeleton
3812          */
3813         private void writeMethodHelperStructCplusSkeleton(InterfaceDecl intDecl, List<String> methParams,
3814                         List<String> methPrmTypes, String method, String methodId, Set<String> callbackClasses) {
3815
3816                 // Generate array of parameter objects
3817                 boolean isCallbackMethod = false;
3818                 String callbackType = null;
3819                 print("int numParam = ");
3820                 writeLengthStructParamClassSkeleton(methParams, methPrmTypes, method, intDecl);
3821                 println(";");
3822                 println("string paramCls[numParam];");
3823                 println("void* paramObj[numParam];");
3824                 // Iterate again over the parameters
3825                 for (int i = 0; i < methParams.size(); i++) {
3826                         String paramType = methPrmTypes.get(i);
3827                         String param = methParams.get(i);
3828                         String simpleType = getGenericType(paramType);
3829                         if (isStructClass(simpleType)) {
3830                                 writeStructMembersCplusSkeleton(simpleType, paramType, param, method, intDecl, i);
3831                         } else {
3832                                 String prmType = returnGenericCallbackType(methPrmTypes.get(i));
3833                                 if (callbackClasses.contains(prmType)) {
3834                                         isCallbackMethod = true;
3835                                         callbackType = paramType;
3836                                         writeCallbackCplusNumStubs(methParams, methPrmTypes, callbackType);
3837                                         println("paramCls[pos] = \"int\";");
3838                                         println("paramObj[pos++] = &numStubs" + i + ";");
3839                                 } else {        // Generate normal classes if it's not a callback object
3840                                         String paramTypeC = checkAndGetCplusType(methPrmTypes.get(i));
3841                                         String prmTypeC = checkAndGetCplusArrayType(paramTypeC, methParams.get(i));
3842                                         if (isEnumClass(getSimpleType(paramTypeC))) {   // Check if this is enum type
3843                                                 println("vector<int> paramEnumInt" + i + ";");
3844                                         } else {
3845                                                 String methParamComplete = checkAndGetCplusArray(paramTypeC, methParams.get(i));
3846                                                 println(methParamComplete + ";");
3847                                         }
3848                                         println("paramCls[pos] = \"" + getEnumType(prmTypeC) + "\";");
3849                                         if (isEnumClass(getSimpleType(paramType)))      // Check if this is enum type
3850                                                 println("paramObj[pos++] = &paramEnumInt" + i);
3851                                         else
3852                                                 println("paramObj[pos++] = &" + getSimpleIdentifier(methParams.get(i)) + ";");
3853                                 }
3854                         }
3855                 }
3856                 // Write the return value part
3857                 writeMethodHelperReturnCplusSkeleton(intDecl, methParams, methPrmTypes, method, isCallbackMethod, 
3858                         callbackType, methodId, callbackClasses);
3859         }
3860
3861
3862         /**
3863          * HELPER: writeMethodHelperCplusSkeleton() writes the method helper of the skeleton class
3864          */
3865         private void writeMethodHelperCplusSkeleton(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
3866
3867                 // Use this set to handle two same methodIds
3868                 Set<String> uniqueMethodIds = new HashSet<String>();
3869                 for (String method : methods) {
3870
3871                         List<String> methParams = intDecl.getMethodParams(method);
3872                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
3873                         if (isStructPresent(methParams, methPrmTypes)) {        // Treat struct differently
3874                                 String methodId = intDecl.getMethodId(method);
3875                                 print("void ___");
3876                                 String helperMethod = methodId;
3877                                 if (uniqueMethodIds.contains(methodId))
3878                                         helperMethod = helperMethod + intDecl.getMethodNumId(method);
3879                                 else
3880                                         uniqueMethodIds.add(methodId);
3881                                 String retType = intDecl.getMethodType(method);
3882                                 print(helperMethod + "(");
3883                                 boolean begin = true;
3884                                 for (int i = 0; i < methParams.size(); i++) { // Print size variables
3885                                         String paramType = methPrmTypes.get(i);
3886                                         String param = methParams.get(i);
3887                                         String simpleType = getSimpleType(paramType);
3888                                         if (isStructClass(simpleType)) {
3889                                                 if (!begin) {   // Generate comma for not the beginning variable
3890                                                         print(", "); begin = false;
3891                                                 }
3892                                                 int methodNumId = intDecl.getMethodNumId(method);
3893                                                 print("int struct" + methodNumId + "Size" + i);
3894                                         }
3895                                 }
3896                                 println(") {");
3897                                 writeMethodHelperStructCplusSkeleton(intDecl, methParams, methPrmTypes, method, methodId, callbackClasses);
3898                                 println("}\n");
3899                         } else {
3900                                 String methodId = intDecl.getMethodId(method);
3901                                 print("void ___");
3902                                 String helperMethod = methodId;
3903                                 if (uniqueMethodIds.contains(methodId))
3904                                         helperMethod = helperMethod + intDecl.getMethodNumId(method);
3905                                 else
3906                                         uniqueMethodIds.add(methodId);
3907                                 // Check if this is "void"
3908                                 String retType = intDecl.getMethodType(method);
3909                                 println(helperMethod + "() {");
3910                                 // Now, write the helper body of skeleton!
3911                                 writeStdMethodHelperBodyCplusSkeleton(intDecl, methParams, methPrmTypes, method, methodId, callbackClasses);
3912                                 println("}\n");
3913                         }
3914                 }
3915                 // Write method helper for structs
3916                 writeMethodHelperStructSetupCplusSkeleton(methods, intDecl);
3917         }
3918
3919
3920         /**
3921          * HELPER: writeMethodHelperStructSetupCplusSkeleton() writes the method helper of the struct in skeleton class
3922          */
3923         private void writeMethodHelperStructSetupCplusSkeleton(Collection<String> methods, 
3924                         InterfaceDecl intDecl) {
3925
3926                 // Use this set to handle two same methodIds
3927                 for (String method : methods) {
3928
3929                         List<String> methParams = intDecl.getMethodParams(method);
3930                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
3931                         // Check for params with structs
3932                         for (int i = 0; i < methParams.size(); i++) {
3933                                 String paramType = methPrmTypes.get(i);
3934                                 String param = methParams.get(i);
3935                                 String simpleType = getSimpleType(paramType);
3936                                 if (isStructClass(simpleType)) {
3937                                         int methodNumId = intDecl.getMethodNumId(method);
3938                                         print("int ___");
3939                                         String helperMethod = methodNumId + "struct" + i;
3940                                         println(helperMethod + "() {");
3941                                         // Now, write the helper body of skeleton!
3942                                         println("string paramCls[] = { \"int\" };");
3943                                         println("int numParam = 1;");
3944                                         println("int param0 = 0;");
3945                                         println("void* paramObj[] = { &param0 };");
3946                                         println("rmiObj->getMethodParams(paramCls, numParam, paramObj);");
3947                                         println("return param0;");
3948                                         println("}\n");
3949                                 }
3950                         }
3951                 }
3952         }
3953
3954
3955         /**
3956          * HELPER: writeMethodHelperStructSetupCplusCallbackSkeleton() writes the method helper of the struct in skeleton class
3957          */
3958         private void writeMethodHelperStructSetupCplusCallbackSkeleton(Collection<String> methods, 
3959                         InterfaceDecl intDecl) {
3960
3961                 // Use this set to handle two same methodIds
3962                 for (String method : methods) {
3963
3964                         List<String> methParams = intDecl.getMethodParams(method);
3965                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
3966                         // Check for params with structs
3967                         for (int i = 0; i < methParams.size(); i++) {
3968                                 String paramType = methPrmTypes.get(i);
3969                                 String param = methParams.get(i);
3970                                 String simpleType = getSimpleType(paramType);
3971                                 if (isStructClass(simpleType)) {
3972                                         int methodNumId = intDecl.getMethodNumId(method);
3973                                         print("int ___");
3974                                         String helperMethod = methodNumId + "struct" + i;
3975                                         println(helperMethod + "(IoTRMIObject* rmiObj) {");
3976                                         // Now, write the helper body of skeleton!
3977                                         println("string paramCls[] = { \"int\" };");
3978                                         println("int numParam = 1;");
3979                                         println("int param0 = 0;");
3980                                         println("void* paramObj[] = { &param0 };");
3981                                         println("rmiObj->getMethodParams(paramCls, numParam, paramObj);");
3982                                         println("return param0;");
3983                                         println("}\n");
3984                                 }
3985                         }
3986                 }
3987         }
3988
3989
3990         /**
3991          * HELPER: writeCplusMethodPermission() writes permission checks in skeleton
3992          */
3993         private void writeCplusMethodPermission(String intface) {
3994
3995                 // Get all the different stubs
3996                 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3997                 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3998                         String newIntface = intMeth.getKey();
3999                         int newObjectId = mapNewIntfaceObjId.get(newIntface);
4000                         println("if (_objectId == object" + newObjectId + "Id) {");
4001                         println("if (set" + newObjectId + "Allowed.find(methodId) == set" + newObjectId + "Allowed.end()) {");
4002                         println("cerr << \"Object with object Id: \" << _objectId << \"  is not allowed to access method: \" << methodId << endl;");
4003                         println("exit(-1);");
4004                         println("}");
4005                         println("else {");
4006                         println("cerr << \"Object Id: \" << _objectId << \" not recognized!\" << endl;");
4007                         println("exit(-1);");
4008                         println("}");
4009                         println("}");
4010                 }
4011         }
4012
4013
4014         /**
4015          * HELPER: writeCplusWaitRequestInvokeMethod() writes the main loop of the skeleton class
4016          */
4017         private void writeCplusWaitRequestInvokeMethod(Collection<String> methods, InterfaceDecl intDecl, boolean callbackExist, String intface) {
4018
4019                 // Use this set to handle two same methodIds
4020                 Set<String> uniqueMethodIds = new HashSet<String>();
4021                 println("void ___waitRequestInvokeMethod() {");
4022                 // Write variables here if we have callbacks or enums or structs
4023                 writeCountVarStructSkeleton(methods, intDecl);
4024                 println("while (true) {");
4025                 println("rmiObj->getMethodBytes();");
4026                 println("int _objectId = rmiObj->getObjectId();");
4027                 println("int methodId = rmiObj->getMethodId();");
4028                 // Generate permission check
4029                 writeCplusMethodPermission(intface);
4030                 println("switch (methodId) {");
4031                 // Print methods and method Ids
4032                 for (String method : methods) {
4033                         String methodId = intDecl.getMethodId(method);
4034                         int methodNumId = intDecl.getMethodNumId(method);
4035                         print("case " + methodNumId + ": ___");
4036                         String helperMethod = methodId;
4037                         if (uniqueMethodIds.contains(methodId))
4038                                 helperMethod = helperMethod + methodNumId;
4039                         else
4040                                 uniqueMethodIds.add(methodId);
4041                         print(helperMethod + "(");
4042                         writeInputCountVarStructSkeleton(method, intDecl);
4043                         println("); break;");
4044                 }
4045                 String method = "___initCallBack()";
4046                 // Print case -9999 (callback handler) if callback exists
4047                 if (callbackExist) {
4048                         int methodId = intDecl.getHelperMethodNumId(method);
4049                         println("case " + methodId + ": ___regCB(); break;");
4050                 }
4051                 writeMethodCallStructSkeleton(methods, intDecl);
4052                 println("default: ");
4053                 println("cerr << \"Method Id \" << methodId << \" not recognized!\" << endl;");
4054                 println("throw exception();");
4055                 println("}");
4056                 println("}");
4057                 println("}\n");
4058         }
4059
4060
4061         /**
4062          * generateCplusSkeletonClass() generate skeletons based on the methods list in C++
4063          */
4064         public void generateCplusSkeletonClass() throws IOException {
4065
4066                 // Create a new directory
4067                 String path = createDirectories(dir, subdir);
4068                 for (String intface : mapIntfacePTH.keySet()) {
4069                         // Open a new file to write into
4070                         String newSkelClass = intface + "_Skeleton";
4071                         FileWriter fw = new FileWriter(path + "/" + newSkelClass + ".hpp");
4072                         pw = new PrintWriter(new BufferedWriter(fw));
4073                         // Write file headers
4074                         println("#ifndef _" + newSkelClass.toUpperCase() + "_HPP__");
4075                         println("#define _" + newSkelClass.toUpperCase() + "_HPP__");
4076                         println("#include <iostream>");
4077                         println("#include \"" + intface + ".hpp\"\n");
4078                         // Pass in set of methods and get import classes
4079                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4080                         InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
4081                         List<String> methods = intDecl.getMethods();
4082                         Set<String> includeClasses = getIncludeClasses(methods, intDecl, intface, true);
4083                         List<String> stdIncludeClasses = getStandardCplusIncludeClasses();
4084                         List<String> allIncludeClasses = getAllLibClasses(stdIncludeClasses, includeClasses);
4085                         printIncludeStatements(allIncludeClasses); println("");
4086                         println("using namespace std;\n");
4087                         // Find out if there are callback objects
4088                         Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
4089                         boolean callbackExist = !callbackClasses.isEmpty();
4090                         // Write class header
4091                         println("class " + newSkelClass + " : public " + intface); println("{");
4092                         println("private:\n");
4093                         // Write properties
4094                         writePropertiesCplusSkeleton(intface, callbackExist, callbackClasses);
4095                         println("public:\n");
4096                         // Write constructor
4097                         writeConstructorCplusSkeleton(newSkelClass, intface, callbackExist);
4098                         // Write deconstructor
4099                         writeDeconstructorCplusSkeleton(newSkelClass, callbackExist, callbackClasses);
4100                         // Write methods
4101                         writeMethodCplusSkeleton(methods, intDecl, callbackClasses, false);
4102                         // Write method helper
4103                         writeMethodHelperCplusSkeleton(methods, intDecl, callbackClasses);
4104                         // Write waitRequestInvokeMethod() - main loop
4105                         writeCplusWaitRequestInvokeMethod(methods, intDecl, callbackExist, intface);
4106                         println("};");
4107                         writePermissionInitializationCplus(intface, newSkelClass, intDecl);
4108                         println("#endif");
4109                         pw.close();
4110                         System.out.println("IoTCompiler: Generated skeleton class " + newSkelClass + ".hpp...");
4111                 }
4112         }
4113
4114
4115         /**
4116          * HELPER: writePropertiesCplusCallbackSkeleton() writes the properties of the callback skeleton class
4117          */
4118         private void writePropertiesCplusCallbackSkeleton(String intface, boolean callbackExist, Set<String> callbackClasses) {
4119
4120                 println(intface + " *mainObj;");
4121                 // Keep track of object Ids of all stubs registered to this interface
4122                 println("static int objectId;");
4123                 // Callback
4124                 if (callbackExist) {
4125                         Iterator it = callbackClasses.iterator();
4126                         String callbackType = (String) it.next();
4127                         String exchangeType = checkAndGetParamClass(callbackType);
4128                         println("// Callback properties");
4129                         println("IoTRMICall* rmiCall;");
4130                         println("vector<" + exchangeType + "*> vecCallbackObj;");
4131                         println("static int objIdCnt;");
4132                 }
4133                 println("\n");
4134         }
4135
4136
4137         /**
4138          * HELPER: writeConstructorCplusCallbackSkeleton() writes the constructor of the skeleton class
4139          */
4140         private void writeConstructorCplusCallbackSkeleton(String newSkelClass, String intface, boolean callbackExist) {
4141
4142                 println(newSkelClass + "(" + intface + " *_mainObj, int _objectId) {");
4143                 println("mainObj = _mainObj;");
4144                 println("objectId = _objectId;");
4145                 // Callback
4146                 if (callbackExist) {
4147                         println("objIdCnt = 0;");
4148                 }
4149                 println("}\n");
4150         }
4151
4152
4153         /**
4154          * HELPER: writeDeconstructorCplusStub() writes the deconstructor of the stub class
4155          */
4156         private void writeDeconstructorCplusCallbackSkeleton(String newStubClass, boolean callbackExist, 
4157                         Set<String> callbackClasses) {
4158
4159                 println("~" + newStubClass + "() {");
4160                 if (callbackExist) {
4161                 // We assume that each class only has one callback interface for now
4162                         println("if (rmiCall != NULL) {");
4163                         println("delete rmiCall;");
4164                         println("rmiCall = NULL;");
4165                         println("}");
4166                         Iterator it = callbackClasses.iterator();
4167                         String callbackType = (String) it.next();
4168                         String exchangeType = checkAndGetParamClass(callbackType);
4169                         println("for(" + exchangeType + "* cb : vecCallbackObj) {");
4170                         println("delete cb;");
4171                         println("cb = NULL;");
4172                         println("}");
4173                 }
4174                 println("}");
4175                 println("");
4176         }
4177
4178
4179         /**
4180          * HELPER: writeMethodHelperCplusCallbackSkeleton() writes the method helper of the callback skeleton class
4181          */
4182         private void writeMethodHelperCplusCallbackSkeleton(Collection<String> methods, InterfaceDecl intDecl, 
4183                         Set<String> callbackClasses) {
4184
4185                 // Use this set to handle two same methodIds
4186                 Set<String> uniqueMethodIds = new HashSet<String>();
4187                 for (String method : methods) {
4188
4189                         List<String> methParams = intDecl.getMethodParams(method);
4190                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4191                         if (isStructPresent(methParams, methPrmTypes)) {        // Treat struct differently
4192                                 String methodId = intDecl.getMethodId(method);
4193                                 print("void ___");
4194                                 String helperMethod = methodId;
4195                                 if (uniqueMethodIds.contains(methodId))
4196                                         helperMethod = helperMethod + intDecl.getMethodNumId(method);
4197                                 else
4198                                         uniqueMethodIds.add(methodId);
4199                                 String retType = intDecl.getMethodType(method);
4200                                 print(helperMethod + "(");
4201                                 boolean begin = true;
4202                                 for (int i = 0; i < methParams.size(); i++) { // Print size variables
4203                                         String paramType = methPrmTypes.get(i);
4204                                         String param = methParams.get(i);
4205                                         String simpleType = getSimpleType(paramType);
4206                                         if (isStructClass(simpleType)) {
4207                                                 if (!begin) {   // Generate comma for not the beginning variable
4208                                                         print(", "); begin = false;
4209                                                 }
4210                                                 int methodNumId = intDecl.getMethodNumId(method);
4211                                                 print("int struct" + methodNumId + "Size" + i);
4212                                         }
4213                                 }
4214                                 println(", IoTRMIObject* rmiObj) {");
4215                                 writeMethodHelperStructCplusSkeleton(intDecl, methParams, methPrmTypes, method, methodId, callbackClasses);
4216                                 println("}\n");
4217                         } else {
4218                                 String methodId = intDecl.getMethodId(method);
4219                                 print("void ___");
4220                                 String helperMethod = methodId;
4221                                 if (uniqueMethodIds.contains(methodId))
4222                                         helperMethod = helperMethod + intDecl.getMethodNumId(method);
4223                                 else
4224                                         uniqueMethodIds.add(methodId);
4225                                 // Check if this is "void"
4226                                 String retType = intDecl.getMethodType(method);
4227                                 println(helperMethod + "(IoTRMIObject* rmiObj) {");
4228                                 // Now, write the helper body of skeleton!
4229                                 writeStdMethodHelperBodyCplusSkeleton(intDecl, methParams, methPrmTypes, method, methodId, callbackClasses);
4230                                 println("}\n");
4231                         }
4232                 }
4233                 // Write method helper for structs
4234                 writeMethodHelperStructSetupCplusCallbackSkeleton(methods, intDecl);
4235         }
4236
4237
4238         /**
4239          * HELPER: writeCplusCallbackWaitRequestInvokeMethod() writes the main loop of the skeleton class
4240          */
4241         private void writeCplusCallbackWaitRequestInvokeMethod(Collection<String> methods, InterfaceDecl intDecl, 
4242                         boolean callbackExist) {
4243
4244                 // Use this set to handle two same methodIds
4245                 Set<String> uniqueMethodIds = new HashSet<String>();
4246                 println("void invokeMethod(IoTRMIObject* rmiObj) {");
4247                 // Write variables here if we have callbacks or enums or structs
4248                 writeCountVarStructSkeleton(methods, intDecl);
4249                 // Write variables here if we have callbacks or enums or structs
4250                 println("int methodId = rmiObj->getMethodId();");
4251                 // TODO: code the permission check here!
4252                 println("switch (methodId) {");
4253                 // Print methods and method Ids
4254                 for (String method : methods) {
4255                         String methodId = intDecl.getMethodId(method);
4256                         int methodNumId = intDecl.getMethodNumId(method);
4257                         print("case " + methodNumId + ": ___");
4258                         String helperMethod = methodId;
4259                         if (uniqueMethodIds.contains(methodId))
4260                                 helperMethod = helperMethod + methodNumId;
4261                         else
4262                                 uniqueMethodIds.add(methodId);
4263                         print(helperMethod + "(");
4264                         if (writeInputCountVarStructSkeleton(method, intDecl))
4265                                 println(", rmiObj); break;");
4266                         else
4267                                 println("rmiObj); break;");
4268                 }
4269                 String method = "___initCallBack()";
4270                 // Print case -9999 (callback handler) if callback exists
4271                 if (callbackExist) {
4272                         int methodId = intDecl.getHelperMethodNumId(method);
4273                         println("case " + methodId + ": ___regCB(rmiObj); break;");
4274                 }
4275                 writeMethodCallStructCallbackSkeleton(methods, intDecl);
4276                 println("default: ");
4277                 println("cerr << \"Method Id \" << methodId << \" not recognized!\" << endl;");
4278                 println("throw exception();");
4279                 println("}");
4280                 println("}\n");
4281         }
4282
4283
4284
4285         /**
4286          * generateCplusCallbackSkeletonClass() generate callback skeletons based on the methods list in C++
4287          */
4288         public void generateCplusCallbackSkeletonClass() throws IOException {
4289
4290                 // Create a new directory
4291                 String path = createDirectories(dir, subdir);
4292                 for (String intface : mapIntfacePTH.keySet()) {
4293                         // Open a new file to write into
4294                         String newSkelClass = intface + "_CallbackSkeleton";
4295                         FileWriter fw = new FileWriter(path + "/" + newSkelClass + ".hpp");
4296                         pw = new PrintWriter(new BufferedWriter(fw));
4297                         // Write file headers
4298                         println("#ifndef _" + newSkelClass.toUpperCase() + "_HPP__");
4299                         println("#define _" + newSkelClass.toUpperCase() + "_HPP__");
4300                         println("#include <iostream>");
4301                         println("#include \"" + intface + ".hpp\"\n");
4302                         // Pass in set of methods and get import classes
4303                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4304                         InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
4305                         List<String> methods = intDecl.getMethods();
4306                         Set<String> includeClasses = getIncludeClasses(methods, intDecl, intface, true);
4307                         List<String> stdIncludeClasses = getStandardCplusIncludeClasses();
4308                         List<String> allIncludeClasses = getAllLibClasses(stdIncludeClasses, includeClasses);
4309                         printIncludeStatements(allIncludeClasses); println("");                 
4310                         // Find out if there are callback objects
4311                         Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
4312                         boolean callbackExist = !callbackClasses.isEmpty();
4313                         println("using namespace std;\n");
4314                         // Write class header
4315                         println("class " + newSkelClass + " : public " + intface); println("{");
4316                         println("private:\n");
4317                         // Write properties
4318                         writePropertiesCplusCallbackSkeleton(intface, callbackExist, callbackClasses);
4319                         println("public:\n");
4320                         // Write constructor
4321                         writeConstructorCplusCallbackSkeleton(newSkelClass, intface, callbackExist);
4322                         // Write deconstructor
4323                         writeDeconstructorCplusCallbackSkeleton(newSkelClass, callbackExist, callbackClasses);
4324                         // Write methods
4325                         writeMethodCplusSkeleton(methods, intDecl, callbackClasses, true);
4326                         // Write method helper
4327                         writeMethodHelperCplusCallbackSkeleton(methods, intDecl, callbackClasses);
4328                         // Write waitRequestInvokeMethod() - main loop
4329                         writeCplusCallbackWaitRequestInvokeMethod(methods, intDecl, callbackExist);
4330                         println("};");
4331                         println("#endif");
4332                         pw.close();
4333                         System.out.println("IoTCompiler: Generated callback skeleton class " + newSkelClass + ".hpp...");
4334                 }
4335         }
4336
4337
4338         /**
4339          * generateInitializer() generate initializer based on type
4340          */
4341         public String generateCplusInitializer(String type) {
4342
4343                 // Generate dummy returns for now
4344                 if (type.equals("short")||
4345                         type.equals("int")      ||
4346                         type.equals("long") ||
4347                         type.equals("float")||
4348                         type.equals("double")) {
4349
4350                         return "0";
4351                 } else if ( type.equals("String") ||
4352                                         type.equals("string")) {
4353   
4354                         return "\"\"";
4355                 } else if ( type.equals("char") ||
4356                                         type.equals("byte")) {
4357
4358                         return "\' \'";
4359                 } else if ( type.equals("boolean")) {
4360
4361                         return "false";
4362                 } else {
4363                         return "NULL";
4364                 }
4365         }
4366
4367
4368         /**
4369          * generateReturnStmt() generate return statement based on methType
4370          */
4371         public String generateReturnStmt(String methType) {
4372
4373                 // Generate dummy returns for now
4374                 if (methType.equals("short")||
4375                         methType.equals("int")  ||
4376                         methType.equals("long") ||
4377                         methType.equals("float")||
4378                         methType.equals("double")) {
4379
4380                         return "1";
4381                 } else if ( methType.equals("String")) {
4382   
4383                         return "\"a\"";
4384                 } else if ( methType.equals("char") ||
4385                                         methType.equals("byte")) {
4386
4387                         return "\'a\'";
4388                 } else if ( methType.equals("boolean")) {
4389
4390                         return "true";
4391                 } else {
4392                         return "null";
4393                 }
4394         }
4395
4396
4397         /**
4398          * setDirectory() sets a new directory for stub files
4399          */
4400         public void setDirectory(String _subdir) {
4401
4402                 subdir = _subdir;
4403         }
4404
4405
4406         /**
4407          * printUsage() prints the usage of this compiler
4408          */
4409         public static void printUsage() {
4410
4411                 System.out.println();
4412                 System.out.println("Sentinel interface and stub compiler version 1.0");
4413                 System.out.println("Copyright (c) 2015-2016 University of California, Irvine - Programming Language Group.");
4414                 System.out.println("All rights reserved.");
4415                 System.out.println("Usage:");
4416                 System.out.println("\tjava IoTCompiler -help / --help / -h\n");
4417                 System.out.println("\t\tDisplay this help texts\n\n");
4418                 System.out.println("\tjava IoTCompiler [<main-policy-file> <req-policy-file>]");
4419                 System.out.println("\tjava IoTCompiler [<main-policy-file> <req-policy-file>] [options]\n");
4420                 System.out.println("\t\tTake one or more pairs of main-req policy files, and generate Java and/or C++ files\n");
4421                 System.out.println("Options:");
4422                 System.out.println("\t-java\t<directory>\tGenerate Java stub files");
4423                 System.out.println("\t-cplus\t<directory>\tGenerate C++ stub files");
4424                 System.out.println();
4425         }
4426
4427
4428         /**
4429          * parseFile() prepares Lexer and Parser objects, then parses the file
4430          */
4431         public static ParseNode parseFile(String file) {
4432
4433                 ParseNode pn = null;
4434                 try {
4435                         ComplexSymbolFactory csf = new ComplexSymbolFactory();
4436                         ScannerBuffer lexer = 
4437                                 new ScannerBuffer(new Lexer(new BufferedReader(new FileReader(file)),csf));
4438                         Parser parse = new Parser(lexer,csf);
4439                         pn = (ParseNode) parse.parse().value;
4440                 } catch (Exception e) {
4441                         e.printStackTrace();
4442                         throw new Error("IoTCompiler: ERROR parsing policy file or wrong command line option: " + file);
4443                 }
4444
4445                 return pn;
4446         }
4447
4448
4449         /**================
4450          * Helper functions
4451          **================
4452          */
4453         boolean newline=true;
4454         int tablevel=0;
4455
4456         private void print(String str) {
4457                 if (newline) {
4458                         int tab=tablevel;
4459                         if (str.equals("}"))
4460                                 tab--;
4461                         for(int i=0; i<tab; i++)
4462                                 pw.print("\t");
4463                 }
4464                 pw.print(str);
4465                 updatetabbing(str);
4466                 newline=false;
4467         }
4468
4469
4470         /**
4471          * This function converts Java to C++ type for compilation
4472          */
4473         private String convertType(String jType) {
4474
4475                 return mapPrimitives.get(jType);
4476         }
4477
4478
4479         private void println(String str) {
4480                 if (newline) {
4481                         int tab = tablevel;
4482                         if (str.contains("}") && !str.contains("{"))
4483                                 tab--;
4484                         for(int i=0; i<tab; i++)
4485                                 pw.print("\t");
4486                 }
4487                 pw.println(str);
4488                 updatetabbing(str);
4489                 newline = true;
4490         }
4491
4492
4493         private void updatetabbing(String str) {
4494
4495                 tablevel+=count(str,'{')-count(str,'}');
4496         }
4497
4498
4499         private int count(String str, char key) {
4500                 char[] array = str.toCharArray();
4501                 int count = 0;
4502                 for(int i=0; i<array.length; i++) {
4503                         if (array[i] == key)
4504                                 count++;
4505                 }
4506                 return count;
4507         }
4508
4509
4510         private void createDirectory(String dirName) {
4511
4512                 File file = new File(dirName);
4513                 if (!file.exists()) {
4514                         if (file.mkdir()) {
4515                                 System.out.println("IoTCompiler: Directory " + dirName + " has been created!");
4516                         } else {
4517                                 System.out.println("IoTCompiler: Failed to create directory " + dirName + "!");
4518                         }
4519                 } else {
4520                         System.out.println("IoTCompiler: Directory " + dirName + " exists...");
4521                 }
4522         }
4523
4524
4525         // Create a directory and possibly a sub directory
4526         private String createDirectories(String dir, String subdir) {
4527
4528                 String path = dir;
4529                 createDirectory(path);
4530                 if (subdir != null) {
4531                         path = path + "/" + subdir;
4532                         createDirectory(path);
4533                 }
4534                 return path;
4535         }
4536
4537
4538         // Inserting array members into a Map object
4539         // that maps arrKey to arrVal objects
4540         private void arraysToMap(Map map, Object[] arrKey, Object[] arrVal) {
4541
4542                 for(int i = 0; i < arrKey.length; i++) {
4543
4544                         map.put(arrKey[i], arrVal[i]);
4545                 }
4546         }
4547
4548
4549         // Return parameter category, i.e. PRIMITIVES, NONPRIMITIVES, or USERDEFINED
4550         private ParamCategory getParamCategory(String paramType) {
4551
4552                 if (mapPrimitives.containsKey(paramType)) {
4553                         return ParamCategory.PRIMITIVES;
4554                 // We can either use mapNonPrimitivesJava or mapNonPrimitivesCplus here
4555                 } else if (mapNonPrimitivesJava.containsKey(getSimpleType(paramType))) {
4556                         return ParamCategory.NONPRIMITIVES;
4557                 } else if (isEnumClass(paramType)) {
4558                         return ParamCategory.ENUM;
4559                 } else if (isStructClass(paramType)) {
4560                         return ParamCategory.STRUCT;
4561                 } else
4562                         return ParamCategory.USERDEFINED;
4563         }
4564
4565
4566         // Return full class name for non-primitives to generate Java import statements
4567         // e.g. java.util.Set for Set, java.util.Map for Map
4568         private String getNonPrimitiveJavaClass(String paramNonPrimitives) {
4569
4570                 return mapNonPrimitivesJava.get(paramNonPrimitives);
4571         }
4572
4573
4574         // Return full class name for non-primitives to generate Cplus include statements
4575         // e.g. #include <set> for Set, #include <map> for Map
4576         private String getNonPrimitiveCplusClass(String paramNonPrimitives) {
4577
4578                 return mapNonPrimitivesCplus.get(paramNonPrimitives);
4579         }
4580
4581
4582         // Get simple types, e.g. HashSet for HashSet<...>
4583         // Basically strip off the "<...>"
4584         private String getSimpleType(String paramType) {
4585
4586                 // Check if this is generics
4587                 if(paramType.contains("<")) {
4588                         String[] type = paramType.split("<");
4589                         return type[0];
4590                 } else
4591                         return paramType;
4592         }
4593
4594
4595         // Generate a set of standard classes for import statements
4596         private List<String> getStandardJavaImportClasses() {
4597
4598                 List<String> importClasses = new ArrayList<String>();
4599                 // Add the standard list first
4600                 importClasses.add("java.io.IOException");
4601                 importClasses.add("java.util.List");
4602                 importClasses.add("java.util.ArrayList");
4603                 importClasses.add("java.util.Arrays");
4604                 importClasses.add("iotrmi.Java.IoTRMICall");
4605                 importClasses.add("iotrmi.Java.IoTRMIObject");
4606
4607                 return importClasses;
4608         }
4609
4610
4611         // Generate a set of standard classes for import statements
4612         private List<String> getStandardCplusIncludeClasses() {
4613
4614                 List<String> importClasses = new ArrayList<String>();
4615                 // Add the standard list first
4616                 importClasses.add("<vector>");
4617                 importClasses.add("<set>");
4618                 importClasses.add("\"IoTRMICall.hpp\"");
4619                 importClasses.add("\"IoTRMIObject.hpp\"");
4620
4621                 return importClasses;
4622         }
4623
4624
4625         // Generate a set of standard classes for import statements
4626         private List<String> getAllLibClasses(Collection<String> stdLibClasses, Collection<String> libClasses) {
4627
4628                 List<String> allLibClasses = new ArrayList<String>(stdLibClasses);
4629                 // Iterate over the list of import classes
4630                 for (String str : libClasses) {
4631                         if (!allLibClasses.contains(str)) {
4632                                 allLibClasses.add(str);
4633                         }
4634                 }
4635
4636                 return allLibClasses;
4637         }
4638
4639
4640
4641         // Generate a set of classes for import statements
4642         private Set<String> getImportClasses(Collection<String> methods, InterfaceDecl intDecl) {
4643
4644                 Set<String> importClasses = new HashSet<String>();
4645                 for (String method : methods) {
4646                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4647                         for (String paramType : methPrmTypes) {
4648
4649                                 String simpleType = getSimpleType(paramType);
4650                                 if (getParamCategory(simpleType) == ParamCategory.NONPRIMITIVES) {
4651                                         importClasses.add(getNonPrimitiveJavaClass(simpleType));
4652                                 }
4653                         }
4654                 }
4655                 return importClasses;
4656         }
4657
4658
4659         // Handle and return the correct enum declaration
4660         // In Java, if we declare enum in Camera interface, then it becomes "Camera.<enum>"
4661         private String getEnumParamDecl(String type, InterfaceDecl intDecl) {
4662
4663                 // Strips off array "[]" for return type
4664                 String pureType = getSimpleArrayType(type);
4665                 // Take the inner type of generic
4666                 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
4667                         pureType = getTypeOfGeneric(type)[0];
4668                 if (isEnumClass(pureType)) {
4669                         String enumType = intDecl.getInterface() + "." + type;
4670                         return enumType;
4671                 } else
4672                         return type;
4673         }
4674
4675
4676         // Handle and return the correct type
4677         private String getEnumParam(String type, String param, int i) {
4678
4679                 // Strips off array "[]" for return type
4680                 String pureType = getSimpleArrayType(type);
4681                 // Take the inner type of generic
4682                 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
4683                         pureType = getTypeOfGeneric(type)[0];
4684                 if (isEnumClass(pureType)) {
4685                         String enumParam = "paramEnum" + i;
4686                         return enumParam;
4687                 } else
4688                         return param;
4689         }
4690
4691
4692         // Handle and return the correct enum declaration translate into int[]
4693         private String getEnumType(String type) {
4694
4695                 // Strips off array "[]" for return type
4696                 String pureType = getSimpleArrayType(type);
4697                 // Take the inner type of generic
4698                 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
4699                         pureType = getTypeOfGeneric(type)[0];
4700                 if (isEnumClass(pureType)) {
4701                         String enumType = "int[]";
4702                         return enumType;
4703                 } else
4704                         return type;
4705         }
4706
4707
4708         // Handle and return the correct struct declaration
4709         private String getStructType(String type) {
4710
4711                 // Strips off array "[]" for return type
4712                 String pureType = getSimpleArrayType(type);
4713                 // Take the inner type of generic
4714                 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
4715                         pureType = getTypeOfGeneric(type)[0];
4716                 if (isStructClass(pureType)) {
4717                         String structType = "int";
4718                         return structType;
4719                 } else
4720                         return type;
4721         }
4722
4723
4724         // Check if this an enum declaration
4725         private boolean isEnumClass(String type) {
4726
4727                 // Just iterate over the set of interfaces
4728                 for (String intface : mapIntfacePTH.keySet()) {
4729                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4730                         EnumDecl enumDecl = (EnumDecl) decHandler.getEnumDecl(intface);
4731                         Set<String> setEnumDecl = enumDecl.getEnumDeclarations();
4732                         if (setEnumDecl.contains(type))
4733                                 return true;
4734                 }
4735                 return false;
4736         }
4737
4738
4739         // Check if this an struct declaration
4740         private boolean isStructClass(String type) {
4741
4742                 // Just iterate over the set of interfaces
4743                 for (String intface : mapIntfacePTH.keySet()) {
4744                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4745                         StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
4746                         List<String> listStructDecl = structDecl.getStructTypes();
4747                         if (listStructDecl.contains(type))
4748                                 return true;
4749                 }
4750                 return false;
4751         }
4752
4753
4754         // Return a struct declaration
4755         private StructDecl getStructDecl(String type) {
4756
4757                 // Just iterate over the set of interfaces
4758                 for (String intface : mapIntfacePTH.keySet()) {
4759                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4760                         StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
4761                         List<String> listStructDecl = structDecl.getStructTypes();
4762                         if (listStructDecl.contains(type))
4763                                 return structDecl;
4764                 }
4765                 return null;
4766         }
4767
4768
4769         // Return number of members (-1 if not found)
4770         private int getNumOfMembers(String type) {
4771
4772                 // Just iterate over the set of interfaces
4773                 for (String intface : mapIntfacePTH.keySet()) {
4774                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4775                         StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
4776                         List<String> listStructDecl = structDecl.getStructTypes();
4777                         if (listStructDecl.contains(type))
4778                                 return structDecl.getNumOfMembers(type);
4779                 }
4780                 return -1;
4781         }
4782
4783
4784         // Generate a set of classes for include statements
4785         private Set<String> getIncludeClasses(Collection<String> methods, InterfaceDecl intDecl, String intface, boolean needExchange) {
4786
4787                 Set<String> includeClasses = new HashSet<String>();
4788                 for (String method : methods) {
4789
4790                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4791                         List<String> methParams = intDecl.getMethodParams(method);
4792                         for (int i = 0; i < methPrmTypes.size(); i++) {
4793
4794                                 String simpleType = getSimpleType(methPrmTypes.get(i));
4795                                 String param = methParams.get(i);
4796                                 if (getParamCategory(simpleType) == ParamCategory.NONPRIMITIVES) {
4797                                         includeClasses.add("<" + getNonPrimitiveCplusClass(simpleType) + ">");
4798                                 } else if (getParamCategory(simpleType) == ParamCategory.USERDEFINED) {
4799                                         // For original interface, we need it exchanged... not for stub interfaces
4800                                         if (needExchange) {
4801                                                 includeClasses.add("\"" + exchangeParamType(simpleType) + ".hpp\"");
4802                                                 includeClasses.add("\"" + exchangeParamType(simpleType) + "_CallbackStub.hpp\"");
4803                                         } else {
4804                                                 includeClasses.add("\"" + simpleType + ".hpp\"");
4805                                                 includeClasses.add("\"" + simpleType + "_CallbackSkeleton.hpp\"");
4806                                         }
4807                                 } else if (getParamCategory(getSimpleArrayType(simpleType)) == ParamCategory.ENUM) {
4808                                         includeClasses.add("\"" + simpleType + ".hpp\"");
4809                                 } else if (getParamCategory(getSimpleArrayType(simpleType)) == ParamCategory.STRUCT) {
4810                                         includeClasses.add("\"" + simpleType + ".hpp\"");
4811                                 } else if (param.contains("[]")) {
4812                                 // Check if this is array for C++; translate into vector
4813                                         includeClasses.add("<vector>");
4814                                 }
4815                         }
4816                 }
4817                 return includeClasses;
4818         }
4819
4820
4821         // Generate a set of callback classes
4822         private Set<String> getCallbackClasses(Collection<String> methods, InterfaceDecl intDecl) {
4823
4824                 Set<String> callbackClasses = new HashSet<String>();
4825                 for (String method : methods) {
4826
4827                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4828                         List<String> methParams = intDecl.getMethodParams(method);
4829                         for (int i = 0; i < methPrmTypes.size(); i++) {
4830
4831                                 String type = methPrmTypes.get(i);
4832                                 if (getParamCategory(type) == ParamCategory.USERDEFINED) {
4833                                         callbackClasses.add(type);
4834                                 } else if (getParamCategory(type) == ParamCategory.NONPRIMITIVES) {
4835                                 // Can be a List<...> of callback objects ...
4836                                         String genericType = getTypeOfGeneric(type)[0];
4837                                         if (getParamCategory(type) == ParamCategory.USERDEFINED) {
4838                                                 callbackClasses.add(type);
4839                                         }
4840                                 }
4841                         }
4842                 }
4843                 return callbackClasses;
4844         }
4845
4846
4847         private void printImportStatements(Collection<String> importClasses) {
4848
4849                 for(String cls : importClasses) {
4850                         println("import " + cls + ";");
4851                 }
4852         }
4853
4854
4855         private void printIncludeStatements(Collection<String> includeClasses) {
4856
4857                 for(String cls : includeClasses) {
4858                         println("#include " + cls);
4859                 }
4860         }
4861
4862
4863         // Get the C++ version of a non-primitive type
4864         // e.g. set for Set and map for Map
4865         // Input nonPrimitiveType has to be generics in format
4866         private String[] getTypeOfGeneric(String nonPrimitiveType) {
4867
4868                 // Handle <, >, and , for 2-type generic/template
4869                 String[] substr = nonPrimitiveType.split("<")[1].split(">")[0].split(",");
4870                 return substr;
4871         }
4872
4873
4874         // Gets generic type inside "<" and ">"
4875         private String getGenericType(String type) {
4876
4877                 // Handle <, >, and , for 2-type generic/template
4878                 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES) {
4879                         String[] substr = type.split("<")[1].split(">")[0].split(",");
4880                         return substr[0];
4881                 } else
4882                         return type;
4883         }
4884
4885
4886         // This helper function strips off array declaration, e.g. int[] becomes int
4887         private String getSimpleArrayType(String type) {
4888
4889                 // Handle [ for array declaration
4890                 String substr = type;
4891                 if (type.contains("[]")) {
4892                         substr = type.split("\\[\\]")[0];
4893                 }
4894                 return substr;
4895         }
4896
4897
4898         // This helper function strips off array declaration, e.g. D[] becomes D
4899         private String getSimpleIdentifier(String ident) {
4900
4901                 // Handle [ for array declaration
4902                 String substr = ident;
4903                 if (ident.contains("[]")) {
4904                         substr = ident.split("\\[\\]")[0];
4905                 }
4906                 return substr;
4907         }
4908
4909
4910         private String checkAndGetCplusType(String paramType) {
4911
4912                 if (getParamCategory(paramType) == ParamCategory.PRIMITIVES) {
4913                         return convertType(paramType);
4914                 } else if (getParamCategory(paramType) == ParamCategory.NONPRIMITIVES) {
4915
4916                         // Check for generic/template format
4917                         if (paramType.contains("<") && paramType.contains(">")) {
4918
4919                                 String genericClass = getSimpleType(paramType);
4920                                 String[] genericType = getTypeOfGeneric(paramType);
4921                                 String cplusTemplate = null;
4922                                 if (genericType.length == 1) // Generic/template with one type
4923                                         cplusTemplate = getNonPrimitiveCplusClass(genericClass) + 
4924                                                 "<" + convertType(genericType[0]) + ">";
4925                                 else // Generic/template with two types
4926                                         cplusTemplate = getNonPrimitiveCplusClass(genericClass) + 
4927                                                 "<" + convertType(genericType[0]) + "," + convertType(genericType[1]) + ">";
4928                                 return cplusTemplate;
4929                         } else
4930                                 return getNonPrimitiveCplusClass(paramType);
4931                 } else if(paramType.contains("[]")) {   // Array type (used for return type only)
4932                         String cArray = "vector<" + getSimpleArrayType(paramType) + ">";
4933                         return cArray;
4934                 } else if(getParamCategory(paramType) == ParamCategory.USERDEFINED) {
4935                         return paramType + "*";
4936                 } else
4937                         // Just return it as is if it's not non-primitives
4938                         return paramType;
4939                         //return checkAndGetParamClass(paramType, true);
4940         }
4941
4942
4943         // Detect array declaration, e.g. int A[],
4944         //              then generate "int A[]" in C++ as "vector<int> A"
4945         private String checkAndGetCplusArray(String paramType, String param) {
4946
4947                 String paramComplete = null;
4948                 // Check for array declaration
4949                 if (param.contains("[]")) {
4950                         paramComplete = "vector<" + paramType + "> " + param.replace("[]","");
4951                 } else
4952                         // Just return it as is if it's not an array
4953                         paramComplete = paramType + " " + param;
4954
4955                 return paramComplete;
4956         }
4957         
4958
4959         // Detect array declaration, e.g. int A[],
4960         //              then generate "int A[]" in C++ as "vector<int> A"
4961         // This method just returns the type
4962         private String checkAndGetCplusArrayType(String paramType) {
4963
4964                 String paramTypeRet = null;
4965                 // Check for array declaration
4966                 if (paramType.contains("[]")) {
4967                         String type = paramType.split("\\[\\]")[0];
4968                         paramTypeRet = checkAndGetCplusType(type) + "[]";
4969                 } else if (paramType.contains("vector")) {
4970                         // Just return it as is if it's not an array
4971                         String type = paramType.split("<")[1].split(">")[0];
4972                         paramTypeRet = checkAndGetCplusType(type) + "[]";
4973                 } else
4974                         paramTypeRet = paramType;
4975
4976                 return paramTypeRet;
4977         }
4978         
4979         
4980         // Detect array declaration, e.g. int A[],
4981         //              then generate "int A[]" in C++ as "vector<int> A"
4982         // This method just returns the type
4983         private String checkAndGetCplusArrayType(String paramType, String param) {
4984
4985                 String paramTypeRet = null;
4986                 // Check for array declaration
4987                 if (param.contains("[]")) {
4988                         paramTypeRet = checkAndGetCplusType(paramType) + "[]";
4989                 } else if (paramType.contains("vector")) {
4990                         // Just return it as is if it's not an array
4991                         String type = paramType.split("<")[1].split(">")[0];
4992                         paramTypeRet = checkAndGetCplusType(type) + "[]";
4993                 } else
4994                         paramTypeRet = paramType;
4995
4996                 return paramTypeRet;
4997         }
4998
4999
5000         // Detect array declaration, e.g. int A[],
5001         //              then generate type "int[]"
5002         private String checkAndGetArray(String paramType, String param) {
5003
5004                 String paramTypeRet = null;
5005                 // Check for array declaration
5006                 if (param.contains("[]")) {
5007                         paramTypeRet = paramType + "[]";
5008                 } else
5009                         // Just return it as is if it's not an array
5010                         paramTypeRet = paramType;
5011
5012                 return paramTypeRet;
5013         }
5014
5015
5016         // Is array or list?
5017         private boolean isArrayOrList(String paramType, String param) {
5018
5019                 // Check for array declaration
5020                 if (isArray(param))
5021                         return true;
5022                 else if (isList(paramType))
5023                         return true;
5024                 else
5025                         return false;
5026         }
5027
5028
5029         // Is array? For return type we put the return type as input parameter
5030         private boolean isArray(String param) {
5031
5032                 // Check for array declaration
5033                 if (param.contains("[]"))
5034                         return true;
5035                 else
5036                         return false;
5037         }
5038
5039
5040         // Is list?
5041         private boolean isList(String paramType) {
5042
5043                 // Check for array declaration
5044                 if (paramType.contains("List"))
5045                         return true;
5046                 else
5047                         return false;
5048         }
5049
5050
5051         // Get the right type for a callback object
5052         private String checkAndGetParamClass(String paramType) {
5053
5054                 // Check if this is generics
5055                 if(getParamCategory(paramType) == ParamCategory.USERDEFINED) {
5056                         return exchangeParamType(paramType);
5057                 } else
5058                         return paramType;
5059         }
5060
5061
5062         // Returns the other interface for type-checking purposes for USERDEFINED
5063         //              classes based on the information provided in multiple policy files
5064         // e.g. return CameraWithXXX instead of Camera
5065         private String exchangeParamType(String intface) {
5066
5067                 // Param type that's passed is the interface name we need to look for
5068                 //              in the map of interfaces, based on available policy files.
5069                 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
5070                 if (decHandler != null) {
5071                 // We've found the required interface policy files
5072                         RequiresDecl reqDecl = (RequiresDecl) decHandler.getRequiresDecl(intface);
5073                         Set<String> setExchInt = reqDecl.getInterfaces();
5074                         if (setExchInt.size() == 1) {
5075                                 Iterator iter = setExchInt.iterator();
5076                                 return (String) iter.next();
5077                         } else {
5078                                 throw new Error("IoTCompiler: Ambiguous stub interfaces: " + setExchInt.toString() + 
5079                                         ". Only one new interface can be declared if the object " + intface +
5080                                         " needs to be passed in as an input parameter!");
5081                         }
5082                 } else {
5083                 // NULL value - this means policy files missing
5084                         throw new Error("IoTCompiler: Parameter type lookup failed for " + intface +
5085                                 "... Please provide the necessary policy files for user-defined types." +
5086                                 " If this is an array please type the brackets after the variable name," +
5087                                 " e.g. \"String str[]\", not \"String[] str\"." +
5088                                 " If this is a Collections (Java) / STL (C++) type, this compiler only" +
5089                                 " supports List/ArrayList (Java) or list (C++).");
5090                 }
5091         }
5092
5093
5094         public static void main(String[] args) throws Exception {
5095
5096                 // If there is no argument or just "--help" or "-h", then invoke printUsage()
5097                 if ((args[0].equals("-help") ||
5098                          args[0].equals("--help")||
5099                          args[0].equals("-h"))   ||
5100                         (args.length == 0)) {
5101
5102                         IoTCompiler.printUsage();
5103
5104                 } else if (args.length > 1) {
5105
5106                         IoTCompiler comp = new IoTCompiler();
5107                         int i = 0;                              
5108                         do {
5109                                 // Parse main policy file
5110                                 ParseNode pnPol = IoTCompiler.parseFile(args[i]);
5111                                 // Parse "requires" policy file
5112                                 ParseNode pnReq = IoTCompiler.parseFile(args[i+1]);
5113                                 // Get interface name
5114                                 String intface = ParseTreeHandler.getOrigIntface(pnPol);
5115                                 comp.setDataStructures(intface, pnPol, pnReq);
5116                                 comp.getMethodsForIntface(intface);
5117                                 i = i + 2;
5118                         // 1) Check if this is the last option before "-java" or "-cplus"
5119                         // 2) Check if this is really the last option (no "-java" or "-cplus")
5120                         } while(!args[i].equals("-java") &&
5121                                         !args[i].equals("-cplus") &&
5122                                         (i < args.length));
5123
5124                         // Generate everything if we don't see "-java" or "-cplus"
5125                         if (i == args.length) {
5126                                 comp.generateEnumJava();
5127                                 comp.generateStructJava();
5128                                 comp.generateJavaLocalInterfaces();
5129                                 comp.generateJavaInterfaces();
5130                                 comp.generateJavaStubClasses();
5131                                 comp.generateJavaCallbackStubClasses();
5132                                 comp.generateJavaSkeletonClass();
5133                                 comp.generateJavaCallbackSkeletonClass();
5134                                 comp.generateEnumCplus();
5135                                 comp.generateStructCplus();
5136                                 comp.generateCplusLocalInterfaces();
5137                                 comp.generateCPlusInterfaces();
5138                                 comp.generateCPlusStubClasses();
5139                                 comp.generateCPlusCallbackStubClasses();
5140                                 comp.generateCplusSkeletonClass();
5141                                 comp.generateCplusCallbackSkeletonClass();
5142                         } else {
5143                         // Check other options
5144                                 while(i < args.length) {
5145                                         // Error checking
5146                                         if (!args[i].equals("-java") &&
5147                                                 !args[i].equals("-cplus")) {
5148                                                 throw new Error("IoTCompiler: ERROR - unrecognized command line option: " + args[i]);
5149                                         } else {
5150                                                 if (i + 1 < args.length) {
5151                                                         comp.setDirectory(args[i+1]);
5152                                                 } else
5153                                                         throw new Error("IoTCompiler: ERROR - please provide <directory> after option: " + args[i]);
5154
5155                                                 if (args[i].equals("-java")) {
5156                                                         comp.generateEnumJava();
5157                                                         comp.generateStructJava();
5158                                                         comp.generateJavaLocalInterfaces();
5159                                                         comp.generateJavaInterfaces();
5160                                                         comp.generateJavaStubClasses();
5161                                                         comp.generateJavaCallbackStubClasses();
5162                                                         comp.generateJavaSkeletonClass();
5163                                                         comp.generateJavaCallbackSkeletonClass();
5164                                                 } else {
5165                                                         comp.generateEnumCplus();
5166                                                         comp.generateStructCplus();
5167                                                         comp.generateCplusLocalInterfaces();
5168                                                         comp.generateCPlusInterfaces();
5169                                                         comp.generateCPlusStubClasses();
5170                                                         comp.generateCPlusCallbackStubClasses();
5171                                                         comp.generateCplusSkeletonClass();
5172                                                         comp.generateCplusCallbackSkeletonClass();
5173                                                 }
5174                                         }
5175                                         i = i + 2;
5176                                 }
5177                         }
5178                 } else {
5179                 // Need to at least have exactly 2 parameters, i.e. main policy file and requires file
5180                         IoTCompiler.printUsage();
5181                         throw new Error("IoTCompiler: At least two arguments (main and requires policy files) have to be provided!");
5182                 }
5183         }
5184 }
5185
5186
5187
5188