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