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