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