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