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