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