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