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