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