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