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