Adding enum support in compiler
[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: writeStdMethodBodyJavaStub() writes the standard method body in the stub class
603          */
604         private void writeStdMethodBodyJavaStub(InterfaceDecl intDecl, List<String> methParams,
605                         List<String> methPrmTypes, String method) {
606
607                 println("int methodId = " + intDecl.getMethodNumId(method) + ";");
608                 String retType = intDecl.getMethodType(method);
609                 println("Class<?> retType = " + getSimpleType(getEnumType(retType)) + ".class;");
610                 checkAndWriteEnumTypeJavaStub(methParams, methPrmTypes);
611                 // Generate array of parameter types
612                 print("Class<?>[] paramCls = new Class<?>[] { ");
613                 for (int i = 0; i < methParams.size(); i++) {
614                         String paramType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
615                         print(getSimpleType(getEnumType(paramType)) + ".class");
616                         // Check if this is the last element (don't print a comma)
617                         if (i != methParams.size() - 1) {
618                                 print(", ");
619                         }
620                 }
621                 println(" };");
622                 // Generate array of parameter objects
623                 print("Object[] paramObj = new Object[] { ");
624                 for (int i = 0; i < methParams.size(); i++) {
625                         print(getEnumParam(methPrmTypes.get(i), getSimpleIdentifier(methParams.get(i)), i));
626                         // Check if this is the last element (don't print a comma)
627                         if (i != methParams.size() - 1) {
628                                 print(", ");
629                         }
630                 }
631                 println(" };");
632                 // Check if this is "void"
633                 if (retType.equals("void")) {
634                         println("rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
635                 } else { // We do have a return value
636                 // Check if the return value NONPRIMITIVES
637                         if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES) {
638                                 String[] retGenValType = getTypeOfGeneric(retType);
639                                 println("Class<?> retGenValType = " + retGenValType[0] + ".class;");
640                                 println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, retGenValType, paramCls, paramObj);");
641                                 println("return (" + retType + ")retObj;");
642                         } else if (getParamCategory(retType) == ParamCategory.ENUM) {
643                         // This is an enum type
644                                 println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
645                                 checkAndWriteEnumRetTypeJavaStub(retType);
646                         } else {
647                                 println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
648                                 println("return (" + retType + ")retObj;");
649                         }
650                 }
651         }
652
653
654         /**
655          * HELPER: returnGenericCallbackType() returns the callback type
656          */
657         private String returnGenericCallbackType(String paramType) {
658
659                 if (getParamCategory(paramType) == ParamCategory.NONPRIMITIVES)
660                         return getTypeOfGeneric(paramType)[0];
661                 else
662                         return paramType;
663         }
664
665
666         /**
667          * HELPER: checkCallbackType() checks the callback type
668          */
669         private boolean checkCallbackType(String paramType, String callbackType) {
670
671                 String prmType = returnGenericCallbackType(paramType);
672                 return callbackType.equals(prmType);
673         }
674
675
676         /**
677          * HELPER: writeCallbackMethodBodyJavaStub() writes the callback method of the stub class
678          */
679         private void writeCallbackMethodBodyJavaStub(InterfaceDecl intDecl, List<String> methParams,
680                         List<String> methPrmTypes, String method, String callbackType) {
681
682                 println("try {");
683                 // Check if this is single object, array, or list of objects
684                 for (int i = 0; i < methParams.size(); i++) {
685
686                         String paramType = methPrmTypes.get(i);
687                         if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
688                                 String param = methParams.get(i);
689                                 if (isArrayOrList(paramType, param)) {  // Generate loop
690                                         println("for (" + paramType + " cb : " + getSimpleIdentifier(param) + ") {");
691                                         println(callbackType + "_CallbackSkeleton skel = new " + callbackType + "_CallbackSkeleton(cb, objIdCnt++);");
692                                 } else
693                                         println(callbackType + "_CallbackSkeleton skel = new " + callbackType + "_CallbackSkeleton(" +
694                                                 getSimpleIdentifier(param) + ", objIdCnt++);");
695                                 println("listCallbackObj.add(skel);");
696                                 if (isArrayOrList(paramType, param))
697                                         println("}");
698                         }
699                 }
700                 println("} catch (Exception ex) {");
701                 println("ex.printStackTrace();");
702                 println("throw new Error(\"Exception when generating skeleton objects!\");");
703                 println("}\n");
704                 println("int methodId = " + intDecl.getMethodNumId(method) + ";");
705                 String retType = intDecl.getMethodType(method);
706                 println("Class<?> retType = " + getSimpleType(getEnumType(retType)) + ".class;");
707                 // Generate array of parameter types
708                 print("Class<?>[] paramCls = new Class<?>[] { ");
709                 for (int i = 0; i < methParams.size(); i++) {
710                         String paramType = methPrmTypes.get(i);
711                         if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
712                                 print("int.class");
713                         } else { // Generate normal classes if it's not a callback object
714                                 String prmType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
715                                 print(getSimpleType(prmType) + ".class");
716                         }
717                         if (i != methParams.size() - 1) // Check if this is the last element
718                                 print(", ");
719                 }
720                 println(" };");
721                 // Generate array of parameter objects
722                 print("Object[] paramObj = new Object[] { ");
723                 for (int i = 0; i < methParams.size(); i++) {
724                         String paramType = methPrmTypes.get(i);
725                         if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
726                                 //if (isArray(methPrmTypes.get(i), methParams.get(i)))
727                                 if (isArray(methParams.get(i)))
728                                         print(getSimpleIdentifier(methParams.get(i)) + ".length");
729                                 else if (isList(methPrmTypes.get(i)))
730                                         print(getSimpleIdentifier(methParams.get(i)) + ".size()");
731                                 else
732                                         print("new Integer(1)");
733                         } else
734                                 print(getSimpleIdentifier(methParams.get(i)));
735                         if (i != methParams.size() - 1)
736                                 print(", ");
737                 }
738                 println(" };");
739                 // Check if this is "void"
740                 if (retType.equals("void")) {
741                         println("rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
742                 } else { // We do have a return value
743                 // Check if the return value NONPRIMITIVES
744                         if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES) {
745                                 String[] retGenValType = getTypeOfGeneric(retType);
746                                 println("Class<?> retGenValType = " + retGenValType[0] + ".class;");
747                                 println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, retGenValType, paramCls, paramObj);");
748                                 println("return (" + retType + ")retObj;");
749                         } else {
750                                 println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
751                                 println("return (" + retType + ")retObj;");
752                         }
753                 }
754         }
755
756
757         /**
758          * HELPER: writeMethodJavaStub() writes the method of the stub class
759          */
760         private void writeMethodJavaStub(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
761
762                 for (String method : methods) {
763
764                         List<String> methParams = intDecl.getMethodParams(method);
765                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
766                         print("public " + intDecl.getMethodType(method) + " " +
767                                 intDecl.getMethodId(method) + "(");
768                         boolean isCallbackMethod = false;
769                         String callbackType = null;
770                         for (int i = 0; i < methParams.size(); i++) {
771
772                                 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
773                                 // Check if this has callback object
774                                 if (callbackClasses.contains(paramType)) {
775                                         isCallbackMethod = true;
776                                         callbackType = paramType;       
777                                         // Even if there're 2 callback arguments, we expect them to be of the same interface
778                                 }
779                                 print(methPrmTypes.get(i) + " " + methParams.get(i));
780                                 // Check if this is the last element (don't print a comma)
781                                 if (i != methParams.size() - 1) {
782                                         print(", ");
783                                 }
784                         }
785                         println(") {");
786                         // Now, write the body of stub!
787                         if (isCallbackMethod)
788                                 writeCallbackMethodBodyJavaStub(intDecl, methParams, methPrmTypes, method, callbackType);
789                         else
790                                 writeStdMethodBodyJavaStub(intDecl, methParams, methPrmTypes, method);
791                         println("}\n");
792                         // Write the init callback helper method
793                         if (isCallbackMethod)
794                                 writeInitCallbackJavaStub(callbackType, intDecl);
795                 }
796         }
797
798
799         /**
800          * generateJavaStubClasses() generate stubs based on the methods list in Java
801          */
802         public void generateJavaStubClasses() throws IOException {
803
804                 // Create a new directory
805                 String path = createDirectories(dir, subdir);
806                 for (String intface : mapIntfacePTH.keySet()) {
807
808                         Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
809                         for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
810
811                                 // Open a new file to write into
812                                 String newIntface = intMeth.getKey();
813                                 String newStubClass = newIntface + "_Stub";
814                                 FileWriter fw = new FileWriter(path + "/" + newStubClass + ".java");
815                                 pw = new PrintWriter(new BufferedWriter(fw));
816                                 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
817                                 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
818                                 // Pass in set of methods and get import classes
819                                 Set<String> methods = intMeth.getValue();
820                                 Set<String> importClasses = getImportClasses(methods, intDecl);
821                                 List<String> stdImportClasses = getStandardJavaImportClasses();
822                                 List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
823                                 printImportStatements(allImportClasses); println("");
824                                 // Find out if there are callback objects
825                                 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
826                                 boolean callbackExist = !callbackClasses.isEmpty();
827                                 // Write class header
828                                 println("public class " + newStubClass + " implements " + newIntface + " {\n");
829                                 // Write properties
830                                 writePropertiesJavaStub(intface, newIntface, callbackExist, callbackClasses);
831                                 // Write constructor
832                                 writeConstructorJavaStub(intface, newStubClass, callbackExist, callbackClasses);
833                                 // Write methods
834                                 writeMethodJavaStub(intMeth.getValue(), intDecl, callbackClasses);
835                                 println("}");
836                                 pw.close();
837                                 System.out.println("IoTCompiler: Generated stub class " + newStubClass + ".java...");
838                         }
839                 }
840         }
841
842
843         /**
844          * HELPER: writePropertiesJavaCallbackStub() writes the properties of the callback stub class
845          */
846         private void writePropertiesJavaCallbackStub(String intface, String newIntface, boolean callbackExist, Set<String> callbackClasses) {
847
848                 println("private IoTRMICall rmiCall;");
849                 println("private String address;");
850                 println("private int[] ports;\n");
851                 // Get the object Id
852                 println("private static int objectId = 0;");
853                 if (callbackExist) {
854                 // We assume that each class only has one callback interface for now
855                         Iterator it = callbackClasses.iterator();
856                         String callbackType = (String) it.next();
857                         println("// Callback properties");
858                         println("private IoTRMIObject rmiObj;");
859                         println("List<" + callbackType + "> listCallbackObj;");
860                         println("private static int objIdCnt = 0;");
861                         // Generate permission stuff for callback stubs
862                         DeclarationHandler decHandler = mapIntDeclHand.get(callbackType);
863                         InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(callbackType);
864                         writePropertiesJavaPermission(callbackType, intDecl);
865                 }
866                 println("\n");
867         }
868
869
870         /**
871          * HELPER: writeConstructorJavaCallbackStub() writes the constructor of the callback stub class
872          */
873         private void writeConstructorJavaCallbackStub(String intface, String newStubClass, boolean callbackExist, Set<String> callbackClasses) {
874
875                 // TODO: If we want callback in callback, then we need to add address and port initializations
876                 println("public " + newStubClass + "(IoTRMICall _rmiCall, int _objectId) throws Exception {");
877                 println("objectId = _objectId;");
878                 println("rmiCall = _rmiCall;");
879                 if (callbackExist) {
880                         Iterator it = callbackClasses.iterator();
881                         String callbackType = (String) it.next();
882                         writeConstructorJavaPermission(intface);
883                         println("listCallbackObj = new ArrayList<" + callbackType + ">();");
884                         println("___initCallBack();");
885                         println("// TODO: Add address and port initialization here if we want callback in callback!");
886                 }
887                 println("}\n");
888         }
889
890
891         /**
892          * generateJavaCallbackStubClasses() generate callback stubs based on the methods list in Java
893          * <p>
894          * Callback stubs gets the IoTRMICall objects from outside of the class as contructor input
895          * because all these stubs are populated by the class that takes in this object as a callback
896          * object. In such a class, we only use one socket, hence one IoTRMICall, for all callback objects.
897          */
898         public void generateJavaCallbackStubClasses() throws IOException {
899
900                 // Create a new directory
901                 String path = createDirectories(dir, subdir);
902                 for (String intface : mapIntfacePTH.keySet()) {
903
904                         Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
905                         for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
906
907                                 // Open a new file to write into
908                                 String newIntface = intMeth.getKey();
909                                 String newStubClass = newIntface + "_CallbackStub";
910                                 FileWriter fw = new FileWriter(path + "/" + newStubClass + ".java");
911                                 pw = new PrintWriter(new BufferedWriter(fw));
912                                 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
913                                 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
914                                 // Pass in set of methods and get import classes
915                                 Set<String> methods = intMeth.getValue();
916                                 Set<String> importClasses = getImportClasses(methods, intDecl);
917                                 List<String> stdImportClasses = getStandardJavaImportClasses();
918                                 List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
919                                 printImportStatements(allImportClasses); println("");
920                                 // Find out if there are callback objects
921                                 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
922                                 boolean callbackExist = !callbackClasses.isEmpty();
923                                 // Write class header
924                                 println("public class " + newStubClass + " implements " + newIntface + " {\n");
925                                 // Write properties
926                                 writePropertiesJavaCallbackStub(intface, newIntface, callbackExist, callbackClasses);
927                                 // Write constructor
928                                 writeConstructorJavaCallbackStub(intface, newStubClass, callbackExist, callbackClasses);
929                                 // Write methods
930                                 // TODO: perhaps need to generate callback for callback
931                                 writeMethodJavaStub(intMeth.getValue(), intDecl, callbackClasses);
932                                 println("}");
933                                 pw.close();
934                                 System.out.println("IoTCompiler: Generated callback stub class " + newStubClass + ".java...");
935                         }
936                 }
937         }
938
939
940         /**
941          * HELPER: writePropertiesJavaSkeleton() writes the properties of the skeleton class
942          */
943         private void writePropertiesJavaSkeleton(String intface, boolean callbackExist, InterfaceDecl intDecl) {
944
945                 println("private " + intface + " mainObj;");
946                 //println("private int ports;");
947                 println("private IoTRMIObject rmiObj;\n");
948                 // Callback
949                 if (callbackExist) {
950                         println("private static int objIdCnt = 0;");
951                         println("private IoTRMICall rmiCall;");
952                 }
953                 writePropertiesJavaPermission(intface, intDecl);
954                 println("\n");
955         }
956
957
958         /**
959          * HELPER: writeConstructorJavaSkeleton() writes the constructor of the skeleton class
960          */
961         private void writeConstructorJavaSkeleton(String newSkelClass, String intface) {
962
963                 println("public " + newSkelClass + "(" + intface + " _mainObj, int _port) throws Exception {");
964                 println("mainObj = _mainObj;");
965                 println("rmiObj = new IoTRMIObject(_port);");
966                 // Generate permission control initialization
967                 writeConstructorJavaPermission(intface);
968                 println("___waitRequestInvokeMethod();");
969                 println("}\n");
970         }
971
972
973         /**
974          * HELPER: writeStdMethodBodyJavaSkeleton() writes the standard method body in the skeleton class
975          */
976         private void writeStdMethodBodyJavaSkeleton(List<String> methParams, String methodId, String methodType) {
977
978                 if (methodType.equals("void"))
979                         print("mainObj." + methodId + "(");
980                 else
981                         print("return mainObj." + methodId + "(");
982                 for (int i = 0; i < methParams.size(); i++) {
983
984                         print(getSimpleIdentifier(methParams.get(i)));
985                         // Check if this is the last element (don't print a comma)
986                         if (i != methParams.size() - 1) {
987                                 print(", ");
988                         }
989                 }
990                 println(");");
991         }
992
993
994         /**
995          * HELPER: writeInitCallbackJavaSkeleton() writes the init callback method for skeleton class
996          */
997         private void writeInitCallbackJavaSkeleton(boolean callbackSkeleton) {
998
999                 // This is a callback skeleton generation
1000                 if (callbackSkeleton)
1001                         println("public void ___regCB(IoTRMIObject rmiObj) throws IOException {");
1002                 else
1003                         println("public void ___regCB() throws IOException {");
1004                 println("Object[] paramObj = rmiObj.getMethodParams(new Class<?>[] { int.class, String.class, int.class },");
1005                 println("\tnew Class<?>[] { null, null, null });");
1006                 println("rmiCall = new IoTRMICall((int) paramObj[0], (String) paramObj[1], (int) paramObj[2]);");
1007                 println("}\n");
1008         }
1009
1010
1011         /**
1012          * HELPER: writeMethodJavaSkeleton() writes the method of the skeleton class
1013          */
1014         private void writeMethodJavaSkeleton(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses, 
1015                         boolean callbackSkeleton) {
1016
1017                 for (String method : methods) {
1018
1019                         List<String> methParams = intDecl.getMethodParams(method);
1020                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1021                         String methodId = intDecl.getMethodId(method);
1022                         print("public " + intDecl.getMethodType(method) + " " + methodId + "(");
1023                         boolean isCallbackMethod = false;
1024                         String callbackType = null;
1025                         for (int i = 0; i < methParams.size(); i++) {
1026
1027                                 String origParamType = methPrmTypes.get(i);
1028                                 String paramType = checkAndGetParamClass(origParamType);
1029                                 if (callbackClasses.contains(origParamType)) { // Check if this has callback object
1030                                         isCallbackMethod = true;
1031                                         callbackType = origParamType;   
1032                                 }
1033                                 print(paramType + " " + methParams.get(i));
1034                                 // Check if this is the last element (don't print a comma)
1035                                 if (i != methParams.size() - 1) {
1036                                         print(", ");
1037                                 }
1038                         }
1039                         println(") {");
1040                         // Now, write the body of skeleton!
1041                         writeStdMethodBodyJavaSkeleton(methParams, methodId, intDecl.getMethodType(method));
1042                         println("}\n");
1043                         if (isCallbackMethod)
1044                                 writeInitCallbackJavaSkeleton(callbackSkeleton);
1045                 }
1046         }
1047
1048
1049         /**
1050          * HELPER: writeCallbackJavaStubGeneration() writes the callback stub generation part
1051          */
1052         private Map<Integer,String> writeCallbackJavaStubGeneration(List<String> methParams, List<String> methPrmTypes, String callbackType) {
1053
1054                 Map<Integer,String> mapStubParam = new HashMap<Integer,String>();
1055                 // Iterate over callback objects
1056                 for (int i = 0; i < methParams.size(); i++) {
1057                         String paramType = methPrmTypes.get(i);
1058                         String param = methParams.get(i);
1059                         //if (callbackType.equals(paramType)) {
1060                         if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
1061                                 println("try {");
1062                                 String exchParamType = checkAndGetParamClass(paramType);
1063                                 // Print array if this is array or list if this is a list of callback objects
1064                                 if (isArray(param)) {
1065                                         println("int numStubs" + i + " = (int) paramObj[" + i + "];");
1066                                         println(exchParamType + "[] stub" + i + " = new " + exchParamType + "[numStubs" + i + "];");
1067                                 } else if (isList(paramType)) {
1068                                         println("int numStubs" + i + " = (int) paramObj[" + i + "];");
1069                                         println("List<" + exchParamType + "> stub" + i + " = new ArrayList<" + exchParamType + ">();");
1070                                 } else {
1071                                         println(exchParamType + " stub" + i + " = new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt);");
1072                                         println("objIdCnt++;");
1073                                 }
1074                         }
1075                         // Generate a loop if needed
1076                         if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
1077                                 String exchParamType = checkAndGetParamClass(paramType);
1078                                 if (isArray(param)) {
1079                                         println("for (int objId = 0; objId < numStubs" + i + "; objId++) {");
1080                                         println("stub" + i + "[objId] = new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt);");
1081                                         println("objIdCnt++;");
1082                                         println("}");
1083                                 } else if (isList(paramType)) {
1084                                         println("for (int objId = 0; objId < numStubs" + i + "; objId++) {");
1085                                         println("stub" + i + ".add(new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt));");
1086                                         println("objIdCnt++;");
1087                                         println("}");
1088                                 }
1089                                 mapStubParam.put(i, "stub" + i);        // List of all stub parameters
1090                         }
1091                 }
1092                 return mapStubParam;
1093         }
1094
1095
1096         /**
1097          * HELPER: checkAndWriteEnumTypeJavaSkeleton() writes the enum type (convert from enum to int)
1098          */
1099         private void checkAndWriteEnumTypeJavaSkeleton(List<String> methParams, List<String> methPrmTypes) {
1100
1101                 // Iterate and find enum declarations
1102                 for (int i = 0; i < methParams.size(); i++) {
1103                         String paramType = methPrmTypes.get(i);
1104                         String param = methParams.get(i);
1105                         String simpleType = getSimpleType(paramType);
1106                         if (isEnumClass(simpleType)) {
1107                         // Check if this is enum type
1108                                 println("int paramInt" + i + "[] = (int[]) paramObj[" + i + "];");
1109                                 println(simpleType + "[] enumVals = " + simpleType + ".values();");
1110                                 if (isArray(param)) {   // An array
1111                                         println("int len" + i + " = paramInt" + i + ".length;");
1112                                         println(simpleType + "[] paramEnum = new " + simpleType + "[len];");
1113                                         println("for (int i = 0; i < len" + i + "; i++) {");
1114                                         println("paramEnum[i] = enumVals[paramInt" + i + "[i]];");
1115                                         println("}");
1116                                 } else if (isList(paramType)) { // A list
1117                                         println("int len" + i + " = paramInt" + i + ".length;");
1118                                         println("List<" + simpleType + "> paramEnum = new ArrayList<" + simpleType + ">();");
1119                                         println("for (int i = 0; i < len" + i + "; i++) {");
1120                                         println("paramEnum.add(enumVals[paramInt" + i + "[i]]);");
1121                                         println("}");
1122                                 } else {        // Just one element
1123                                         println(simpleType + " paramEnum" + i + " = enumVals[paramInt" + i + "[0]];");
1124                                 }
1125                         }
1126                 }
1127         }
1128
1129
1130         /**
1131          * HELPER: checkAndWriteEnumRetTypeJavaSkeleton() writes the enum return type (convert from enum to int)
1132          */
1133         private void checkAndWriteEnumRetTypeJavaSkeleton(String retType, String methodId) {
1134
1135                 // Strips off array "[]" for return type
1136                 String pureType = getSimpleArrayType(getSimpleType(retType));
1137                 // Take the inner type of generic
1138                 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
1139                         pureType = getTypeOfGeneric(retType)[0];
1140                 if (isEnumClass(pureType)) {
1141                 // Check if this is enum type
1142                         // Enum decoder
1143                         if (isArray(retType)) {                 // An array
1144                                 print(pureType + "[] retEnum = " + methodId + "(");
1145                         } else if (isList(retType)) {   // A list
1146                                 print("List<" + pureType + "> retEnum = " + methodId + "(");
1147                         } else {        // Just one element
1148                                 print(pureType + " retEnum = " + methodId + "(");
1149                         }
1150                 }
1151         }
1152
1153
1154         /**
1155          * HELPER: checkAndWriteEnumRetConvJavaSkeleton() writes the enum return type (convert from enum to int)
1156          */
1157         private void checkAndWriteEnumRetConvJavaSkeleton(String retType) {
1158
1159                 // Strips off array "[]" for return type
1160                 String pureType = getSimpleArrayType(getSimpleType(retType));
1161                 // Take the inner type of generic
1162                 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
1163                         pureType = getTypeOfGeneric(retType)[0];
1164                 if (isEnumClass(pureType)) {
1165                 // Check if this is enum type
1166                         if (isArray(retType)) { // An array
1167                                 println("int retLen = retEnum.length;");
1168                                 println("int[] retEnumVal = new int[retLen];");
1169                                 println("for (int i = 0; i < retLen; i++) {");
1170                                 println("retEnumVal[i] = retEnum[i].ordinal();");
1171                                 println("}");
1172                         } else if (isList(retType)) {   // A list
1173                                 println("int retLen = retEnum.size();");
1174                                 println("List<" + pureType + "> retEnumVal = new ArrayList<" + pureType + ">();");
1175                                 println("for (int i = 0; i < retLen; i++) {");
1176                                 println("retEnumVal.add(retEnum[i].ordinal());");
1177                                 println("}");
1178                         } else {        // Just one element
1179                                 println("int[] retEnumVal = new int[1];");
1180                                 println("retEnumVal[0] = retEnum.ordinal();");
1181                         }
1182                         println("Object retObj = retEnumVal;");
1183                 }
1184         }
1185
1186
1187         /**
1188          * HELPER: writeStdMethodHelperBodyJavaSkeleton() writes the standard method body helper in the skeleton class
1189          */
1190         private void writeStdMethodHelperBodyJavaSkeleton(InterfaceDecl intDecl, List<String> methParams,
1191                         List<String> methPrmTypes, String method, Set<String> callbackClasses) {
1192                 // Generate array of parameter objects
1193                 boolean isCallbackMethod = false;
1194                 String callbackType = null;
1195                 print("Object[] paramObj = rmiObj.getMethodParams(new Class<?>[] { ");
1196                 for (int i = 0; i < methParams.size(); i++) {
1197
1198                         String paramType = returnGenericCallbackType(methPrmTypes.get(i));
1199                         if (callbackClasses.contains(paramType)) {
1200                                 isCallbackMethod = true;
1201                                 callbackType = paramType;
1202                                 print("int.class");
1203                         } else {        // Generate normal classes if it's not a callback object
1204                                 String prmType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
1205                                 print(getSimpleType(getEnumType(prmType)) + ".class");
1206                         }
1207                         if (i != methParams.size() - 1)
1208                                 print(", ");
1209                 }
1210                 println(" }, ");
1211                 // Generate generic class if it's a generic type.. null otherwise
1212                 print("new Class<?>[] { ");
1213                 for (int i = 0; i < methParams.size(); i++) {
1214                         String prmType = methPrmTypes.get(i);
1215                         if (getParamCategory(prmType) == ParamCategory.NONPRIMITIVES)
1216                                 print(getTypeOfGeneric(prmType)[0] + ".class");
1217                         else
1218                                 print("null");
1219                         if (i != methParams.size() - 1)
1220                                 print(", ");
1221                 }
1222                 println(" });");
1223                 checkAndWriteEnumTypeJavaSkeleton(methParams, methPrmTypes);
1224                 Map<Integer,String> mapStubParam = null;
1225                 if (isCallbackMethod)
1226                         mapStubParam = writeCallbackJavaStubGeneration(methParams, methPrmTypes, callbackType);
1227                 // Check if this is "void"
1228                 String retType = intDecl.getMethodType(method);
1229                 if (retType.equals("void")) {
1230                         print(intDecl.getMethodId(method) + "(");
1231                 } else if (isEnumClass(getSimpleArrayType(getSimpleType(retType)))) {   // Enum type
1232                         checkAndWriteEnumRetTypeJavaSkeleton(retType, intDecl.getMethodId(method));
1233                 } else { // We do have a return value
1234                         print("Object retObj = " + intDecl.getMethodId(method) + "(");
1235                 }
1236                 for (int i = 0; i < methParams.size(); i++) {
1237
1238                         if (isCallbackMethod) {
1239                                 print(mapStubParam.get(i));     // Get the callback parameter
1240                         } else if (isEnumClass(getSimpleType(methPrmTypes.get(i)))) { // Enum class
1241                                 print(getEnumParam(methPrmTypes.get(i), methParams.get(i), i));
1242                         } else {
1243                                 String prmType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
1244                                 print("(" + prmType + ") paramObj[" + i + "]");
1245                         }
1246                         if (i != methParams.size() - 1)
1247                                 print(", ");
1248                 }
1249                 println(");");
1250                 if (!retType.equals("void")) {
1251                         if (isEnumClass(getSimpleArrayType(getSimpleType(retType)))) // Enum type
1252                                 checkAndWriteEnumRetConvJavaSkeleton(retType);
1253                         println("rmiObj.sendReturnObj(retObj);");
1254                 }
1255                 if (isCallbackMethod) { // Catch exception if this is callback
1256                         println("} catch(Exception ex) {");
1257                         println("ex.printStackTrace();");
1258                         println("throw new Error(\"Exception from callback object instantiation!\");");
1259                         println("}");
1260                 }
1261         }
1262
1263
1264         /**
1265          * HELPER: writeMethodHelperJavaSkeleton() writes the method helper of the skeleton class
1266          */
1267         private void writeMethodHelperJavaSkeleton(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
1268
1269                 // Use this set to handle two same methodIds
1270                 Set<String> uniqueMethodIds = new HashSet<String>();
1271                 for (String method : methods) {
1272
1273                         List<String> methParams = intDecl.getMethodParams(method);
1274                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1275                         String methodId = intDecl.getMethodId(method);
1276                         print("public void ___");
1277                         String helperMethod = methodId;
1278                         if (uniqueMethodIds.contains(methodId))
1279                                 helperMethod = helperMethod + intDecl.getMethodNumId(method);
1280                         else
1281                                 uniqueMethodIds.add(methodId);
1282                         // Check if this is "void"
1283                         String retType = intDecl.getMethodType(method);
1284                         if (retType.equals("void"))
1285                                 println(helperMethod + "() {");
1286                         else
1287                                 println(helperMethod + "() throws IOException {");
1288                         // Now, write the helper body of skeleton!
1289                         writeStdMethodHelperBodyJavaSkeleton(intDecl, methParams, methPrmTypes, method, callbackClasses);
1290                         println("}\n");
1291                 }
1292         }
1293
1294
1295         /**
1296          * HELPER: writeJavaMethodPermission() writes permission checks in skeleton
1297          */
1298         private void writeJavaMethodPermission(String intface) {
1299
1300                 // Get all the different stubs
1301                 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
1302                 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
1303                         String newIntface = intMeth.getKey();
1304                         int newObjectId = mapNewIntfaceObjId.get(newIntface);
1305                         println("if (_objectId == object" + newObjectId + "Id) {");
1306                         println("if (!set" + newObjectId + "Allowed.contains(methodId)) {");
1307                         println("throw new Error(\"Object with object Id: \" + _objectId + \"  is not allowed to access method: \" + methodId);");
1308                         println("}");
1309                         println("else {");
1310                         println("throw new Error(\"Object Id: \" + _objectId + \" not recognized!\");");
1311                         println("}");
1312                         println("}");
1313                 }
1314         }
1315
1316
1317         /**
1318          * HELPER: writeJavaWaitRequestInvokeMethod() writes the main loop of the skeleton class
1319          */
1320         private void writeJavaWaitRequestInvokeMethod(Collection<String> methods, InterfaceDecl intDecl, boolean callbackExist, String intface) {
1321
1322                 // Use this set to handle two same methodIds
1323                 Set<String> uniqueMethodIds = new HashSet<String>();
1324                 println("private void ___waitRequestInvokeMethod() throws IOException {");
1325                 // Write variables here if we have callbacks or enums or structs
1326                 println("while (true) {");
1327                 println("rmiObj.getMethodBytes();");
1328                 println("int _objectId = rmiObj.getObjectId();");
1329                 println("int methodId = rmiObj.getMethodId();");
1330                 // Generate permission check
1331                 writeJavaMethodPermission(intface);
1332                 println("switch (methodId) {");
1333                 // Print methods and method Ids
1334                 for (String method : methods) {
1335                         String methodId = intDecl.getMethodId(method);
1336                         int methodNumId = intDecl.getMethodNumId(method);
1337                         print("case " + methodNumId + ": ___");
1338                         String helperMethod = methodId;
1339                         if (uniqueMethodIds.contains(methodId))
1340                                 helperMethod = helperMethod + methodNumId;
1341                         else
1342                                 uniqueMethodIds.add(methodId);
1343                         println(helperMethod + "(); break;");
1344                 }
1345                 String method = "___initCallBack()";
1346                 // Print case -9999 (callback handler) if callback exists
1347                 if (callbackExist) {
1348                         int methodId = intDecl.getHelperMethodNumId(method);
1349                         println("case " + methodId + ": ___regCB(); break;");
1350                 }
1351                 println("default: ");
1352                 println("throw new Error(\"Method Id \" + methodId + \" not recognized!\");");
1353                 println("}");
1354                 println("}");
1355                 println("}\n");
1356         }
1357
1358
1359         /**
1360          * generateJavaSkeletonClass() generate skeletons based on the methods list in Java
1361          */
1362         public void generateJavaSkeletonClass() throws IOException {
1363
1364                 // Create a new directory
1365                 String path = createDirectories(dir, subdir);
1366                 for (String intface : mapIntfacePTH.keySet()) {
1367                         // Open a new file to write into
1368                         String newSkelClass = intface + "_Skeleton";
1369                         FileWriter fw = new FileWriter(path + "/" + newSkelClass + ".java");
1370                         pw = new PrintWriter(new BufferedWriter(fw));
1371                         // Pass in set of methods and get import classes
1372                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
1373                         InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
1374                         List<String> methods = intDecl.getMethods();
1375                         Set<String> importClasses = getImportClasses(methods, intDecl);
1376                         List<String> stdImportClasses = getStandardJavaImportClasses();
1377                         List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
1378                         printImportStatements(allImportClasses);
1379                         // Find out if there are callback objects
1380                         Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
1381                         boolean callbackExist = !callbackClasses.isEmpty();
1382                         // Write class header
1383                         println("");
1384                         println("public class " + newSkelClass  + " implements " + intface + " {\n");
1385                         // Write properties
1386                         writePropertiesJavaSkeleton(intface, callbackExist, intDecl);
1387                         // Write constructor
1388                         writeConstructorJavaSkeleton(newSkelClass, intface);
1389                         // Write methods
1390                         writeMethodJavaSkeleton(methods, intDecl, callbackClasses, false);
1391                         // Write method helper
1392                         writeMethodHelperJavaSkeleton(methods, intDecl, callbackClasses);
1393                         // Write waitRequestInvokeMethod() - main loop
1394                         writeJavaWaitRequestInvokeMethod(methods, intDecl, callbackExist, intface);
1395                         println("}");
1396                         pw.close();
1397                         System.out.println("IoTCompiler: Generated skeleton class " + newSkelClass + ".java...");
1398                 }
1399         }
1400
1401
1402         /**
1403          * HELPER: writePropertiesJavaCallbackSkeleton() writes the properties of the callback skeleton class
1404          */
1405         private void writePropertiesJavaCallbackSkeleton(String intface, boolean callbackExist) {
1406
1407                 println("private " + intface + " mainObj;");
1408                 // For callback skeletons, this is its own object Id
1409                 println("private static int objectId = 0;");
1410                 // Callback
1411                 if (callbackExist) {
1412                         println("private static int objIdCnt = 0;");
1413                         println("private IoTRMICall rmiCall;");
1414                 }
1415                 println("\n");
1416         }
1417
1418
1419         /**
1420          * HELPER: writeConstructorJavaCallbackSkeleton() writes the constructor of the skeleton class
1421          */
1422         private void writeConstructorJavaCallbackSkeleton(String newSkelClass, String intface) {
1423
1424                 println("public " + newSkelClass + "(" + intface + " _mainObj, int _objectId) throws Exception {");
1425                 println("mainObj = _mainObj;");
1426                 println("objectId = _objectId;");
1427                 println("}\n");
1428         }
1429
1430
1431         /**
1432          * HELPER: writeMethodHelperJavaCallbackSkeleton() writes the method helper of the callback skeleton class
1433          */
1434         private void writeMethodHelperJavaCallbackSkeleton(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
1435
1436                 // Use this set to handle two same methodIds
1437                 Set<String> uniqueMethodIds = new HashSet<String>();
1438                 for (String method : methods) {
1439
1440                         List<String> methParams = intDecl.getMethodParams(method);
1441                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1442                         String methodId = intDecl.getMethodId(method);
1443                         print("public void ___");
1444                         String helperMethod = methodId;
1445                         if (uniqueMethodIds.contains(methodId))
1446                                 helperMethod = helperMethod + intDecl.getMethodNumId(method);
1447                         else
1448                                 uniqueMethodIds.add(methodId);
1449                         // Check if this is "void"
1450                         String retType = intDecl.getMethodType(method);
1451                         if (retType.equals("void"))
1452                                 println(helperMethod + "(IoTRMIObject rmiObj) {");
1453                         else
1454                                 println(helperMethod + "(IoTRMIObject rmiObj) throws IOException {");
1455                         // Now, write the helper body of skeleton!
1456                         writeStdMethodHelperBodyJavaSkeleton(intDecl, methParams, methPrmTypes, method, callbackClasses);
1457                         println("}\n");
1458                 }
1459         }
1460
1461
1462         /**
1463          * HELPER: writeJavaCallbackWaitRequestInvokeMethod() writes the main loop of the skeleton class
1464          */
1465         private void writeJavaCallbackWaitRequestInvokeMethod(Collection<String> methods, InterfaceDecl intDecl, boolean callbackExist) {
1466
1467                 // Use this set to handle two same methodIds
1468                 Set<String> uniqueMethodIds = new HashSet<String>();
1469                 println("public void invokeMethod(IoTRMIObject rmiObj) throws IOException {");
1470                 // Write variables here if we have callbacks or enums or structs
1471                 println("int methodId = rmiObj.getMethodId();");
1472                 // TODO: code the permission check here!
1473                 println("switch (methodId) {");
1474                 // Print methods and method Ids
1475                 for (String method : methods) {
1476                         String methodId = intDecl.getMethodId(method);
1477                         int methodNumId = intDecl.getMethodNumId(method);
1478                         print("case " + methodNumId + ": ___");
1479                         String helperMethod = methodId;
1480                         if (uniqueMethodIds.contains(methodId))
1481                                 helperMethod = helperMethod + methodNumId;
1482                         else
1483                                 uniqueMethodIds.add(methodId);
1484                         println(helperMethod + "(rmiObj); break;");
1485                 }
1486                 String method = "___initCallBack()";
1487                 // Print case -9999 (callback handler) if callback exists
1488                 if (callbackExist) {
1489                         int methodId = intDecl.getHelperMethodNumId(method);
1490                         println("case " + methodId + ": ___regCB(rmiObj); break;");
1491                 }
1492                 println("default: ");
1493                 println("throw new Error(\"Method Id \" + methodId + \" not recognized!\");");
1494                 println("}");
1495                 println("}\n");
1496         }
1497
1498
1499         /**
1500          * generateJavaCallbackSkeletonClass() generate callback skeletons based on the methods list in Java
1501          */
1502         public void generateJavaCallbackSkeletonClass() throws IOException {
1503
1504                 // Create a new directory
1505                 String path = createDirectories(dir, subdir);
1506                 for (String intface : mapIntfacePTH.keySet()) {
1507                         // Open a new file to write into
1508                         String newSkelClass = intface + "_CallbackSkeleton";
1509                         FileWriter fw = new FileWriter(path + "/" + newSkelClass + ".java");
1510                         pw = new PrintWriter(new BufferedWriter(fw));
1511                         // Pass in set of methods and get import classes
1512                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
1513                         InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
1514                         List<String> methods = intDecl.getMethods();
1515                         Set<String> importClasses = getImportClasses(methods, intDecl);
1516                         List<String> stdImportClasses = getStandardJavaImportClasses();
1517                         List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
1518                         printImportStatements(allImportClasses);
1519                         // Find out if there are callback objects
1520                         Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
1521                         boolean callbackExist = !callbackClasses.isEmpty();
1522                         // Write class header
1523                         println("");
1524                         println("public class " + newSkelClass  + " implements " + intface + " {\n");
1525                         // Write properties
1526                         writePropertiesJavaCallbackSkeleton(intface, callbackExist);
1527                         // Write constructor
1528                         writeConstructorJavaCallbackSkeleton(newSkelClass, intface);
1529                         // Write methods
1530                         writeMethodJavaSkeleton(methods, intDecl, callbackClasses, true);
1531                         // Write method helper
1532                         writeMethodHelperJavaCallbackSkeleton(methods, intDecl, callbackClasses);
1533                         // Write waitRequestInvokeMethod() - main loop
1534                         writeJavaCallbackWaitRequestInvokeMethod(methods, intDecl, callbackExist);
1535                         println("}");
1536                         pw.close();
1537                         System.out.println("IoTCompiler: Generated callback skeleton class " + newSkelClass + ".java...");
1538                 }
1539         }
1540
1541
1542         /**
1543          * HELPER: writeMethodCplusLocalInterface() writes the method of the interface
1544          */
1545         private void writeMethodCplusLocalInterface(Collection<String> methods, InterfaceDecl intDecl) {
1546
1547                 for (String method : methods) {
1548
1549                         List<String> methParams = intDecl.getMethodParams(method);
1550                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1551                         print("virtual " + checkAndGetCplusType(intDecl.getMethodType(method)) + " " +
1552                                 intDecl.getMethodId(method) + "(");
1553                         for (int i = 0; i < methParams.size(); i++) {
1554                                 // Check for params with driver class types and exchange it 
1555                                 //              with its remote interface
1556                                 String paramType = checkAndGetParamClass(methPrmTypes.get(i));
1557                                 paramType = checkAndGetCplusType(paramType);
1558                                 // Check for arrays - translate into vector in C++
1559                                 String paramComplete = checkAndGetCplusArray(paramType, methParams.get(i));
1560                                 print(paramComplete);
1561                                 // Check if this is the last element (don't print a comma)
1562                                 if (i != methParams.size() - 1) {
1563                                         print(", ");
1564                                 }
1565                         }
1566                         println(") = 0;");
1567                 }
1568         }
1569
1570
1571         /**
1572          * HELPER: writeMethodCplusInterface() writes the method of the interface
1573          */
1574         private void writeMethodCplusInterface(Collection<String> methods, InterfaceDecl intDecl) {
1575
1576                 for (String method : methods) {
1577
1578                         List<String> methParams = intDecl.getMethodParams(method);
1579                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1580                         print("virtual " + checkAndGetCplusType(intDecl.getMethodType(method)) + " " +
1581                                 intDecl.getMethodId(method) + "(");
1582                         for (int i = 0; i < methParams.size(); i++) {
1583                                 // Check for params with driver class types and exchange it 
1584                                 //              with its remote interface
1585                                 String paramType = methPrmTypes.get(i);
1586                                 paramType = checkAndGetCplusType(paramType);
1587                                 // Check for arrays - translate into vector in C++
1588                                 String paramComplete = checkAndGetCplusArray(paramType, methParams.get(i));
1589                                 print(paramComplete);
1590                                 // Check if this is the last element (don't print a comma)
1591                                 if (i != methParams.size() - 1) {
1592                                         print(", ");
1593                                 }
1594                         }
1595                         println(") = 0;");
1596                 }
1597         }
1598
1599
1600         /**
1601          * HELPER: generateEnumCplus() writes the enumeration declaration
1602          */
1603         public void generateEnumCplus() throws IOException {
1604
1605                 // Create a new directory
1606                 createDirectory(dir);
1607                 for (String intface : mapIntfacePTH.keySet()) {
1608                         // Get the right StructDecl
1609                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
1610                         EnumDecl enumDecl = (EnumDecl) decHandler.getEnumDecl(intface);
1611                         Set<String> enumTypes = enumDecl.getEnumDeclarations();
1612                         // Iterate over enum declarations
1613                         for (String enType : enumTypes) {
1614                                 // Open a new file to write into
1615                                 FileWriter fw = new FileWriter(dir + "/" + enType + ".hpp");
1616                                 pw = new PrintWriter(new BufferedWriter(fw));
1617                                 // Write file headers
1618                                 println("#ifndef _" + enType.toUpperCase() + "_HPP__");
1619                                 println("#define _" + enType.toUpperCase() + "_HPP__");
1620                                 println("enum " + enType + " {");
1621                                 List<String> enumMembers = enumDecl.getMembers(enType);
1622                                 for (int i = 0; i < enumMembers.size(); i++) {
1623
1624                                         String member = enumMembers.get(i);
1625                                         print(member);
1626                                         // Check if this is the last element (don't print a comma)
1627                                         if (i != enumMembers.size() - 1)
1628                                                 println(",");
1629                                         else
1630                                                 println("");
1631                                 }
1632                                 println("};\n");
1633                                 println("#endif");
1634                                 pw.close();
1635                                 System.out.println("IoTCompiler: Generated enum " + enType + ".hpp...");
1636                         }
1637                 }
1638         }
1639
1640
1641         /**
1642          * HELPER: generateStructCplus() writes the struct declaration
1643          */
1644         public void generateStructCplus() throws IOException {
1645
1646                 // Create a new directory
1647                 createDirectory(dir);
1648                 for (String intface : mapIntfacePTH.keySet()) {
1649                         // Get the right StructDecl
1650                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
1651                         StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
1652                         List<String> structTypes = structDecl.getStructTypes();
1653                         // Iterate over enum declarations
1654                         for (String stType : structTypes) {
1655                                 // Open a new file to write into
1656                                 FileWriter fw = new FileWriter(dir + "/" + stType + ".hpp");
1657                                 pw = new PrintWriter(new BufferedWriter(fw));
1658                                 // Write file headers
1659                                 println("#ifndef _" + stType.toUpperCase() + "_HPP__");
1660                                 println("#define _" + stType.toUpperCase() + "_HPP__");
1661                                 println("struct " + stType + " {");
1662                                 List<String> structMemberTypes = structDecl.getMemberTypes(stType);
1663                                 List<String> structMembers = structDecl.getMembers(stType);
1664                                 for (int i = 0; i < structMembers.size(); i++) {
1665
1666                                         String memberType = structMemberTypes.get(i);
1667                                         String member = structMembers.get(i);
1668                                         String structTypeC = checkAndGetCplusType(memberType);
1669                                         String structComplete = checkAndGetCplusArray(structTypeC, member);
1670                                         println(structComplete + ";");
1671                                 }
1672                                 println("};\n");
1673                                 println("#endif");
1674                                 pw.close();
1675                                 System.out.println("IoTCompiler: Generated struct " + stType + ".hpp...");
1676                         }
1677                 }
1678         }
1679
1680
1681         /**
1682          * generateCplusLocalInterfaces() writes the local interfaces and provides type-checking.
1683          * <p>
1684          * It needs to rewrite and exchange USERDEFINED types in input parameters of stub
1685          * and original interfaces, e.g. exchange Camera and CameraWithVideoAndRecording.
1686          * The local interface has to be the input parameter for the stub and the stub 
1687          * interface has to be the input parameter for the local class.
1688          */
1689         public void generateCplusLocalInterfaces() throws IOException {
1690
1691                 // Create a new directory
1692                 createDirectory(dir);
1693                 for (String intface : mapIntfacePTH.keySet()) {
1694                         // Open a new file to write into
1695                         FileWriter fw = new FileWriter(dir + "/" + intface + ".hpp");
1696                         pw = new PrintWriter(new BufferedWriter(fw));
1697                         // Write file headers
1698                         println("#ifndef _" + intface.toUpperCase() + "_HPP__");
1699                         println("#define _" + intface.toUpperCase() + "_HPP__");
1700                         println("#include <iostream>");
1701                         // Pass in set of methods and get include classes
1702                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
1703                         InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
1704                         List<String> methods = intDecl.getMethods();
1705                         Set<String> includeClasses = getIncludeClasses(methods, intDecl, intface, true);
1706                         printIncludeStatements(includeClasses); println("");
1707                         println("using namespace std;\n");
1708                         // Write enum if any...
1709                         //EnumDecl enumDecl = (EnumDecl) decHandler.getEnumDecl(intface);
1710                         //writeEnumCplus(enumDecl);
1711                         // Write struct if any...
1712                         //StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
1713                         //writeStructCplus(structDecl);
1714                         println("class " + intface); println("{");
1715                         println("public:");
1716                         // Write methods
1717                         writeMethodCplusLocalInterface(methods, intDecl);
1718                         println("};");
1719                         println("#endif");
1720                         pw.close();
1721                         System.out.println("IoTCompiler: Generated local interface " + intface + ".hpp...");
1722                 }
1723         }
1724
1725
1726         /**
1727          * generateCPlusInterfaces() generate stub interfaces based on the methods list in C++
1728          * <p>
1729          * For C++ we use virtual classe as interface
1730          */
1731         public void generateCPlusInterfaces() throws IOException {
1732
1733                 // Create a new directory
1734                 String path = createDirectories(dir, subdir);
1735                 for (String intface : mapIntfacePTH.keySet()) {
1736
1737                         Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
1738                         for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
1739
1740                                 // Open a new file to write into
1741                                 String newIntface = intMeth.getKey();
1742                                 FileWriter fw = new FileWriter(path + "/" + newIntface + ".hpp");
1743                                 pw = new PrintWriter(new BufferedWriter(fw));
1744                                 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
1745                                 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
1746                                 // Write file headers
1747                                 println("#ifndef _" + newIntface.toUpperCase() + "_HPP__");
1748                                 println("#define _" + newIntface.toUpperCase() + "_HPP__");
1749                                 println("#include <iostream>");
1750                                 // Pass in set of methods and get import classes
1751                                 Set<String> includeClasses = getIncludeClasses(intMeth.getValue(), intDecl, intface, false);
1752                                 List<String> stdIncludeClasses = getStandardCplusIncludeClasses();
1753                                 List<String> allIncludeClasses = getAllLibClasses(stdIncludeClasses, includeClasses);
1754                                 printIncludeStatements(allIncludeClasses); println("");                 
1755                                 println("using namespace std;\n");
1756                                 println("class " + newIntface);
1757                                 println("{");
1758                                 println("public:");
1759                                 // Write methods
1760                                 writeMethodCplusInterface(intMeth.getValue(), intDecl);
1761                                 println("};");
1762                                 println("#endif");
1763                                 pw.close();
1764                                 System.out.println("IoTCompiler: Generated interface " + newIntface + ".hpp...");
1765                         }
1766                 }
1767         }
1768
1769
1770         /**
1771          * HELPER: writeMethodCplusStub() writes the method of the stub
1772          */
1773         private void writeMethodCplusStub(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
1774
1775                 for (String method : methods) {
1776
1777                         List<String> methParams = intDecl.getMethodParams(method);
1778                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1779                         print(checkAndGetCplusType(intDecl.getMethodType(method)) + " " +
1780                                 intDecl.getMethodId(method) + "(");
1781                         boolean isCallbackMethod = false;
1782                         String callbackType = null;
1783                         for (int i = 0; i < methParams.size(); i++) {
1784
1785                                 String paramType = methPrmTypes.get(i);
1786                                 // Check if this has callback object
1787                                 if (callbackClasses.contains(paramType)) {
1788                                         isCallbackMethod = true;
1789                                         callbackType = paramType;       
1790                                         // Even if there're 2 callback arguments, we expect them to be of the same interface
1791                                 }
1792                                 String methPrmType = checkAndGetCplusType(methPrmTypes.get(i));
1793                                 String methParamComplete = checkAndGetCplusArray(methPrmType, methParams.get(i));
1794                                 print(methParamComplete);
1795                                 // Check if this is the last element (don't print a comma)
1796                                 if (i != methParams.size() - 1) {
1797                                         print(", ");
1798                                 }
1799                         }
1800                         println(") { ");
1801                         if (isCallbackMethod)
1802                                 writeCallbackMethodBodyCplusStub(intDecl, methParams, methPrmTypes, method, callbackType);
1803                         else
1804                                 writeStdMethodBodyCplusStub(intDecl, methParams, methPrmTypes, method);
1805                         println("}\n");
1806                         // Write the init callback helper method
1807                         if (isCallbackMethod) {
1808                                 writeInitCallbackCplusStub(callbackType, intDecl);
1809                                 writeInitCallbackSendInfoCplusStub(intDecl);
1810                         }
1811                 }
1812         }
1813
1814
1815         /**
1816          * HELPER: writeCallbackMethodBodyCplusStub() writes the callback method of the stub class
1817          */
1818         private void writeCallbackMethodBodyCplusStub(InterfaceDecl intDecl, List<String> methParams,
1819                         List<String> methPrmTypes, String method, String callbackType) {
1820
1821                 // Check if this is single object, array, or list of objects
1822                 boolean isArrayOrList = false;
1823                 String callbackParam = null;
1824                 for (int i = 0; i < methParams.size(); i++) {
1825
1826                         String paramType = methPrmTypes.get(i);
1827                         if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
1828                                 String param = methParams.get(i);
1829                                 if (isArrayOrList(paramType, param)) {  // Generate loop
1830                                         println("for (" + paramType + "* cb : " + getSimpleIdentifier(param) + ") {");
1831                                         println(callbackType + "_CallbackSkeleton* skel = new " + callbackType + "_CallbackSkeleton(cb, objIdCnt++);");
1832                                         isArrayOrList = true;
1833                                         callbackParam = getSimpleIdentifier(param);
1834                                 } else
1835                                         println(callbackType + "_CallbackSkeleton* skel = new " + callbackType + "_CallbackSkeleton(" +
1836                                                 getSimpleIdentifier(param) + ", objIdCnt++);");
1837                                 println("vecCallbackObj.push_back(skel);");
1838                                 if (isArrayOrList(paramType, param))
1839                                         println("}");
1840                         }
1841                 }
1842                 println("int numParam = " + methParams.size() + ";");
1843                 println("int methodId = " + intDecl.getMethodNumId(method) + ";");
1844                 String retType = intDecl.getMethodType(method);
1845                 String retTypeC = checkAndGetCplusType(retType);
1846                 println("string retType = \"" + checkAndGetCplusArrayType(retTypeC) + "\";");
1847                 // Generate array of parameter types
1848                 print("string paramCls[] = { ");
1849                 for (int i = 0; i < methParams.size(); i++) {
1850                         String paramType = methPrmTypes.get(i);
1851                         if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
1852                                 print("\"int\"");
1853                         } else { // Generate normal classes if it's not a callback object
1854                                 String paramTypeC = checkAndGetCplusType(methPrmTypes.get(i));
1855                                 String prmType = checkAndGetCplusArrayType(paramTypeC, methParams.get(i));
1856                                 print("\"" + prmType + "\"");
1857                         }
1858                         if (i != methParams.size() - 1) // Check if this is the last element
1859                                 print(", ");
1860                 }
1861                 println(" };");
1862                 print("int ___paramCB = ");
1863                 if (isArrayOrList)
1864                         println(callbackParam + ".size();");
1865                 else
1866                         println("1;");
1867                 // Generate array of parameter objects
1868                 print("void* paramObj[] = { ");
1869                 for (int i = 0; i < methParams.size(); i++) {
1870                         String paramType = methPrmTypes.get(i);
1871                         if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
1872                                 print("&___paramCB");
1873                         } else
1874                                 print(getSimpleIdentifier(methParams.get(i)));
1875                         if (i != methParams.size() - 1)
1876                                 print(", ");
1877                 }
1878                 println(" };");
1879                 // Check if this is "void"
1880                 if (retType.equals("void")) {
1881                         println("void* retObj = NULL;");
1882                         println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
1883                 } else { // We do have a return value
1884                         if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
1885                                 println(checkAndGetCplusType(retType) + " retVal;");
1886                         else
1887                                 println(checkAndGetCplusType(retType) + " retVal = " + generateCplusInitializer(retType) + ";");
1888                         println("void* retObj = &retVal;");
1889                         println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
1890                         println("return retVal;");
1891                 }
1892         }
1893
1894
1895         /**
1896          * HELPER: checkAndWriteEnumTypeCplusStub() writes the enum type (convert from enum to int)
1897          */
1898         private void checkAndWriteEnumTypeCplusStub(List<String> methParams, List<String> methPrmTypes) {
1899
1900                 // Iterate and find enum declarations
1901                 for (int i = 0; i < methParams.size(); i++) {
1902                         String paramType = methPrmTypes.get(i);
1903                         String param = methParams.get(i);
1904                         String simpleType = getSimpleType(paramType);
1905                         if (isEnumClass(simpleType)) {
1906                         // Check if this is enum type
1907                                 if (isArrayOrList(paramType, param)) {  // An array or vector
1908                                         println("int len" + i + " = " + param + ".size();");
1909                                         println("vector<int> paramEnum" + i + "(len);");
1910                                         println("for (int i = 0; i < len" + i + "; i++) {");
1911                                         println("paramEnum" + i + "[i] = (int) " + param + "[i];");
1912                                         println("}");
1913                                 } else {        // Just one element
1914                                         println("vector<int> paramEnum" + i + "(1);");
1915                                         println("paramEnum" + i + "[0] = (int) " + param + ";");
1916                                 }
1917                         }
1918                 }
1919         }
1920
1921
1922         /**
1923          * HELPER: checkAndWriteEnumRetTypeCplusStub() writes the enum return type (convert from enum to int)
1924          */
1925         private void checkAndWriteEnumRetTypeCplusStub(String retType) {
1926
1927                 // Strips off array "[]" for return type
1928                 String pureType = getSimpleArrayType(getSimpleType(retType));
1929                 // Take the inner type of generic
1930                 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
1931                         pureType = getTypeOfGeneric(retType)[0];
1932                 if (isEnumClass(pureType)) {
1933                 // Check if this is enum type
1934                         println("vector<int> retEnumInt;");
1935                         println("void* retObj = &retEnumInt;");
1936                         println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
1937                         if (isArrayOrList(retType, retType)) {  // An array or vector
1938                                 println("int retLen = retEnumInt.size();");
1939                                 println("vector<" + pureType + "> retVal(retLen);");
1940                                 println("for (int i = 0; i < retLen; i++) {");
1941                                 println("retVal[i] = (" + pureType + ") retEnumInt[i];");
1942                                 println("}");
1943                         } else {        // Just one element
1944                                 println(pureType + " retVal = (" + pureType + ") retEnumInt[0];");
1945                         }
1946                         println("return retVal;");
1947                 }
1948         }
1949
1950
1951         /**
1952          * HELPER: writeStdMethodBodyCplusStub() writes the standard method body in the stub class
1953          */
1954         private void writeStdMethodBodyCplusStub(InterfaceDecl intDecl, List<String> methParams,
1955                         List<String> methPrmTypes, String method) {
1956
1957                 println("int numParam = " + methParams.size() + ";");
1958                 println("int methodId = " + intDecl.getMethodNumId(method) + ";");
1959                 String retType = intDecl.getMethodType(method);
1960                 String retTypeC = checkAndGetCplusType(retType);
1961                 println("string retType = \"" + checkAndGetCplusArrayType(getEnumType(retTypeC)) + "\";");
1962                 // Generate array of parameter types
1963                 print("string paramCls[] = { ");
1964                 for (int i = 0; i < methParams.size(); i++) {
1965                         String paramTypeC = checkAndGetCplusType(methPrmTypes.get(i));
1966                         String paramType = checkAndGetCplusArrayType(paramTypeC, methParams.get(i));
1967                         print("\"" + getEnumType(paramType) + "\"");
1968                         // Check if this is the last element (don't print a comma)
1969                         if (i != methParams.size() - 1) {
1970                                 print(", ");
1971                         }
1972                 }
1973                 println(" };");
1974                 checkAndWriteEnumTypeCplusStub(methParams, methPrmTypes);
1975                 // Generate array of parameter objects
1976                 print("void* paramObj[] = { ");
1977                 for (int i = 0; i < methParams.size(); i++) {
1978                         print("&" + getEnumParam(methPrmTypes.get(i), getSimpleIdentifier(methParams.get(i)), i));
1979                         // Check if this is the last element (don't print a comma)
1980                         if (i != methParams.size() - 1) {
1981                                 print(", ");
1982                         }
1983                 }
1984                 println(" };");
1985                 // Check if this is "void"
1986                 if (retType.equals("void")) {
1987                         println("void* retObj = NULL;");
1988                         println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
1989                 } else { // We do have a return value
1990                         if (getParamCategory(retType) == ParamCategory.ENUM) {
1991                                 checkAndWriteEnumRetTypeCplusStub(retType);
1992                         } else {
1993                                 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
1994                                         println(checkAndGetCplusType(retType) + " retVal;");
1995                                 else
1996                                         println(checkAndGetCplusType(retType) + " retVal = " + generateCplusInitializer(retType) + ";");
1997                                 println("void* retObj = &retVal;");
1998                                 println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
1999                                 println("return retVal;");
2000                         }
2001                 }
2002         }
2003
2004
2005         /**
2006          * HELPER: writePropertiesCplusStub() writes the properties of the stub class
2007          */
2008         private void writePropertiesCplusPermission(String intface) {
2009
2010                 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
2011                 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
2012                         String newIntface = intMeth.getKey();
2013                         int newObjectId = mapNewIntfaceObjId.get(newIntface);
2014                         println("const static int object" + newObjectId + "Id = " + newObjectId + ";");
2015                         println("const static set<int> set" + newObjectId + "Allowed;");
2016                 }
2017         }       
2018
2019         /**
2020          * HELPER: writePropertiesCplusStub() writes the properties of the stub class
2021          */
2022         private void writePropertiesCplusStub(String intface, String newIntface, boolean callbackExist, Set<String> callbackClasses) {
2023
2024                 println("IoTRMICall *rmiCall;");
2025                 //println("IoTRMIObject\t\t\t*rmiObj;");
2026                 println("string address;");
2027                 println("vector<int> ports;\n");
2028                 // Get the object Id
2029                 Integer objId = mapIntfaceObjId.get(intface);
2030                 println("const static int objectId = " + objId + ";");
2031                 mapNewIntfaceObjId.put(newIntface, objId);
2032                 mapIntfaceObjId.put(intface, objId++);
2033                 if (callbackExist) {
2034                 // We assume that each class only has one callback interface for now
2035                         Iterator it = callbackClasses.iterator();
2036                         String callbackType = (String) it.next();
2037                         println("// Callback properties");
2038                         println("IoTRMIObject *rmiObj;");
2039                         println("vector<" + callbackType + "*> vecCallbackObj;");
2040                         println("static int objIdCnt;");
2041                         // Generate permission stuff for callback stubs
2042                         writePropertiesCplusPermission(callbackType);
2043                 }
2044                 println("\n");
2045         }
2046
2047
2048         /**
2049          * HELPER: writeConstructorCplusStub() writes the constructor of the stub class
2050          */
2051         private void writeConstructorCplusStub(String newStubClass, boolean callbackExist, Set<String> callbackClasses) {
2052
2053                 println(newStubClass + 
2054                         "(int _port, const char* _address, int _rev, bool* _bResult, vector<int> _ports) {");
2055                 println("address = _address;");
2056                 println("ports = _ports;");
2057                 println("rmiCall = new IoTRMICall(_port, _address, _rev, _bResult);");
2058                 if (callbackExist) {
2059                         println("objIdCnt = 0;");
2060                         Iterator it = callbackClasses.iterator();
2061                         String callbackType = (String) it.next();
2062                         println("thread th1 (&" + newStubClass + "::___initCallBack, this);");
2063                         println("th1.detach();");
2064                         println("___regCB();");
2065                 }
2066                 println("}\n");
2067         }
2068
2069
2070         /**
2071          * HELPER: writeDeconstructorCplusStub() writes the deconstructor of the stub class
2072          */
2073         private void writeDeconstructorCplusStub(String newStubClass, boolean callbackExist, Set<String> callbackClasses) {
2074
2075                 println("~" + newStubClass + "() {");
2076                 println("if (rmiCall != NULL) {");
2077                 println("delete rmiCall;");
2078                 println("rmiCall = NULL;");
2079                 println("}");
2080                 if (callbackExist) {
2081                 // We assume that each class only has one callback interface for now
2082                         println("if (rmiObj != NULL) {");
2083                         println("delete rmiObj;");
2084                         println("rmiObj = NULL;");
2085                         println("}");
2086                         Iterator it = callbackClasses.iterator();
2087                         String callbackType = (String) it.next();
2088                         println("for(" + callbackType + "* cb : vecCallbackObj) {");
2089                         println("delete cb;");
2090                         println("cb = NULL;");
2091                         println("}");
2092                 }
2093                 println("}");
2094                 println("");
2095         }
2096
2097
2098         /**
2099          * HELPER: writeCplusMethodCallbackPermission() writes permission checks in stub for callbacks
2100          */
2101         private void writeCplusMethodCallbackPermission(String intface) {
2102
2103                 println("int methodId = IoTRMIObject::getMethodId(method);");
2104                 // Get all the different stubs
2105                 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
2106                 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
2107                         String newIntface = intMeth.getKey();
2108                         int newObjectId = mapNewIntfaceObjId.get(newIntface);
2109                         println("if (set" + newObjectId + "Allowed.find(methodId) == set" + newObjectId + "Allowed.end()) {");
2110                         println("cerr << \"Callback object for " + intface + " is not allowed to access method: \" << methodId;");
2111                         println("exit(-1);");
2112                         println("}");
2113                 }
2114         }
2115
2116
2117         /**
2118          * HELPER: writeInitCallbackCplusStub() writes the initialization of callback
2119          */
2120         private void writeInitCallbackCplusStub(String intface, InterfaceDecl intDecl) {
2121
2122                 println("void ___initCallBack() {");
2123                 println("bool bResult = false;");
2124                 println("rmiObj = new IoTRMIObject(ports[0], &bResult);");
2125                 println("while (true) {");
2126                 println("char* method = rmiObj->getMethodBytes();");
2127                 writeCplusMethodCallbackPermission(intface);
2128                 println("int objId = IoTRMIObject::getObjectId(method);");
2129                 println("if (objId < vecCallbackObj.size()) {   // Check if still within range");
2130                 println(intface + "_CallbackSkeleton* skel = dynamic_cast<" + intface + 
2131                         "_CallbackSkeleton*> (vecCallbackObj.at(objId));");
2132                 println("skel->invokeMethod(rmiObj);");
2133                 println("} else {");
2134                 println("cerr << \"Illegal object Id: \" << to_string(objId);");
2135                 // TODO: perhaps need to change this into "throw" to make it cleaner (allow stack unfolding)
2136                 println("exit(-1);");
2137                 println("}");
2138                 println("}");
2139                 println("}\n");
2140         }
2141
2142
2143         /**
2144          * HELPER: writeInitCallbackSendInfoCplusStub() writes the initialization of callback
2145          */
2146         private void writeInitCallbackSendInfoCplusStub(InterfaceDecl intDecl) {
2147
2148                 // Generate info sending part
2149                 println("void ___regCB() {");
2150                 println("int numParam = 3;");
2151                 String method = "___initCallBack()";
2152                 println("int methodId = " + intDecl.getHelperMethodNumId(method) + ";");
2153                 println("string retType = \"void\";");
2154                 println("string paramCls[] = { \"int\", \"string\", \"int\" };");
2155                 println("int rev = 0;");
2156                 println("void* paramObj[] = { &ports[0], &address, &rev };");
2157                 println("void* retObj = NULL;");
2158                 println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
2159                 println("}\n");
2160         }
2161
2162
2163         /**
2164          * generateCPlusStubClasses() generate stubs based on the methods list in C++
2165          */
2166         public void generateCPlusStubClasses() throws IOException {
2167
2168                 // Create a new directory
2169                 String path = createDirectories(dir, subdir);
2170                 for (String intface : mapIntfacePTH.keySet()) {
2171
2172                         Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
2173                         for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
2174                                 // Open a new file to write into
2175                                 String newIntface = intMeth.getKey();
2176                                 String newStubClass = newIntface + "_Stub";
2177                                 FileWriter fw = new FileWriter(path + "/" + newStubClass + ".hpp");
2178                                 pw = new PrintWriter(new BufferedWriter(fw));
2179                                 // Write file headers
2180                                 println("#ifndef _" + newStubClass.toUpperCase() + "_HPP__");
2181                                 println("#define _" + newStubClass.toUpperCase() + "_HPP__");
2182                                 println("#include <iostream>");
2183                                 // Find out if there are callback objects
2184                                 Set<String> methods = intMeth.getValue();
2185                                 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2186                                 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
2187                                 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
2188                                 boolean callbackExist = !callbackClasses.isEmpty();
2189                                 if (callbackExist)      // Need thread library if this has callback
2190                                         println("#include <thread>");
2191                                 println("#include \"" + newIntface + ".hpp\""); println("");            
2192                                 println("using namespace std;"); println("");
2193                                 println("class " + newStubClass + " : public " + newIntface); println("{");
2194                                 println("private:\n");
2195                                 writePropertiesCplusStub(intface, newIntface, callbackExist, callbackClasses);
2196                                 println("public:\n");
2197                                 // Add default constructor and destructor
2198                                 println(newStubClass + "() { }"); println("");
2199                                 writeConstructorCplusStub(newStubClass, callbackExist, callbackClasses);
2200                                 writeDeconstructorCplusStub(newStubClass, callbackExist, callbackClasses);
2201                                 // Write methods
2202                                 writeMethodCplusStub(methods, intDecl, callbackClasses);
2203                                 print("}"); println(";");
2204                                 if (callbackExist)
2205                                         writePermissionInitializationCplus(intface, newStubClass, intDecl);
2206                                 println("#endif");
2207                                 pw.close();
2208                                 System.out.println("IoTCompiler: Generated stub class " + newStubClass + ".hpp...");
2209                         }
2210                 }
2211         }
2212
2213
2214         /**
2215          * HELPER: writePropertiesCplusCallbackStub() writes the properties of the stub class
2216          */
2217         private void writePropertiesCplusCallbackStub(String intface, String newIntface, boolean callbackExist, Set<String> callbackClasses) {
2218
2219                 println("IoTRMICall *rmiCall;");
2220                 // Get the object Id
2221                 println("static int objectId;");
2222                 if (callbackExist) {
2223                 // We assume that each class only has one callback interface for now
2224                         Iterator it = callbackClasses.iterator();
2225                         String callbackType = (String) it.next();
2226                         println("// Callback properties");
2227                         println("IoTRMIObject *rmiObj;");
2228                         println("vector<" + callbackType + "*> vecCallbackObj;");
2229                         println("static int objIdCnt;");
2230                         // TODO: Need to initialize address and ports if we want to have callback-in-callback
2231                         println("string address;");
2232                         println("vector<int> ports;\n");
2233                         writePropertiesCplusPermission(callbackType);
2234                 }
2235                 println("\n");
2236         }
2237
2238
2239         /**
2240          * HELPER: writeConstructorCplusCallbackStub() writes the constructor of the stub class
2241          */
2242         private void writeConstructorCplusCallbackStub(String newStubClass, boolean callbackExist, Set<String> callbackClasses) {
2243
2244                 println(newStubClass + "(IoTRMICall* _rmiCall, int _objectId) {");
2245                 println("objectId = _objectId;");
2246                 println("rmiCall = _rmiCall;");
2247                 if (callbackExist) {
2248                         Iterator it = callbackClasses.iterator();
2249                         String callbackType = (String) it.next();
2250                         println("thread th1 (&" + newStubClass + "::___initCallBack, this);");
2251                         println("th1.detach();");
2252                         println("___regCB();");
2253                 }
2254                 println("}\n");
2255         }
2256
2257
2258         /**
2259          * generateCPlusCallbackStubClasses() generate callback stubs based on the methods list in C++
2260          */
2261         public void generateCPlusCallbackStubClasses() throws IOException {
2262
2263                 // Create a new directory
2264                 String path = createDirectories(dir, subdir);
2265                 for (String intface : mapIntfacePTH.keySet()) {
2266
2267                         Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
2268                         for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
2269                                 // Open a new file to write into
2270                                 String newIntface = intMeth.getKey();
2271                                 String newStubClass = newIntface + "_CallbackStub";
2272                                 FileWriter fw = new FileWriter(path + "/" + newStubClass + ".hpp");
2273                                 pw = new PrintWriter(new BufferedWriter(fw));
2274                                 // Find out if there are callback objects
2275                                 Set<String> methods = intMeth.getValue();
2276                                 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2277                                 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
2278                                 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
2279                                 boolean callbackExist = !callbackClasses.isEmpty();
2280                                 // Write file headers
2281                                 println("#ifndef _" + newStubClass.toUpperCase() + "_HPP__");
2282                                 println("#define _" + newStubClass.toUpperCase() + "_HPP__");
2283                                 println("#include <iostream>");
2284                                 if (callbackExist)
2285                                         println("#include <thread>");
2286                                 println("#include \"" + newIntface + ".hpp\""); println("");            
2287                                 println("using namespace std;"); println("");
2288                                 println("class " + newStubClass + " : public " + newIntface); println("{");
2289                                 println("private:\n");
2290                                 writePropertiesCplusCallbackStub(intface, newIntface, callbackExist, callbackClasses);
2291                                 println("public:\n");
2292                                 // Add default constructor and destructor
2293                                 println(newStubClass + "() { }"); println("");
2294                                 writeConstructorCplusCallbackStub(newStubClass, callbackExist, callbackClasses);
2295                                 writeDeconstructorCplusStub(newStubClass, callbackExist, callbackClasses);
2296                                 // Write methods
2297                                 writeMethodCplusStub(methods, intDecl, callbackClasses);
2298                                 println("};");
2299                                 if (callbackExist)
2300                                         writePermissionInitializationCplus(intface, newStubClass, intDecl);
2301                                 println("#endif");
2302                                 pw.close();
2303                                 System.out.println("IoTCompiler: Generated callback stub class " + newIntface + ".hpp...");
2304                         }
2305                 }
2306         }
2307
2308
2309         /**
2310          * HELPER: writePropertiesCplusSkeleton() writes the properties of the skeleton class
2311          */
2312         private void writePropertiesCplusSkeleton(String intface, boolean callbackExist, Set<String> callbackClasses) {
2313
2314                 println(intface + " *mainObj;");
2315                 // Callback
2316                 if (callbackExist) {
2317                         Iterator it = callbackClasses.iterator();
2318                         String callbackType = (String) it.next();
2319                         String exchangeType = checkAndGetParamClass(callbackType);
2320                         println("// Callback properties");
2321                         println("static int objIdCnt;");
2322                         println("vector<" + exchangeType + "*> vecCallbackObj;");
2323                         println("IoTRMICall *rmiCall;");
2324                 }
2325                 println("IoTRMIObject *rmiObj;\n");
2326                 // Keep track of object Ids of all stubs registered to this interface
2327                 writePropertiesCplusPermission(intface);
2328                 println("\n");
2329         }
2330
2331
2332         /**
2333          * HELPER: writePermissionInitializationCplus() writes the initialization of permission set
2334          */
2335         private void writePermissionInitializationCplus(String intface, String newSkelClass, InterfaceDecl intDecl) {
2336
2337                 // Keep track of object Ids of all stubs registered to this interface
2338                 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
2339                 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
2340                         String newIntface = intMeth.getKey();
2341                         int newObjectId = mapNewIntfaceObjId.get(newIntface);
2342                         print("const set<int> " + newSkelClass + "::set" + newObjectId + "Allowed {");
2343                         Set<String> methodIds = intMeth.getValue();
2344                         int i = 0;
2345                         for (String methodId : methodIds) {
2346                                 int methodNumId = intDecl.getMethodNumId(methodId);
2347                                 print(Integer.toString(methodNumId));
2348                                 // Check if this is the last element (don't print a comma)
2349                                 if (i != methodIds.size() - 1) {
2350                                         print(", ");
2351                                 }
2352                                 i++;
2353                         }
2354                         println(" };");
2355                 }       
2356         }
2357
2358
2359         /**
2360          * HELPER: writeConstructorCplusSkeleton() writes the constructor of the skeleton class
2361          */
2362         private void writeConstructorCplusSkeleton(String newSkelClass, String intface, boolean callbackExist) {
2363
2364                 println(newSkelClass + "(" + intface + " *_mainObj, int _port) {");
2365                 println("bool _bResult = false;");
2366                 println("mainObj = _mainObj;");
2367                 println("rmiObj = new IoTRMIObject(_port, &_bResult);");
2368                 // Callback
2369                 if (callbackExist) {
2370                         println("objIdCnt = 0;");
2371                 }
2372                 //println("set0Allowed = Arrays.asList(object0Permission);");
2373                 println("___waitRequestInvokeMethod();");
2374                 println("}\n");
2375         }
2376
2377
2378         /**
2379          * HELPER: writeDeconstructorCplusSkeleton() writes the deconstructor of the skeleton class
2380          */
2381         private void writeDeconstructorCplusSkeleton(String newSkelClass, boolean callbackExist, Set<String> callbackClasses) {
2382
2383                 println("~" + newSkelClass + "() {");
2384                 println("if (rmiObj != NULL) {");
2385                 println("delete rmiObj;");
2386                 println("rmiObj = NULL;");
2387                 println("}");
2388                 if (callbackExist) {
2389                 // We assume that each class only has one callback interface for now
2390                         println("if (rmiCall != NULL) {");
2391                         println("delete rmiCall;");
2392                         println("rmiCall = NULL;");
2393                         println("}");
2394                         Iterator it = callbackClasses.iterator();
2395                         String callbackType = (String) it.next();
2396                         String exchangeType = checkAndGetParamClass(callbackType);
2397                         println("for(" + exchangeType + "* cb : vecCallbackObj) {");
2398                         println("delete cb;");
2399                         println("cb = NULL;");
2400                         println("}");
2401                 }
2402                 println("}");
2403                 println("");
2404         }
2405
2406
2407         /**
2408          * HELPER: writeStdMethodBodyCplusSkeleton() writes the standard method body in the skeleton class
2409          */
2410         private void writeStdMethodBodyCplusSkeleton(List<String> methParams, String methodId, String methodType) {
2411
2412                 if (methodType.equals("void"))
2413                         print("mainObj->" + methodId + "(");
2414                 else
2415                         print("return mainObj->" + methodId + "(");
2416                 for (int i = 0; i < methParams.size(); i++) {
2417
2418                         print(getSimpleIdentifier(methParams.get(i)));
2419                         // Check if this is the last element (don't print a comma)
2420                         if (i != methParams.size() - 1) {
2421                                 print(", ");
2422                         }
2423                 }
2424                 println(");");
2425         }
2426
2427
2428         /**
2429          * HELPER: writeInitCallbackCplusSkeleton() writes the init callback method for skeleton class
2430          */
2431         private void writeInitCallbackCplusSkeleton(boolean callbackSkeleton) {
2432
2433                 // This is a callback skeleton generation
2434                 if (callbackSkeleton)
2435                         println("void ___regCB(IoTRMIObject* rmiObj) {");
2436                 else
2437                         println("void ___regCB() {");
2438                 println("int numParam = 3;");
2439                 println("int param1 = 0;");
2440                 println("string param2 = \"\";");
2441                 println("int param3 = 0;");
2442                 println("void* paramObj[] = { &param1, &param2, &param3 };");
2443                 println("bool bResult = false;");
2444                 println("rmiCall = new IoTRMICall(param1, param2.c_str(), param3, &bResult);");
2445                 println("}\n");
2446         }
2447
2448
2449         /**
2450          * HELPER: writeMethodCplusSkeleton() writes the method of the skeleton class
2451          */
2452         private void writeMethodCplusSkeleton(Collection<String> methods, InterfaceDecl intDecl, 
2453                         Set<String> callbackClasses, boolean callbackSkeleton) {
2454
2455                 for (String method : methods) {
2456
2457                         List<String> methParams = intDecl.getMethodParams(method);
2458                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2459                         String methodId = intDecl.getMethodId(method);
2460                         String methodType = checkAndGetCplusType(intDecl.getMethodType(method));
2461                         print(methodType + " " + methodId + "(");
2462                         boolean isCallbackMethod = false;
2463                         String callbackType = null;
2464                         for (int i = 0; i < methParams.size(); i++) {
2465
2466                                 String origParamType = methPrmTypes.get(i);
2467                                 if (callbackClasses.contains(origParamType)) { // Check if this has callback object
2468                                         isCallbackMethod = true;
2469                                         callbackType = origParamType;   
2470                                 }
2471                                 String paramType = checkAndGetParamClass(methPrmTypes.get(i));
2472                                 String methPrmType = checkAndGetCplusType(paramType);
2473                                 String methParamComplete = checkAndGetCplusArray(methPrmType, methParams.get(i));
2474                                 print(methParamComplete);
2475                                 // Check if this is the last element (don't print a comma)
2476                                 if (i != methParams.size() - 1) {
2477                                         print(", ");
2478                                 }
2479                         }
2480                         println(") {");
2481                         // Now, write the body of skeleton!
2482                         writeStdMethodBodyCplusSkeleton(methParams, methodId, intDecl.getMethodType(method));
2483                         println("}\n");
2484                         if (isCallbackMethod)
2485                                 writeInitCallbackCplusSkeleton(callbackSkeleton);
2486                 }
2487         }
2488
2489
2490         /**
2491          * HELPER: writeCallbackCplusNumStubs() writes the numStubs variable
2492          */
2493         private void writeCallbackCplusNumStubs(List<String> methParams, List<String> methPrmTypes, String callbackType) {
2494
2495                 for (int i = 0; i < methParams.size(); i++) {
2496                         String paramType = methPrmTypes.get(i);
2497                         String param = methParams.get(i);
2498                         //if (callbackType.equals(paramType)) {
2499                         if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
2500                                 String exchParamType = checkAndGetParamClass(paramType);
2501                                 // Print array if this is array or list if this is a list of callback objects
2502                                 println("int numStubs" + i + " = 0;");
2503                         }
2504                 }
2505         }
2506
2507
2508         /**
2509          * HELPER: writeCallbackCplusStubGeneration() writes the callback stub generation part
2510          */
2511         private void writeCallbackCplusStubGeneration(List<String> methParams, List<String> methPrmTypes, String callbackType) {
2512
2513                 // Iterate over callback objects
2514                 for (int i = 0; i < methParams.size(); i++) {
2515                         String paramType = methPrmTypes.get(i);
2516                         String param = methParams.get(i);
2517                         // Generate a loop if needed
2518                         if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
2519                                 String exchParamType = checkAndGetParamClass(paramType);
2520                                 if (isArrayOrList(paramType, param)) {
2521                                         println("vector<" + exchParamType + "> stub;");
2522                                         println("for (int objId = 0; objId < numStubs" + i + "; objId++) {");
2523                                         println(exchParamType + "* cb" + i + " = new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt);");
2524                                         println("stub" + i + ".push_back(cb);");
2525                                         println("vecCallbackObj.push_back(cb);");
2526                                         println("objIdCnt++;");
2527                                         println("}");
2528                                 } else {
2529                                         println(exchParamType + "* stub" + i + " = new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt);");
2530                                         println("vecCallbackObj.push_back(stub" + i + ");");
2531                                         println("objIdCnt++;");
2532                                 }
2533                         }
2534                 }
2535         }
2536
2537
2538         /**
2539          * HELPER: checkAndWriteEnumTypeCplusSkeleton() writes the enum type (convert from enum to int)
2540          */
2541         private void checkAndWriteEnumTypeCplusSkeleton(List<String> methParams, List<String> methPrmTypes) {
2542
2543                 // Iterate and find enum declarations
2544                 for (int i = 0; i < methParams.size(); i++) {
2545                         String paramType = methPrmTypes.get(i);
2546                         String param = methParams.get(i);
2547                         String simpleType = getSimpleType(paramType);
2548                         if (isEnumClass(simpleType)) {
2549                         // Check if this is enum type
2550                                 if (isArrayOrList(paramType, param)) {  // An array
2551                                         println("int len" + i + " = paramEnumInt" + i + ".size();");
2552                                         println("vector<" + simpleType + "> paramEnum" + i + "(len" + i + ");");
2553                                         println("for (int i=0; i < len" + i + "; i++) {");
2554                                         println("paramEnum" + i + "[i] = (" + simpleType + ") paramEnumInt" + i + "[i];");
2555                                         println("}");
2556                                 } else {        // Just one element
2557                                         println(simpleType + " paramEnum" + i + ";");
2558                                         println("paramEnum" + i + " = (" + simpleType + ") paramEnumInt" + i + "[0];");
2559                                 }
2560                         }
2561                 }
2562         }
2563
2564
2565         /**
2566          * HELPER: checkAndWriteEnumRetTypeCplusSkeleton() writes the enum return type (convert from enum to int)
2567          */
2568         private void checkAndWriteEnumRetTypeCplusSkeleton(String retType) {
2569
2570                 // Strips off array "[]" for return type
2571                 String pureType = getSimpleArrayType(getSimpleType(retType));
2572                 // Take the inner type of generic
2573                 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
2574                         pureType = getTypeOfGeneric(retType)[0];
2575                 if (isEnumClass(pureType)) {
2576                 // Check if this is enum type
2577                         // Enum decoder
2578                         if (isArrayOrList(retType, retType)) {  // An array
2579                                 println("int retLen = retEnum.size();");
2580                                 println("vector<int> retEnumInt(retLen);");
2581                                 println("for (int i=0; i < retLen; i++) {");
2582                                 println("retEnumInt[i] = (int) retEnum[i];");
2583                                 println("}");
2584                         } else {        // Just one element
2585                                 println("vector<int> retEnumInt(1);");
2586                                 println("retEnumInt[0] = (int) retEnum;");
2587                         }
2588                 }
2589         }
2590
2591
2592         /**
2593          * HELPER: writeStdMethodHelperBodyCplusSkeleton() writes the standard method body helper in the skeleton class
2594          */
2595         private void writeStdMethodHelperBodyCplusSkeleton(InterfaceDecl intDecl, List<String> methParams,
2596                         List<String> methPrmTypes, String method, String methodId, Set<String> callbackClasses) {
2597
2598                 // Generate array of parameter types
2599                 boolean isCallbackMethod = false;
2600                 String callbackType = null;
2601                 print("string paramCls[] = { ");
2602                 for (int i = 0; i < methParams.size(); i++) {
2603                         String paramType = returnGenericCallbackType(methPrmTypes.get(i));
2604                         if (callbackClasses.contains(paramType)) {
2605                                 isCallbackMethod = true;
2606                                 callbackType = paramType;
2607                                 print("\"int\"");
2608                         } else {        // Generate normal classes if it's not a callback object
2609                                 String paramTypeC = checkAndGetCplusType(methPrmTypes.get(i));
2610                                 String prmType = checkAndGetCplusArrayType(paramTypeC, methParams.get(i));
2611                                 print("\"" + getEnumType(prmType) + "\"");
2612                         }
2613                         if (i != methParams.size() - 1) {
2614                                 print(", ");
2615                         }
2616                 }
2617                 println(" };");
2618                 println("int numParam = " + methParams.size() + ";");
2619                 if (isCallbackMethod)
2620                         writeCallbackCplusNumStubs(methParams, methPrmTypes, callbackType);
2621                 // Generate parameters
2622                 for (int i = 0; i < methParams.size(); i++) {
2623                         String paramType = returnGenericCallbackType(methPrmTypes.get(i));
2624                         if (!callbackClasses.contains(paramType)) {
2625                                 String methPrmType = checkAndGetCplusType(methPrmTypes.get(i));
2626                                 if (isEnumClass(getSimpleType(methPrmType))) {  // Check if this is enum type
2627                                         println("vector<int> paramEnumInt" + i + ";");
2628                                 } else {
2629                                         String methParamComplete = checkAndGetCplusArray(methPrmType, methParams.get(i));
2630                                         println(methParamComplete + ";");
2631                                 }
2632                         }
2633                 }
2634                 // Generate array of parameter objects
2635                 print("void* paramObj[] = { ");
2636                 for (int i = 0; i < methParams.size(); i++) {
2637                         String paramType = returnGenericCallbackType(methPrmTypes.get(i));
2638                         if (callbackClasses.contains(paramType))
2639                                 print("&numStubs" + i);
2640                         else if (isEnumClass(getSimpleType(paramType))) // Check if this is enum type
2641                                 print("&paramEnumInt" + i);
2642                         else
2643                                 print("&" + getSimpleIdentifier(methParams.get(i)));
2644                         if (i != methParams.size() - 1) {
2645                                 print(", ");
2646                         }
2647                 }
2648                 println(" };");
2649                 println("rmiObj->getMethodParams(paramCls, numParam, paramObj);");
2650                 if (isCallbackMethod)
2651                         writeCallbackCplusStubGeneration(methParams, methPrmTypes, callbackType);
2652                 checkAndWriteEnumTypeCplusSkeleton(methParams, methPrmTypes);
2653                 String retType = intDecl.getMethodType(method);
2654                 // Check if this is "void"
2655                 if (retType.equals("void")) {
2656                         print(methodId + "(");
2657                         for (int i = 0; i < methParams.size(); i++) {
2658                                 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
2659                                 if (callbackClasses.contains(paramType))
2660                                         print("stub" + i);
2661                                 else if (isEnumClass(getSimpleType(paramType))) // Check if this is enum type
2662                                         print("paramEnum" + i);
2663                                 else
2664                                         print(getSimpleIdentifier(methParams.get(i)));
2665                                 if (i != methParams.size() - 1) {
2666                                         print(", ");
2667                                 }
2668                         }
2669                         println(");");
2670                 } else { // We do have a return value
2671                         if (isEnumClass(getSimpleArrayType(getSimpleType(retType)))) // Enum type
2672                                 print(checkAndGetCplusType(retType) + " retEnum = ");
2673                         else
2674                                 print(checkAndGetCplusType(retType) + " retVal = ");
2675                         print(methodId + "(");
2676                         for (int i = 0; i < methParams.size(); i++) {
2677                                 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
2678                                 if (callbackClasses.contains(paramType))
2679                                         print("stub" + i);
2680                                 else if (isEnumClass(getSimpleType(paramType))) // Check if this is enum type
2681                                         print("paramEnum" + i);
2682                                 else
2683                                         print(getSimpleIdentifier(methParams.get(i)));
2684                                 if (i != methParams.size() - 1) {
2685                                         print(", ");
2686                                 }
2687                         }
2688                         println(");");
2689                         checkAndWriteEnumRetTypeCplusSkeleton(retType);
2690                         if (isEnumClass(getSimpleArrayType(getSimpleType(retType)))) // Enum type
2691                                 println("void* retObj = &retEnumInt;");
2692                         else
2693                                 println("void* retObj = &retVal;");
2694                         String retTypeC = checkAndGetCplusType(retType);
2695                         println("rmiObj->sendReturnObj(retObj, \"" + getEnumType(checkAndGetCplusArrayType(retTypeC)) + "\");");
2696                 }
2697         }
2698
2699
2700         /**
2701          * HELPER: writeMethodHelperCplusSkeleton() writes the method helper of the skeleton class
2702          */
2703         private void writeMethodHelperCplusSkeleton(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
2704
2705                 // Use this set to handle two same methodIds
2706                 Set<String> uniqueMethodIds = new HashSet<String>();
2707                 for (String method : methods) {
2708
2709                         List<String> methParams = intDecl.getMethodParams(method);
2710                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2711                         String methodId = intDecl.getMethodId(method);
2712                         print("void ___");
2713                         String helperMethod = methodId;
2714                         if (uniqueMethodIds.contains(methodId))
2715                                 helperMethod = helperMethod + intDecl.getMethodNumId(method);
2716                         else
2717                                 uniqueMethodIds.add(methodId);
2718                         // Check if this is "void"
2719                         String retType = intDecl.getMethodType(method);
2720                         println(helperMethod + "() {");
2721                         // Now, write the helper body of skeleton!
2722                         writeStdMethodHelperBodyCplusSkeleton(intDecl, methParams, methPrmTypes, method, methodId, callbackClasses);
2723                         println("}\n");
2724                 }
2725         }
2726
2727
2728         /**
2729          * HELPER: writeCplusMethodPermission() writes permission checks in skeleton
2730          */
2731         private void writeCplusMethodPermission(String intface) {
2732
2733                 // Get all the different stubs
2734                 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
2735                 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
2736                         String newIntface = intMeth.getKey();
2737                         int newObjectId = mapNewIntfaceObjId.get(newIntface);
2738                         println("if (_objectId == object" + newObjectId + "Id) {");
2739                         println("if (set" + newObjectId + "Allowed.find(methodId) == set" + newObjectId + "Allowed.end()) {");
2740                         println("cerr << \"Object with object Id: \" << _objectId << \"  is not allowed to access method: \" << methodId << endl;");
2741                         println("exit(-1);");
2742                         println("}");
2743                         println("else {");
2744                         println("cerr << \"Object Id: \" << _objectId << \" not recognized!\" << endl;");
2745                         println("exit(-1);");
2746                         println("}");
2747                         println("}");
2748                 }
2749         }
2750
2751
2752         /**
2753          * HELPER: writeCplusWaitRequestInvokeMethod() writes the main loop of the skeleton class
2754          */
2755         private void writeCplusWaitRequestInvokeMethod(Collection<String> methods, InterfaceDecl intDecl, boolean callbackExist, String intface) {
2756
2757                 // Use this set to handle two same methodIds
2758                 Set<String> uniqueMethodIds = new HashSet<String>();
2759                 println("void ___waitRequestInvokeMethod() {");
2760                 // Write variables here if we have callbacks or enums or structs
2761                 println("while (true) {");
2762                 println("rmiObj->getMethodBytes();");
2763                 println("int _objectId = rmiObj->getObjectId();");
2764                 println("int methodId = rmiObj->getMethodId();");
2765                 // Generate permission check
2766                 writeCplusMethodPermission(intface);
2767                 println("switch (methodId) {");
2768                 // Print methods and method Ids
2769                 for (String method : methods) {
2770                         String methodId = intDecl.getMethodId(method);
2771                         int methodNumId = intDecl.getMethodNumId(method);
2772                         print("case " + methodNumId + ": ___");
2773                         String helperMethod = methodId;
2774                         if (uniqueMethodIds.contains(methodId))
2775                                 helperMethod = helperMethod + methodNumId;
2776                         else
2777                                 uniqueMethodIds.add(methodId);
2778                         println(helperMethod + "(); break;");
2779                 }
2780                 String method = "___initCallBack()";
2781                 // Print case -9999 (callback handler) if callback exists
2782                 if (callbackExist) {
2783                         int methodId = intDecl.getHelperMethodNumId(method);
2784                         println("case " + methodId + ": ___regCB(); break;");
2785                 }
2786                 println("default: ");
2787                 println("cerr << \"Method Id \" << methodId << \" not recognized!\" << endl;");
2788                 println("throw exception();");
2789                 println("}");
2790                 println("}");
2791                 println("}\n");
2792         }
2793
2794
2795         /**
2796          * generateCplusSkeletonClass() generate skeletons based on the methods list in C++
2797          */
2798         public void generateCplusSkeletonClass() throws IOException {
2799
2800                 // Create a new directory
2801                 String path = createDirectories(dir, subdir);
2802                 for (String intface : mapIntfacePTH.keySet()) {
2803                         // Open a new file to write into
2804                         String newSkelClass = intface + "_Skeleton";
2805                         FileWriter fw = new FileWriter(path + "/" + newSkelClass + ".hpp");
2806                         pw = new PrintWriter(new BufferedWriter(fw));
2807                         // Write file headers
2808                         println("#ifndef _" + newSkelClass.toUpperCase() + "_HPP__");
2809                         println("#define _" + newSkelClass.toUpperCase() + "_HPP__");
2810                         println("#include <iostream>");
2811                         println("#include \"" + intface + ".hpp\"\n");
2812                         // Pass in set of methods and get import classes
2813                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2814                         InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
2815                         List<String> methods = intDecl.getMethods();
2816                         Set<String> includeClasses = getIncludeClasses(methods, intDecl, intface, true);
2817                         List<String> stdIncludeClasses = getStandardCplusIncludeClasses();
2818                         List<String> allIncludeClasses = getAllLibClasses(stdIncludeClasses, includeClasses);
2819                         printIncludeStatements(allIncludeClasses); println("");
2820                         println("using namespace std;\n");
2821                         // Find out if there are callback objects
2822                         Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
2823                         boolean callbackExist = !callbackClasses.isEmpty();
2824                         // Write class header
2825                         println("class " + newSkelClass + " : public " + intface); println("{");
2826                         println("private:\n");
2827                         // Write properties
2828                         writePropertiesCplusSkeleton(intface, callbackExist, callbackClasses);
2829                         println("public:\n");
2830                         // Write constructor
2831                         writeConstructorCplusSkeleton(newSkelClass, intface, callbackExist);
2832                         // Write deconstructor
2833                         writeDeconstructorCplusSkeleton(newSkelClass, callbackExist, callbackClasses);
2834                         // Write methods
2835                         writeMethodCplusSkeleton(methods, intDecl, callbackClasses, false);
2836                         // Write method helper
2837                         writeMethodHelperCplusSkeleton(methods, intDecl, callbackClasses);
2838                         // Write waitRequestInvokeMethod() - main loop
2839                         writeCplusWaitRequestInvokeMethod(methods, intDecl, callbackExist, intface);
2840                         println("};");
2841                         writePermissionInitializationCplus(intface, newSkelClass, intDecl);
2842                         println("#endif");
2843                         pw.close();
2844                         System.out.println("IoTCompiler: Generated skeleton class " + newSkelClass + ".hpp...");
2845                 }
2846         }
2847
2848
2849         /**
2850          * HELPER: writePropertiesCplusCallbackSkeleton() writes the properties of the callback skeleton class
2851          */
2852         private void writePropertiesCplusCallbackSkeleton(String intface, boolean callbackExist, Set<String> callbackClasses) {
2853
2854                 println(intface + " *mainObj;");
2855                 // Keep track of object Ids of all stubs registered to this interface
2856                 println("static int objectId;");
2857                 // Callback
2858                 if (callbackExist) {
2859                         Iterator it = callbackClasses.iterator();
2860                         String callbackType = (String) it.next();
2861                         String exchangeType = checkAndGetParamClass(callbackType);
2862                         println("// Callback properties");
2863                         println("IoTRMICall* rmiCall;");
2864                         println("vector<" + exchangeType + "*> vecCallbackObj;");
2865                         println("static int objIdCnt;");
2866                 }
2867                 println("\n");
2868         }
2869
2870
2871         /**
2872          * HELPER: writeConstructorCplusCallbackSkeleton() writes the constructor of the skeleton class
2873          */
2874         private void writeConstructorCplusCallbackSkeleton(String newSkelClass, String intface, boolean callbackExist) {
2875
2876                 println(newSkelClass + "(" + intface + " *_mainObj, int _objectId) {");
2877                 println("mainObj = _mainObj;");
2878                 println("objectId = _objectId;");
2879                 // Callback
2880                 if (callbackExist) {
2881                         println("objIdCnt = 0;");
2882                 }
2883                 println("}\n");
2884         }
2885
2886
2887         /**
2888          * HELPER: writeDeconstructorCplusStub() writes the deconstructor of the stub class
2889          */
2890         private void writeDeconstructorCplusCallbackSkeleton(String newStubClass, boolean callbackExist, 
2891                         Set<String> callbackClasses) {
2892
2893                 println("~" + newStubClass + "() {");
2894                 if (callbackExist) {
2895                 // We assume that each class only has one callback interface for now
2896                         println("if (rmiCall != NULL) {");
2897                         println("delete rmiCall;");
2898                         println("rmiCall = NULL;");
2899                         println("}");
2900                         Iterator it = callbackClasses.iterator();
2901                         String callbackType = (String) it.next();
2902                         String exchangeType = checkAndGetParamClass(callbackType);
2903                         println("for(" + exchangeType + "* cb : vecCallbackObj) {");
2904                         println("delete cb;");
2905                         println("cb = NULL;");
2906                         println("}");
2907                 }
2908                 println("}");
2909                 println("");
2910         }
2911
2912
2913         /**
2914          * HELPER: writeMethodHelperCplusCallbackSkeleton() writes the method helper of the callback skeleton class
2915          */
2916         private void writeMethodHelperCplusCallbackSkeleton(Collection<String> methods, InterfaceDecl intDecl, 
2917                         Set<String> callbackClasses) {
2918
2919                 // Use this set to handle two same methodIds
2920                 Set<String> uniqueMethodIds = new HashSet<String>();
2921                 for (String method : methods) {
2922
2923                         List<String> methParams = intDecl.getMethodParams(method);
2924                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2925                         String methodId = intDecl.getMethodId(method);
2926                         print("void ___");
2927                         String helperMethod = methodId;
2928                         if (uniqueMethodIds.contains(methodId))
2929                                 helperMethod = helperMethod + intDecl.getMethodNumId(method);
2930                         else
2931                                 uniqueMethodIds.add(methodId);
2932                         // Check if this is "void"
2933                         String retType = intDecl.getMethodType(method);
2934                         println(helperMethod + "(IoTRMIObject* rmiObj) {");
2935                         // Now, write the helper body of skeleton!
2936                         writeStdMethodHelperBodyCplusSkeleton(intDecl, methParams, methPrmTypes, method, methodId, callbackClasses);
2937                         println("}\n");
2938                 }
2939         }
2940
2941
2942         /**
2943          * HELPER: writeCplusCallbackWaitRequestInvokeMethod() writes the main loop of the skeleton class
2944          */
2945         private void writeCplusCallbackWaitRequestInvokeMethod(Collection<String> methods, InterfaceDecl intDecl, 
2946                         boolean callbackExist) {
2947
2948                 // Use this set to handle two same methodIds
2949                 Set<String> uniqueMethodIds = new HashSet<String>();
2950                 println("void invokeMethod(IoTRMIObject* rmiObj) {");
2951                 // Write variables here if we have callbacks or enums or structs
2952                 println("int methodId = rmiObj->getMethodId();");
2953                 // TODO: code the permission check here!
2954                 println("switch (methodId) {");
2955                 // Print methods and method Ids
2956                 for (String method : methods) {
2957                         String methodId = intDecl.getMethodId(method);
2958                         int methodNumId = intDecl.getMethodNumId(method);
2959                         print("case " + methodNumId + ": ___");
2960                         String helperMethod = methodId;
2961                         if (uniqueMethodIds.contains(methodId))
2962                                 helperMethod = helperMethod + methodNumId;
2963                         else
2964                                 uniqueMethodIds.add(methodId);
2965                         println(helperMethod + "(rmiObj); break;");
2966                 }
2967                 String method = "___initCallBack()";
2968                 // Print case -9999 (callback handler) if callback exists
2969                 if (callbackExist) {
2970                         int methodId = intDecl.getHelperMethodNumId(method);
2971                         println("case " + methodId + ": ___regCB(rmiObj); break;");
2972                 }
2973                 println("default: ");
2974                 println("cerr << \"Method Id \" << methodId << \" not recognized!\" << endl;");
2975                 println("throw exception();");
2976                 println("}");
2977                 println("}\n");
2978         }
2979
2980
2981
2982         /**
2983          * generateCplusCallbackSkeletonClass() generate callback skeletons based on the methods list in C++
2984          */
2985         public void generateCplusCallbackSkeletonClass() throws IOException {
2986
2987                 // Create a new directory
2988                 String path = createDirectories(dir, subdir);
2989                 for (String intface : mapIntfacePTH.keySet()) {
2990                         // Open a new file to write into
2991                         String newSkelClass = intface + "_CallbackSkeleton";
2992                         FileWriter fw = new FileWriter(path + "/" + newSkelClass + ".hpp");
2993                         pw = new PrintWriter(new BufferedWriter(fw));
2994                         // Write file headers
2995                         println("#ifndef _" + newSkelClass.toUpperCase() + "_HPP__");
2996                         println("#define _" + newSkelClass.toUpperCase() + "_HPP__");
2997                         println("#include <iostream>");
2998                         println("#include \"" + intface + ".hpp\"\n");
2999                         // Pass in set of methods and get import classes
3000                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
3001                         InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
3002                         List<String> methods = intDecl.getMethods();
3003                         Set<String> includeClasses = getIncludeClasses(methods, intDecl, intface, true);
3004                         List<String> stdIncludeClasses = getStandardCplusIncludeClasses();
3005                         List<String> allIncludeClasses = getAllLibClasses(stdIncludeClasses, includeClasses);
3006                         printIncludeStatements(allIncludeClasses); println("");                 
3007                         // Find out if there are callback objects
3008                         Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
3009                         boolean callbackExist = !callbackClasses.isEmpty();
3010                         println("using namespace std;\n");
3011                         // Write class header
3012                         println("class " + newSkelClass + " : public " + intface); println("{");
3013                         println("private:\n");
3014                         // Write properties
3015                         writePropertiesCplusCallbackSkeleton(intface, callbackExist, callbackClasses);
3016                         println("public:\n");
3017                         // Write constructor
3018                         writeConstructorCplusCallbackSkeleton(newSkelClass, intface, callbackExist);
3019                         // Write deconstructor
3020                         writeDeconstructorCplusCallbackSkeleton(newSkelClass, callbackExist, callbackClasses);
3021                         // Write methods
3022                         writeMethodCplusSkeleton(methods, intDecl, callbackClasses, true);
3023                         // Write method helper
3024                         writeMethodHelperCplusCallbackSkeleton(methods, intDecl, callbackClasses);
3025                         // Write waitRequestInvokeMethod() - main loop
3026                         writeCplusCallbackWaitRequestInvokeMethod(methods, intDecl, callbackExist);
3027                         println("};");
3028                         println("#endif");
3029                         pw.close();
3030                         System.out.println("IoTCompiler: Generated callback skeleton class " + newSkelClass + ".hpp...");
3031                 }
3032         }
3033
3034
3035         /**
3036          * generateInitializer() generate initializer based on type
3037          */
3038         public String generateCplusInitializer(String type) {
3039
3040                 // Generate dummy returns for now
3041                 if (type.equals("short")||
3042                         type.equals("int")      ||
3043                         type.equals("long") ||
3044                         type.equals("float")||
3045                         type.equals("double")) {
3046
3047                         return "0";
3048                 } else if ( type.equals("String") ||
3049                                         type.equals("string")) {
3050   
3051                         return "\"\"";
3052                 } else if ( type.equals("char") ||
3053                                         type.equals("byte")) {
3054
3055                         return "\' \'";
3056                 } else if ( type.equals("boolean")) {
3057
3058                         return "false";
3059                 } else {
3060                         return "NULL";
3061                 }
3062         }
3063
3064
3065         /**
3066          * generateReturnStmt() generate return statement based on methType
3067          */
3068         public String generateReturnStmt(String methType) {
3069
3070                 // Generate dummy returns for now
3071                 if (methType.equals("short")||
3072                         methType.equals("int")  ||
3073                         methType.equals("long") ||
3074                         methType.equals("float")||
3075                         methType.equals("double")) {
3076
3077                         return "1";
3078                 } else if ( methType.equals("String")) {
3079   
3080                         return "\"a\"";
3081                 } else if ( methType.equals("char") ||
3082                                         methType.equals("byte")) {
3083
3084                         return "\'a\'";
3085                 } else if ( methType.equals("boolean")) {
3086
3087                         return "true";
3088                 } else {
3089                         return "null";
3090                 }
3091         }
3092
3093
3094         /**
3095          * setDirectory() sets a new directory for stub files
3096          */
3097         public void setDirectory(String _subdir) {
3098
3099                 subdir = _subdir;
3100         }
3101
3102
3103         /**
3104          * printUsage() prints the usage of this compiler
3105          */
3106         public static void printUsage() {
3107
3108                 System.out.println();
3109                 System.out.println("Sentinel interface and stub compiler version 1.0");
3110                 System.out.println("Copyright (c) 2015-2016 University of California, Irvine - Programming Language Group.");
3111                 System.out.println("All rights reserved.");
3112                 System.out.println("Usage:");
3113                 System.out.println("\tjava IoTCompiler -help / --help / -h\n");
3114                 System.out.println("\t\tDisplay this help texts\n\n");
3115                 System.out.println("\tjava IoTCompiler [<main-policy-file> <req-policy-file>]");
3116                 System.out.println("\tjava IoTCompiler [<main-policy-file> <req-policy-file>] [options]\n");
3117                 System.out.println("\t\tTake one or more pairs of main-req policy files, and generate Java and/or C++ files\n");
3118                 System.out.println("Options:");
3119                 System.out.println("\t-java\t<directory>\tGenerate Java stub files");
3120                 System.out.println("\t-cplus\t<directory>\tGenerate C++ stub files");
3121                 System.out.println();
3122         }
3123
3124
3125         /**
3126          * parseFile() prepares Lexer and Parser objects, then parses the file
3127          */
3128         public static ParseNode parseFile(String file) {
3129
3130                 ParseNode pn = null;
3131                 try {
3132                         ComplexSymbolFactory csf = new ComplexSymbolFactory();
3133                         ScannerBuffer lexer = 
3134                                 new ScannerBuffer(new Lexer(new BufferedReader(new FileReader(file)),csf));
3135                         Parser parse = new Parser(lexer,csf);
3136                         pn = (ParseNode) parse.parse().value;
3137                 } catch (Exception e) {
3138                         e.printStackTrace();
3139                         throw new Error("IoTCompiler: ERROR parsing policy file or wrong command line option: " + file);
3140                 }
3141
3142                 return pn;
3143         }
3144
3145
3146         /**================
3147          * Helper functions
3148          **================
3149          */
3150         boolean newline=true;
3151         int tablevel=0;
3152
3153         private void print(String str) {
3154                 if (newline) {
3155                         int tab=tablevel;
3156                         if (str.equals("}"))
3157                                 tab--;
3158                         for(int i=0; i<tab; i++)
3159                                 pw.print("\t");
3160                 }
3161                 pw.print(str);
3162                 updatetabbing(str);
3163                 newline=false;
3164         }
3165
3166
3167         /**
3168          * This function converts Java to C++ type for compilation
3169          */
3170         private String convertType(String jType) {
3171
3172                 return mapPrimitives.get(jType);
3173         }
3174
3175
3176         private void println(String str) {
3177                 if (newline) {
3178                         int tab = tablevel;
3179                         if (str.contains("}") && !str.contains("{"))
3180                                 tab--;
3181                         for(int i=0; i<tab; i++)
3182                                 pw.print("\t");
3183                 }
3184                 pw.println(str);
3185                 updatetabbing(str);
3186                 newline = true;
3187         }
3188
3189
3190         private void updatetabbing(String str) {
3191
3192                 tablevel+=count(str,'{')-count(str,'}');
3193         }
3194
3195
3196         private int count(String str, char key) {
3197                 char[] array = str.toCharArray();
3198                 int count = 0;
3199                 for(int i=0; i<array.length; i++) {
3200                         if (array[i] == key)
3201                                 count++;
3202                 }
3203                 return count;
3204         }
3205
3206
3207         private void createDirectory(String dirName) {
3208
3209                 File file = new File(dirName);
3210                 if (!file.exists()) {
3211                         if (file.mkdir()) {
3212                                 System.out.println("IoTCompiler: Directory " + dirName + " has been created!");
3213                         } else {
3214                                 System.out.println("IoTCompiler: Failed to create directory " + dirName + "!");
3215                         }
3216                 } else {
3217                         System.out.println("IoTCompiler: Directory " + dirName + " exists...");
3218                 }
3219         }
3220
3221
3222         // Create a directory and possibly a sub directory
3223         private String createDirectories(String dir, String subdir) {
3224
3225                 String path = dir;
3226                 createDirectory(path);
3227                 if (subdir != null) {
3228                         path = path + "/" + subdir;
3229                         createDirectory(path);
3230                 }
3231                 return path;
3232         }
3233
3234
3235         // Inserting array members into a Map object
3236         // that maps arrKey to arrVal objects
3237         private void arraysToMap(Map map, Object[] arrKey, Object[] arrVal) {
3238
3239                 for(int i = 0; i < arrKey.length; i++) {
3240
3241                         map.put(arrKey[i], arrVal[i]);
3242                 }
3243         }
3244
3245
3246         // Return parameter category, i.e. PRIMITIVES, NONPRIMITIVES, or USERDEFINED
3247         private ParamCategory getParamCategory(String paramType) {
3248
3249                 if (mapPrimitives.containsKey(paramType)) {
3250                         return ParamCategory.PRIMITIVES;
3251                 // We can either use mapNonPrimitivesJava or mapNonPrimitivesCplus here
3252                 } else if (mapNonPrimitivesJava.containsKey(getSimpleType(paramType))) {
3253                         return ParamCategory.NONPRIMITIVES;
3254                 } else if (isEnumClass(paramType)) {
3255                         return ParamCategory.ENUM;
3256                 } else if (isStructClass(paramType)) {
3257                         return ParamCategory.STRUCT;
3258                 } else
3259                         return ParamCategory.USERDEFINED;
3260         }
3261
3262
3263         // Return full class name for non-primitives to generate Java import statements
3264         // e.g. java.util.Set for Set, java.util.Map for Map
3265         private String getNonPrimitiveJavaClass(String paramNonPrimitives) {
3266
3267                 return mapNonPrimitivesJava.get(paramNonPrimitives);
3268         }
3269
3270
3271         // Return full class name for non-primitives to generate Cplus include statements
3272         // e.g. #include <set> for Set, #include <map> for Map
3273         private String getNonPrimitiveCplusClass(String paramNonPrimitives) {
3274
3275                 return mapNonPrimitivesCplus.get(paramNonPrimitives);
3276         }
3277
3278
3279         // Get simple types, e.g. HashSet for HashSet<...>
3280         // Basically strip off the "<...>"
3281         private String getSimpleType(String paramType) {
3282
3283                 // Check if this is generics
3284                 if(paramType.contains("<")) {
3285                         String[] type = paramType.split("<");
3286                         return type[0];
3287                 } else
3288                         return paramType;
3289         }
3290
3291
3292         // Generate a set of standard classes for import statements
3293         private List<String> getStandardJavaImportClasses() {
3294
3295                 List<String> importClasses = new ArrayList<String>();
3296                 // Add the standard list first
3297                 importClasses.add("java.io.IOException");
3298                 importClasses.add("java.util.List");
3299                 importClasses.add("java.util.ArrayList");
3300                 importClasses.add("java.util.Arrays");
3301                 importClasses.add("iotrmi.Java.IoTRMICall");
3302                 importClasses.add("iotrmi.Java.IoTRMIObject");
3303
3304                 return importClasses;
3305         }
3306
3307
3308         // Generate a set of standard classes for import statements
3309         private List<String> getStandardCplusIncludeClasses() {
3310
3311                 List<String> importClasses = new ArrayList<String>();
3312                 // Add the standard list first
3313                 importClasses.add("<vector>");
3314                 importClasses.add("<set>");
3315                 importClasses.add("\"IoTRMICall.hpp\"");
3316                 importClasses.add("\"IoTRMIObject.hpp\"");
3317
3318                 return importClasses;
3319         }
3320
3321
3322         // Generate a set of standard classes for import statements
3323         private List<String> getAllLibClasses(Collection<String> stdLibClasses, Collection<String> libClasses) {
3324
3325                 List<String> allLibClasses = new ArrayList<String>(stdLibClasses);
3326                 // Iterate over the list of import classes
3327                 for (String str : libClasses) {
3328                         if (!allLibClasses.contains(str)) {
3329                                 allLibClasses.add(str);
3330                         }
3331                 }
3332
3333                 return allLibClasses;
3334         }
3335
3336
3337
3338         // Generate a set of classes for import statements
3339         private Set<String> getImportClasses(Collection<String> methods, InterfaceDecl intDecl) {
3340
3341                 Set<String> importClasses = new HashSet<String>();
3342                 for (String method : methods) {
3343                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
3344                         for (String paramType : methPrmTypes) {
3345
3346                                 String simpleType = getSimpleType(paramType);
3347                                 if (getParamCategory(simpleType) == ParamCategory.NONPRIMITIVES) {
3348                                         importClasses.add(getNonPrimitiveJavaClass(simpleType));
3349                                 }
3350                         }
3351                 }
3352                 return importClasses;
3353         }
3354
3355
3356         // Handle and return the correct enum declaration
3357         // In Java, if we declare enum in Camera interface, then it becomes "Camera.<enum>"
3358         private String getEnumParamDecl(String type, InterfaceDecl intDecl) {
3359
3360                 // Strips off array "[]" for return type
3361                 String pureType = getSimpleArrayType(type);
3362                 // Take the inner type of generic
3363                 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
3364                         pureType = getTypeOfGeneric(type)[0];
3365                 if (isEnumClass(pureType)) {
3366                         String enumType = intDecl.getInterface() + "." + type;
3367                         return enumType;
3368                 } else
3369                         return type;
3370         }
3371
3372
3373         // Handle and return the correct type
3374         private String getEnumParam(String type, String param, int i) {
3375
3376                 // Strips off array "[]" for return type
3377                 String pureType = getSimpleArrayType(type);
3378                 // Take the inner type of generic
3379                 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
3380                         pureType = getTypeOfGeneric(type)[0];
3381                 if (isEnumClass(pureType)) {
3382                         String enumParam = "paramEnum" + i;
3383                         return enumParam;
3384                 } else
3385                         return param;
3386         }
3387
3388
3389         // Handle and return the correct enum declaration translate into int[]
3390         private String getEnumType(String type) {
3391
3392                 // Strips off array "[]" for return type
3393                 String pureType = getSimpleArrayType(type);
3394                 // Take the inner type of generic
3395                 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
3396                         pureType = getTypeOfGeneric(type)[0];
3397                 if (isEnumClass(pureType)) {
3398                         String enumType = "int[]";
3399                         return enumType;
3400                 } else
3401                         return type;
3402         }
3403
3404
3405         // Handle and return the correct struct declaration
3406         private String getStructType(String type) {
3407
3408                 if (isStructClass(type)) {
3409                 // TODO: complete this method
3410                         return type;
3411                 } else
3412                         return type;
3413         }
3414
3415
3416         // Check if this an enum declaration
3417         private boolean isEnumClass(String type) {
3418
3419                 // Just iterate over the set of interfaces
3420                 for (String intface : mapIntfacePTH.keySet()) {
3421                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
3422                         EnumDecl enumDecl = (EnumDecl) decHandler.getEnumDecl(intface);
3423                         Set<String> setEnumDecl = enumDecl.getEnumDeclarations();
3424                         if (setEnumDecl.contains(type))
3425                                 return true;
3426                 }
3427                 return false;
3428         }
3429
3430
3431         // Check if this an struct declaration
3432         private boolean isStructClass(String type) {
3433
3434                 // Just iterate over the set of interfaces
3435                 for (String intface : mapIntfacePTH.keySet()) {
3436                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
3437                         StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
3438                         List<String> listStructDecl = structDecl.getStructTypes();
3439                         if (listStructDecl.contains(type))
3440                                 return true;
3441                 }
3442                 return false;
3443         }
3444
3445
3446         // Generate a set of classes for include statements
3447         private Set<String> getIncludeClasses(Collection<String> methods, InterfaceDecl intDecl, String intface, boolean needExchange) {
3448
3449                 Set<String> includeClasses = new HashSet<String>();
3450                 for (String method : methods) {
3451
3452                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
3453                         List<String> methParams = intDecl.getMethodParams(method);
3454                         for (int i = 0; i < methPrmTypes.size(); i++) {
3455
3456                                 String simpleType = getSimpleType(methPrmTypes.get(i));
3457                                 String param = methParams.get(i);
3458                                 if (getParamCategory(simpleType) == ParamCategory.NONPRIMITIVES) {
3459                                         includeClasses.add("<" + getNonPrimitiveCplusClass(simpleType) + ">");
3460                                 } else if (getParamCategory(simpleType) == ParamCategory.USERDEFINED) {
3461                                         // For original interface, we need it exchanged... not for stub interfaces
3462                                         if (needExchange) {
3463                                                 includeClasses.add("\"" + exchangeParamType(simpleType) + ".hpp\"");
3464                                                 includeClasses.add("\"" + exchangeParamType(simpleType) + "_CallbackStub.hpp\"");
3465                                         } else {
3466                                                 includeClasses.add("\"" + simpleType + ".hpp\"");
3467                                                 includeClasses.add("\"" + simpleType + "_CallbackSkeleton.hpp\"");
3468                                         }
3469                                 } else if (getParamCategory(getSimpleArrayType(simpleType)) == ParamCategory.ENUM) {
3470                                         includeClasses.add("\"" + simpleType + ".hpp\"");
3471                                 } else if (param.contains("[]")) {
3472                                 // Check if this is array for C++; translate into vector
3473                                         includeClasses.add("<vector>");
3474                                 }
3475                         }
3476                 }
3477                 return includeClasses;
3478         }
3479
3480
3481         // Generate a set of callback classes
3482         private Set<String> getCallbackClasses(Collection<String> methods, InterfaceDecl intDecl) {
3483
3484                 Set<String> callbackClasses = new HashSet<String>();
3485                 for (String method : methods) {
3486
3487                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
3488                         List<String> methParams = intDecl.getMethodParams(method);
3489                         for (int i = 0; i < methPrmTypes.size(); i++) {
3490
3491                                 String type = methPrmTypes.get(i);
3492                                 if (getParamCategory(type) == ParamCategory.USERDEFINED) {
3493                                         callbackClasses.add(type);
3494                                 } else if (getParamCategory(type) == ParamCategory.NONPRIMITIVES) {
3495                                 // Can be a List<...> of callback objects ...
3496                                         String genericType = getTypeOfGeneric(type)[0];
3497                                         if (getParamCategory(type) == ParamCategory.USERDEFINED) {
3498                                                 callbackClasses.add(type);
3499                                         }
3500                                 }
3501                         }
3502                 }
3503                 return callbackClasses;
3504         }
3505
3506
3507         private void printImportStatements(Collection<String> importClasses) {
3508
3509                 for(String cls : importClasses) {
3510                         println("import " + cls + ";");
3511                 }
3512         }
3513
3514
3515         private void printIncludeStatements(Collection<String> includeClasses) {
3516
3517                 for(String cls : includeClasses) {
3518                         println("#include " + cls);
3519                 }
3520         }
3521
3522
3523         // Get the C++ version of a non-primitive type
3524         // e.g. set for Set and map for Map
3525         // Input nonPrimitiveType has to be generics in format
3526         private String[] getTypeOfGeneric(String nonPrimitiveType) {
3527
3528                 // Handle <, >, and , for 2-type generic/template
3529                 String[] substr = nonPrimitiveType.split("<")[1].split(">")[0].split(",");
3530                 return substr;
3531         }
3532
3533
3534         // This helper function strips off array declaration, e.g. int[] becomes int
3535         private String getSimpleArrayType(String type) {
3536
3537                 // Handle [ for array declaration
3538                 String substr = type;
3539                 if (type.contains("[]")) {
3540                         substr = type.split("\\[\\]")[0];
3541                 }
3542                 return substr;
3543         }
3544
3545
3546         // This helper function strips off array declaration, e.g. D[] becomes D
3547         private String getSimpleIdentifier(String ident) {
3548
3549                 // Handle [ for array declaration
3550                 String substr = ident;
3551                 if (ident.contains("[]")) {
3552                         substr = ident.split("\\[\\]")[0];
3553                 }
3554                 return substr;
3555         }
3556
3557
3558         private String checkAndGetCplusType(String paramType) {
3559
3560                 if (getParamCategory(paramType) == ParamCategory.PRIMITIVES) {
3561                         return convertType(paramType);
3562                 } else if (getParamCategory(paramType) == ParamCategory.NONPRIMITIVES) {
3563
3564                         // Check for generic/template format
3565                         if (paramType.contains("<") && paramType.contains(">")) {
3566
3567                                 String genericClass = getSimpleType(paramType);
3568                                 String[] genericType = getTypeOfGeneric(paramType);
3569                                 String cplusTemplate = null;
3570                                 if (genericType.length == 1) // Generic/template with one type
3571                                         cplusTemplate = getNonPrimitiveCplusClass(genericClass) + 
3572                                                 "<" + convertType(genericType[0]) + ">";
3573                                 else // Generic/template with two types
3574                                         cplusTemplate = getNonPrimitiveCplusClass(genericClass) + 
3575                                                 "<" + convertType(genericType[0]) + "," + convertType(genericType[1]) + ">";
3576                                 return cplusTemplate;
3577                         } else
3578                                 return getNonPrimitiveCplusClass(paramType);
3579                 } else if(getParamCategory(paramType) == ParamCategory.USERDEFINED) {
3580                         return paramType + "*";
3581                 } else
3582                         // Just return it as is if it's not non-primitives
3583                         return paramType;
3584                         //return checkAndGetParamClass(paramType, true);
3585         }
3586
3587
3588         // Detect array declaration, e.g. int A[],
3589         //              then generate "int A[]" in C++ as "vector<int> A"
3590         private String checkAndGetCplusArray(String paramType, String param) {
3591
3592                 String paramComplete = null;
3593                 // Check for array declaration
3594                 if (param.contains("[]")) {
3595                         paramComplete = "vector<" + paramType + "> " + param.replace("[]","");
3596                 } else
3597                         // Just return it as is if it's not an array
3598                         paramComplete = paramType + " " + param;
3599
3600                 return paramComplete;
3601         }
3602         
3603
3604         // Detect array declaration, e.g. int A[],
3605         //              then generate "int A[]" in C++ as "vector<int> A"
3606         // This method just returns the type
3607         private String checkAndGetCplusArrayType(String paramType) {
3608
3609                 String paramTypeRet = null;
3610                 // Check for array declaration
3611                 if (paramType.contains("[]")) {
3612                         String type = paramType.split("\\[\\]")[0];
3613                         paramTypeRet = checkAndGetCplusType(type) + "[]";
3614                 } else if (paramType.contains("vector")) {
3615                         // Just return it as is if it's not an array
3616                         String type = paramType.split("<")[1].split(">")[0];
3617                         paramTypeRet = checkAndGetCplusType(type) + "[]";
3618                 } else
3619                         paramTypeRet = paramType;
3620
3621                 return paramTypeRet;
3622         }
3623         
3624         
3625         // Detect array declaration, e.g. int A[],
3626         //              then generate "int A[]" in C++ as "vector<int> A"
3627         // This method just returns the type
3628         private String checkAndGetCplusArrayType(String paramType, String param) {
3629
3630                 String paramTypeRet = null;
3631                 // Check for array declaration
3632                 if (param.contains("[]")) {
3633                         paramTypeRet = checkAndGetCplusType(paramType) + "[]";
3634                 } else if (paramType.contains("vector")) {
3635                         // Just return it as is if it's not an array
3636                         String type = paramType.split("<")[1].split(">")[0];
3637                         paramTypeRet = checkAndGetCplusType(type) + "[]";
3638                 } else
3639                         paramTypeRet = paramType;
3640
3641                 return paramTypeRet;
3642         }
3643
3644
3645         // Detect array declaration, e.g. int A[],
3646         //              then generate type "int[]"
3647         private String checkAndGetArray(String paramType, String param) {
3648
3649                 String paramTypeRet = null;
3650                 // Check for array declaration
3651                 if (param.contains("[]")) {
3652                         paramTypeRet = paramType + "[]";
3653                 } else
3654                         // Just return it as is if it's not an array
3655                         paramTypeRet = paramType;
3656
3657                 return paramTypeRet;
3658         }
3659
3660
3661         // Is array or list?
3662         private boolean isArrayOrList(String paramType, String param) {
3663
3664                 // Check for array declaration
3665                 if (isArray(param))
3666                         return true;
3667                 else if (isList(paramType))
3668                         return true;
3669                 else
3670                         return false;
3671         }
3672
3673
3674         // Is array? For return type we put the return type as input parameter
3675         private boolean isArray(String param) {
3676
3677                 // Check for array declaration
3678                 if (param.contains("[]"))
3679                         return true;
3680                 else
3681                         return false;
3682         }
3683
3684
3685         // Is list?
3686         private boolean isList(String paramType) {
3687
3688                 // Check for array declaration
3689                 if (paramType.contains("List"))
3690                         return true;
3691                 else
3692                         return false;
3693         }
3694
3695
3696         // Get the right type for a callback object
3697         private String checkAndGetParamClass(String paramType) {
3698
3699                 // Check if this is generics
3700                 if(getParamCategory(paramType) == ParamCategory.USERDEFINED) {
3701                         return exchangeParamType(paramType);
3702                 } else
3703                         return paramType;
3704         }
3705
3706
3707         // Returns the other interface for type-checking purposes for USERDEFINED
3708         //              classes based on the information provided in multiple policy files
3709         // e.g. return CameraWithXXX instead of Camera
3710         private String exchangeParamType(String intface) {
3711
3712                 // Param type that's passed is the interface name we need to look for
3713                 //              in the map of interfaces, based on available policy files.
3714                 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
3715                 if (decHandler != null) {
3716                 // We've found the required interface policy files
3717                         RequiresDecl reqDecl = (RequiresDecl) decHandler.getRequiresDecl(intface);
3718                         Set<String> setExchInt = reqDecl.getInterfaces();
3719                         if (setExchInt.size() == 1) {
3720                                 Iterator iter = setExchInt.iterator();
3721                                 return (String) iter.next();
3722                         } else {
3723                                 throw new Error("IoTCompiler: Ambiguous stub interfaces: " + setExchInt.toString() + 
3724                                         ". Only one new interface can be declared if the object " + intface +
3725                                         " needs to be passed in as an input parameter!");
3726                         }
3727                 } else {
3728                 // NULL value - this means policy files missing
3729                         throw new Error("IoTCompiler: Parameter type lookup failed for " + intface +
3730                                 "... Please provide the necessary policy files for user-defined types." +
3731                                 " If this is an array please type the brackets after the variable name," +
3732                                 " e.g. \"String str[]\", not \"String[] str\"." +
3733                                 " If this is a Collections (Java) / STL (C++) type, this compiler only" +
3734                                 " supports List/ArrayList (Java) or list (C++).");
3735                 }
3736         }
3737
3738
3739         public static void main(String[] args) throws Exception {
3740
3741                 // If there is no argument or just "--help" or "-h", then invoke printUsage()
3742                 if ((args[0].equals("-help") ||
3743                          args[0].equals("--help")||
3744                          args[0].equals("-h"))   ||
3745                         (args.length == 0)) {
3746
3747                         IoTCompiler.printUsage();
3748
3749                 } else if (args.length > 1) {
3750
3751                         IoTCompiler comp = new IoTCompiler();
3752                         int i = 0;                              
3753                         do {
3754                                 // Parse main policy file
3755                                 ParseNode pnPol = IoTCompiler.parseFile(args[i]);
3756                                 // Parse "requires" policy file
3757                                 ParseNode pnReq = IoTCompiler.parseFile(args[i+1]);
3758                                 // Get interface name
3759                                 String intface = ParseTreeHandler.getOrigIntface(pnPol);
3760                                 comp.setDataStructures(intface, pnPol, pnReq);
3761                                 comp.getMethodsForIntface(intface);
3762                                 i = i + 2;
3763                         // 1) Check if this is the last option before "-java" or "-cplus"
3764                         // 2) Check if this is really the last option (no "-java" or "-cplus")
3765                         } while(!args[i].equals("-java") &&
3766                                         !args[i].equals("-cplus") &&
3767                                         (i < args.length));
3768
3769                         // Generate everything if we don't see "-java" or "-cplus"
3770                         if (i == args.length) {
3771                                 comp.generateEnumJava();
3772                                 comp.generateStructJava();
3773                                 comp.generateJavaLocalInterfaces();
3774                                 comp.generateJavaInterfaces();
3775                                 comp.generateJavaStubClasses();
3776                                 comp.generateJavaCallbackStubClasses();
3777                                 comp.generateJavaSkeletonClass();
3778                                 comp.generateJavaCallbackSkeletonClass();
3779                                 comp.generateEnumCplus();
3780                                 comp.generateStructCplus();
3781                                 comp.generateCplusLocalInterfaces();
3782                                 comp.generateCPlusInterfaces();
3783                                 comp.generateCPlusStubClasses();
3784                                 comp.generateCPlusCallbackStubClasses();
3785                                 comp.generateCplusSkeletonClass();
3786                                 comp.generateCplusCallbackSkeletonClass();
3787                         } else {
3788                         // Check other options
3789                                 while(i < args.length) {
3790                                         // Error checking
3791                                         if (!args[i].equals("-java") &&
3792                                                 !args[i].equals("-cplus")) {
3793                                                 throw new Error("IoTCompiler: ERROR - unrecognized command line option: " + args[i]);
3794                                         } else {
3795                                                 if (i + 1 < args.length) {
3796                                                         comp.setDirectory(args[i+1]);
3797                                                 } else
3798                                                         throw new Error("IoTCompiler: ERROR - please provide <directory> after option: " + args[i]);
3799
3800                                                 if (args[i].equals("-java")) {
3801                                                         comp.generateEnumJava();
3802                                                         comp.generateStructJava();
3803                                                         comp.generateJavaLocalInterfaces();
3804                                                         comp.generateJavaInterfaces();
3805                                                         comp.generateJavaStubClasses();
3806                                                         comp.generateJavaCallbackStubClasses();
3807                                                         comp.generateJavaSkeletonClass();
3808                                                         comp.generateJavaCallbackSkeletonClass();
3809                                                 } else {
3810                                                         comp.generateEnumCplus();
3811                                                         comp.generateStructCplus();
3812                                                         comp.generateCplusLocalInterfaces();
3813                                                         comp.generateCPlusInterfaces();
3814                                                         comp.generateCPlusStubClasses();
3815                                                         comp.generateCPlusCallbackStubClasses();
3816                                                         comp.generateCplusSkeletonClass();
3817                                                         comp.generateCplusCallbackSkeletonClass();
3818                                                 }
3819                                         }
3820                                         i = i + 2;
3821                                 }
3822                         }
3823                 } else {
3824                 // Need to at least have exactly 2 parameters, i.e. main policy file and requires file
3825                         IoTCompiler.printUsage();
3826                         throw new Error("IoTCompiler: At least two arguments (main and requires policy files) have to be provided!");
3827                 }
3828         }
3829 }
3830
3831
3832
3833