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