Fixing bugs: 1) Arrays.asList generates finaled List (need to feed it into an ArrayLi...
[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                                         // Iterate over interfaces to give permissions to
1236                                         Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
1237                                         for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
1238                                                 String newIntface = intMeth.getKey();
1239                                                 int newObjectId = getNewIntfaceObjectId(newIntface);
1240                                                 println("set" + newObjectId + "Allowed.add(" + methodNumId + ");");
1241                                         }
1242                                 }
1243                         }
1244                 }
1245         }
1246
1247
1248         /**
1249          * HELPER: writeConstructorJavaSkeleton() writes the constructor of the skeleton class
1250          */
1251         private void writeConstructorJavaSkeleton(String newSkelClass, String intface, InterfaceDecl intDecl, Collection<String> methods, boolean callbackExist) {
1252
1253                 println("public " + newSkelClass + "(" + intface + " _mainObj, int _port) throws Exception {");
1254                 println("mainObj = _mainObj;");
1255                 println("rmiObj = new IoTRMIObject(_port);");
1256                 // Generate permission control initialization
1257                 writeConstructorJavaPermission(intface);
1258                 writeJavaInitCallbackPermission(intface, intDecl, callbackExist);
1259                 writeStructPermissionJavaSkeleton(methods, intDecl, intface);
1260                 println("___waitRequestInvokeMethod();");
1261                 println("}\n");
1262         }
1263
1264
1265         /**
1266          * HELPER: writeStdMethodBodyJavaSkeleton() writes the standard method body in the skeleton class
1267          */
1268         private void writeStdMethodBodyJavaSkeleton(List<String> methParams, String methodId, String methodType) {
1269
1270                 if (methodType.equals("void"))
1271                         print("mainObj." + methodId + "(");
1272                 else
1273                         print("return mainObj." + methodId + "(");
1274                 for (int i = 0; i < methParams.size(); i++) {
1275
1276                         print(getSimpleIdentifier(methParams.get(i)));
1277                         // Check if this is the last element (don't print a comma)
1278                         if (i != methParams.size() - 1) {
1279                                 print(", ");
1280                         }
1281                 }
1282                 println(");");
1283         }
1284
1285
1286         /**
1287          * HELPER: writeInitCallbackJavaSkeleton() writes the init callback method for skeleton class
1288          */
1289         private void writeInitCallbackJavaSkeleton(boolean callbackSkeleton) {
1290
1291                 // This is a callback skeleton generation
1292                 if (callbackSkeleton)
1293                         println("public void ___regCB(IoTRMIObject rmiObj) throws IOException {");
1294                 else
1295                         println("public void ___regCB() throws IOException {");
1296                 println("Object[] paramObj = rmiObj.getMethodParams(new Class<?>[] { int.class, String.class, int.class },");
1297                 println("\tnew Class<?>[] { null, null, null });");
1298                 println("rmiCall = new IoTRMICall((int) paramObj[0], (String) paramObj[1], (int) paramObj[2]);");
1299                 println("}\n");
1300         }
1301
1302
1303         /**
1304          * HELPER: writeMethodJavaSkeleton() writes the method of the skeleton class
1305          */
1306         private void writeMethodJavaSkeleton(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses, 
1307                         boolean callbackSkeleton) {
1308
1309                 for (String method : methods) {
1310
1311                         List<String> methParams = intDecl.getMethodParams(method);
1312                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1313                         String methodId = intDecl.getMethodId(method);
1314                         print("public " + intDecl.getMethodType(method) + " " + methodId + "(");
1315                         boolean isCallbackMethod = false;
1316                         String callbackType = null;
1317                         for (int i = 0; i < methParams.size(); i++) {
1318
1319                                 String origParamType = methPrmTypes.get(i);
1320                                 String paramType = checkAndGetParamClass(origParamType);
1321                                 if (callbackClasses.contains(origParamType)) { // Check if this has callback object
1322                                         isCallbackMethod = true;
1323                                         callbackType = origParamType;   
1324                                 }
1325                                 print(paramType + " " + methParams.get(i));
1326                                 // Check if this is the last element (don't print a comma)
1327                                 if (i != methParams.size() - 1) {
1328                                         print(", ");
1329                                 }
1330                         }
1331                         println(") {");
1332                         // Now, write the body of skeleton!
1333                         writeStdMethodBodyJavaSkeleton(methParams, methodId, intDecl.getMethodType(method));
1334                         println("}\n");
1335                         if (isCallbackMethod)
1336                                 writeInitCallbackJavaSkeleton(callbackSkeleton);
1337                 }
1338         }
1339
1340
1341         /**
1342          * HELPER: writeCallbackJavaStubGeneration() writes the callback stub generation part
1343          */
1344         private Map<Integer,String> writeCallbackJavaStubGeneration(List<String> methParams, List<String> methPrmTypes, 
1345                         String callbackType) {
1346
1347                 Map<Integer,String> mapStubParam = new HashMap<Integer,String>();
1348                 // Iterate over callback objects
1349                 for (int i = 0; i < methParams.size(); i++) {
1350                         String paramType = methPrmTypes.get(i);
1351                         String param = methParams.get(i);
1352                         //if (callbackType.equals(paramType)) {
1353                         if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
1354                                 println("try {");
1355                                 String exchParamType = checkAndGetParamClass(paramType);
1356                                 // Print array if this is array or list if this is a list of callback objects
1357                                 if (isArray(param)) {
1358                                         println("int numStubs" + i + " = (int) paramObj[" + i + "];");
1359                                         println(exchParamType + "[] stub" + i + " = new " + exchParamType + "[numStubs" + i + "];");
1360                                 } else if (isList(paramType)) {
1361                                         println("int numStubs" + i + " = (int) paramObj[" + i + "];");
1362                                         println("List<" + exchParamType + "> stub" + i + " = new ArrayList<" + exchParamType + ">();");
1363                                 } else {
1364                                         println(exchParamType + " stub" + i + " = new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt);");
1365                                         println("objIdCnt++;");
1366                                 }
1367                         }
1368                         // Generate a loop if needed
1369                         if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
1370                                 String exchParamType = checkAndGetParamClass(paramType);
1371                                 if (isArray(param)) {
1372                                         println("for (int objId = 0; objId < numStubs" + i + "; objId++) {");
1373                                         println("stub" + i + "[objId] = new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt);");
1374                                         println("objIdCnt++;");
1375                                         println("}");
1376                                 } else if (isList(paramType)) {
1377                                         println("for (int objId = 0; objId < numStubs" + i + "; objId++) {");
1378                                         println("stub" + i + ".add(new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt));");
1379                                         println("objIdCnt++;");
1380                                         println("}");
1381                                 }
1382                                 mapStubParam.put(i, "stub" + i);        // List of all stub parameters
1383                         }
1384                 }
1385                 return mapStubParam;
1386         }
1387
1388
1389         /**
1390          * HELPER: checkAndWriteEnumTypeJavaSkeleton() writes the enum type (convert from enum to int)
1391          */
1392         private void checkAndWriteEnumTypeJavaSkeleton(List<String> methParams, List<String> methPrmTypes) {
1393
1394                 // Iterate and find enum declarations
1395                 for (int i = 0; i < methParams.size(); i++) {
1396                         String paramType = methPrmTypes.get(i);
1397                         String param = methParams.get(i);
1398                         String simpleType = getGenericType(paramType);
1399                         if (isEnumClass(simpleType)) {
1400                         // Check if this is enum type
1401                                 println("int paramInt" + i + "[] = (int[]) paramObj[" + i + "];");
1402                                 println(simpleType + "[] enumVals = " + simpleType + ".values();");
1403                                 if (isArray(param)) {   // An array
1404                                         println("int len" + i + " = paramInt" + i + ".length;");
1405                                         println(simpleType + "[] paramEnum" + i + " = new " + simpleType + "[len" + i + "];");
1406                                         println("for (int i = 0; i < len" + i + "; i++) {");
1407                                         println("paramEnum" + i + "[i] = enumVals[paramInt" + i + "[i]];");
1408                                         println("}");
1409                                 } else if (isList(paramType)) { // A list
1410                                         println("int len" + i + " = paramInt" + i + ".length;");
1411                                         println("List<" + simpleType + "> paramEnum" + i + " = new ArrayList<" + simpleType + ">();");
1412                                         println("for (int i = 0; i < len" + i + "; i++) {");
1413                                         println("paramEnum" + i + ".add(enumVals[paramInt" + i + "[i]]);");
1414                                         println("}");
1415                                 } else {        // Just one element
1416                                         println(simpleType + " paramEnum" + i + " = enumVals[paramInt" + i + "[0]];");
1417                                 }
1418                         }
1419                 }
1420         }
1421
1422
1423         /**
1424          * HELPER: checkAndWriteEnumRetTypeJavaSkeleton() writes the enum return type (convert from enum to int)
1425          */
1426         private void checkAndWriteEnumRetTypeJavaSkeleton(String retType, String methodId) {
1427
1428                 // Strips off array "[]" for return type
1429                 String pureType = getSimpleArrayType(getGenericType(retType));
1430                 // Take the inner type of generic
1431                 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
1432                         pureType = getGenericType(retType);
1433                 if (isEnumClass(pureType)) {
1434                 // Check if this is enum type
1435                         // Enum decoder
1436                         if (isArray(retType)) {                 // An array
1437                                 print(pureType + "[] retEnum = " + methodId + "(");
1438                         } else if (isList(retType)) {   // A list
1439                                 print("List<" + pureType + "> retEnum = " + methodId + "(");
1440                         } else {        // Just one element
1441                                 print(pureType + " retEnum = " + methodId + "(");
1442                         }
1443                 }
1444         }
1445
1446
1447         /**
1448          * HELPER: checkAndWriteEnumRetConvJavaSkeleton() writes the enum return type (convert from enum to int)
1449          */
1450         private void checkAndWriteEnumRetConvJavaSkeleton(String retType) {
1451
1452                 // Strips off array "[]" for return type
1453                 String pureType = getSimpleArrayType(getGenericType(retType));
1454                 // Take the inner type of generic
1455                 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
1456                         pureType = getGenericType(retType);
1457                 if (isEnumClass(pureType)) {
1458                 // Check if this is enum type
1459                         if (isArray(retType)) { // An array
1460                                 println("int retLen = retEnum.length;");
1461                                 println("int[] retEnumVal = new int[retLen];");
1462                                 println("for (int i = 0; i < retLen; i++) {");
1463                                 println("retEnumVal[i] = retEnum[i].ordinal();");
1464                                 println("}");
1465                         } else if (isList(retType)) {   // A list
1466                                 println("int retLen = retEnum.size();");
1467                                 println("int[] retEnumVal = new int[retLen];");
1468                                 println("for (int i = 0; i < retLen; i++) {");
1469                                 println("retEnumVal[i] = retEnum.get(i).ordinal();");
1470                                 println("}");
1471                         } else {        // Just one element
1472                                 println("int[] retEnumVal = new int[1];");
1473                                 println("retEnumVal[0] = retEnum.ordinal();");
1474                         }
1475                         println("Object retObj = retEnumVal;");
1476                 }
1477         }
1478         
1479         
1480         /**
1481          * HELPER: writeLengthStructParamClassSkeleton() writes lengths of params
1482          */
1483         private void writeLengthStructParamClassSkeleton(List<String> methParams, List<String> methPrmTypes, 
1484                         String method, InterfaceDecl intDecl) {
1485
1486                 // Iterate and find struct declarations - count number of params
1487                 for (int i = 0; i < methParams.size(); i++) {
1488                         String paramType = methPrmTypes.get(i);
1489                         String param = methParams.get(i);
1490                         String simpleType = getGenericType(paramType);
1491                         if (isStructClass(simpleType)) {
1492                                 int members = getNumOfMembers(simpleType);
1493                                 print(Integer.toString(members) + "*");
1494                                 int methodNumId = intDecl.getMethodNumId(method);
1495                                 print("struct" + methodNumId + "Size" + i);
1496                         } else
1497                                 print("1");
1498                         if (i != methParams.size() - 1) {
1499                                 print("+");
1500                         }
1501                 }
1502         }
1503
1504         
1505         /**
1506          * HELPER: writeStructMembersJavaSkeleton() writes member parameters of struct
1507          */
1508         private void writeStructMembersJavaSkeleton(String simpleType, String paramType, 
1509                         String param, String method, InterfaceDecl intDecl, int iVar) {
1510
1511                 // Get the struct declaration for this struct and generate initialization code
1512                 StructDecl structDecl = getStructDecl(simpleType);
1513                 List<String> memTypes = structDecl.getMemberTypes(simpleType);
1514                 List<String> members = structDecl.getMembers(simpleType);
1515                 if (isArrayOrList(param, paramType)) {  // An array or list
1516                         int methodNumId = intDecl.getMethodNumId(method);
1517                         String counter = "struct" + methodNumId + "Size" + iVar;
1518                         println("for(int i = 0; i < " + counter + "; i++) {");
1519                 }
1520                 println("int pos = 0;");
1521                 if (isArrayOrList(param, paramType)) {  // An array or list
1522                         println("for(int i = 0; i < retLen; i++) {");
1523                         for (int i = 0; i < members.size(); i++) {
1524                                 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
1525                                 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
1526                                 println("paramClsGen[pos++] = null;");
1527                         }
1528                         println("}");
1529                 } else {        // Just one struct element
1530                         for (int i = 0; i < members.size(); i++) {
1531                                 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
1532                                 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
1533                                 println("paramClsGen[pos++] = null;");
1534                         }
1535                 }
1536         }
1537
1538
1539         /**
1540          * HELPER: writeStructMembersInitJavaSkeleton() writes member parameters initialization of struct
1541          */
1542         private void writeStructMembersInitJavaSkeleton(InterfaceDecl intDecl, List<String> methParams,
1543                         List<String> methPrmTypes, String method) {
1544
1545                 for (int i = 0; i < methParams.size(); i++) {
1546                         String paramType = methPrmTypes.get(i);
1547                         String param = methParams.get(i);
1548                         String simpleType = getGenericType(paramType);
1549                         if (isStructClass(simpleType)) {
1550                                 int methodNumId = intDecl.getMethodNumId(method);
1551                                 String counter = "struct" + methodNumId + "Size" + i;
1552                                 // Declaration
1553                                 if (isArray(param)) {                   // An array
1554                                         println(simpleType + "[] paramStruct" + i + " = new " + simpleType + "[" + counter + "];");
1555                                         println("for(int i = 0; i < " + counter + "; i++) {");
1556                                         println("paramStruct" + i + "[i] = new " + simpleType + "();");
1557                                         println("}");
1558                                 } else if (isList(paramType)) { // A list
1559                                         println("List<" + simpleType + "> paramStruct" + i + " = new ArrayList<" + simpleType + ">();");
1560                                 } else
1561                                         println(simpleType + " paramStruct" + i + " = new " + simpleType + "();");
1562                                 println("int objPos = 0;");
1563                                 // Initialize members
1564                                 StructDecl structDecl = getStructDecl(simpleType);
1565                                 List<String> members = structDecl.getMembers(simpleType);
1566                                 List<String> memTypes = structDecl.getMemberTypes(simpleType);
1567                                 if (isArrayOrList(param, paramType)) {  // An array or list
1568                                         println("for(int i = 0; i < " + counter + "; i++) {");
1569                                 }
1570                                 if (isArray(param)) {   // An array
1571                                         for (int j = 0; j < members.size(); j++) {
1572                                                 String prmType = checkAndGetArray(memTypes.get(j), members.get(j));
1573                                                 print("paramStruct" + i + "[i]." + getSimpleIdentifier(members.get(j)));
1574                                                 println(" = (" + getSimpleType(getEnumType(prmType)) + ") paramObj[objPos++];");
1575                                         }
1576                                         println("}");
1577                                 } else if (isList(paramType)) { // A list
1578                                         println(simpleType + " paramStructMem = new " + simpleType + "();");
1579                                         for (int j = 0; j < members.size(); j++) {
1580                                                 String prmType = checkAndGetArray(memTypes.get(j), members.get(j));
1581                                                 print("paramStructMem." + getSimpleIdentifier(members.get(j)));
1582                                                 println(" = (" + getSimpleType(getEnumType(prmType)) + ") paramObj[objPos++];");
1583                                         }
1584                                         println("paramStruct" + i + ".add(paramStructMem);");
1585                                         println("}");
1586                                 } else {        // Just one struct element
1587                                         for (int j = 0; j < members.size(); j++) {
1588                                                 String prmType = checkAndGetArray(memTypes.get(j), members.get(j));
1589                                                 print("paramStruct" + i + "." + getSimpleIdentifier(members.get(j)));
1590                                                 println(" = (" + getSimpleType(getEnumType(prmType)) + ") paramObj[objPos++];");
1591                                         }
1592                                 }
1593                         } else {
1594                                 // Take offsets of parameters
1595                                 println("int offset" + i +" = objPos;");
1596                         }
1597                 }
1598         }
1599
1600
1601         /**
1602          * HELPER: writeStructReturnJavaSkeleton() writes struct for return statement
1603          */
1604         private void writeStructReturnJavaSkeleton(String simpleType, String retType) {
1605
1606                 // Minimum retLen is 1 if this is a single struct object
1607                 if (isArray(retType))
1608                         println("int retLen = retStruct.length;");
1609                 else if (isList(retType))
1610                         println("int retLen = retStruct.size();");
1611                 else    // Just single struct object
1612                         println("int retLen = 1;");
1613                 println("Object retLenObj = retLen;");
1614                 println("rmiObj.sendReturnObj(retLenObj);");
1615                 int numMem = getNumOfMembers(simpleType);
1616                 println("Class<?>[] retCls = new Class<?>[" + numMem + "*retLen];");
1617                 println("Object[] retObj = new Object[" + numMem + "*retLen];");
1618                 println("int retPos = 0;");
1619                 // Get the struct declaration for this struct and generate initialization code
1620                 StructDecl structDecl = getStructDecl(simpleType);
1621                 List<String> memTypes = structDecl.getMemberTypes(simpleType);
1622                 List<String> members = structDecl.getMembers(simpleType);
1623                 if (isArrayOrList(retType, retType)) {  // An array or list
1624                         println("for(int i = 0; i < retLen; i++) {");
1625                         for (int i = 0; i < members.size(); i++) {
1626                                 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
1627                                 println("retCls[retPos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
1628                                 print("retObj[retPos++] = retStruct[i].");
1629                                 print(getEnumParam(memTypes.get(i), getSimpleIdentifier(members.get(i)), i));
1630                                 println(";");
1631                         }
1632                         println("}");
1633                 } else {        // Just one struct element
1634                         for (int i = 0; i < members.size(); i++) {
1635                                 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
1636                                 println("retCls[retPos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
1637                                 print("retObj[retPos++] = retStruct.");
1638                                 print(getEnumParam(memTypes.get(i), getSimpleIdentifier(members.get(i)), i));
1639                                 println(";");
1640                         }
1641                 }
1642
1643         }
1644
1645
1646         /**
1647          * HELPER: writeMethodHelperReturnJavaSkeleton() writes return statement part in skeleton
1648          */
1649         private void writeMethodHelperReturnJavaSkeleton(InterfaceDecl intDecl, List<String> methParams,
1650                         List<String> methPrmTypes, String method, boolean isCallbackMethod, String callbackType,
1651                         boolean isStructMethod) {
1652
1653                 checkAndWriteEnumTypeJavaSkeleton(methParams, methPrmTypes);
1654                 Map<Integer,String> mapStubParam = null;
1655                 if (isCallbackMethod)
1656                         mapStubParam = writeCallbackJavaStubGeneration(methParams, methPrmTypes, callbackType);
1657                 // Check if this is "void"
1658                 String retType = intDecl.getMethodType(method);
1659                 if (retType.equals("void")) {
1660                         print(intDecl.getMethodId(method) + "(");
1661                 } else if (isEnumClass(getSimpleArrayType(getGenericType(retType)))) {  // Enum type
1662                         checkAndWriteEnumRetTypeJavaSkeleton(retType, intDecl.getMethodId(method));
1663                 } else if (isStructClass(getSimpleArrayType(getGenericType(retType)))) {        // Struct type
1664                         print(retType + " retStruct = " + intDecl.getMethodId(method) + "(");
1665                 } else { // We do have a return value
1666                         print("Object retObj = " + intDecl.getMethodId(method) + "(");
1667                 }
1668                 for (int i = 0; i < methParams.size(); i++) {
1669
1670                         if (isCallbackMethod) {
1671                                 print(mapStubParam.get(i));     // Get the callback parameter
1672                         } else if (isEnumClass(getGenericType(methPrmTypes.get(i)))) { // Enum class
1673                                 print(getEnumParam(methPrmTypes.get(i), methParams.get(i), i));
1674                         } else if (isStructClass(getGenericType(methPrmTypes.get(i)))) {
1675                                 print("paramStruct" + i);
1676                         } else {
1677                                 String prmType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
1678                                 if (isStructMethod)
1679                                         print("(" + prmType + ") paramObj[offset" + i + "]");
1680                                 else
1681                                         print("(" + prmType + ") paramObj[" + i + "]");
1682                         }
1683                         if (i != methParams.size() - 1)
1684                                 print(", ");
1685                 }
1686                 println(");");
1687                 if (!retType.equals("void")) {
1688                         if (isEnumClass(getSimpleArrayType(getGenericType(retType)))) { // Enum type
1689                                 checkAndWriteEnumRetConvJavaSkeleton(retType);
1690                                 println("rmiObj.sendReturnObj(retObj);");
1691                         } else if (isStructClass(getSimpleArrayType(getGenericType(retType)))) { // Struct type
1692                                 writeStructReturnJavaSkeleton(getSimpleArrayType(getGenericType(retType)), retType);
1693                                 println("rmiObj.sendReturnObj(retCls, retObj);");
1694                         } else
1695                                 println("rmiObj.sendReturnObj(retObj);");
1696                 }
1697                 if (isCallbackMethod) { // Catch exception if this is callback
1698                         print("}");
1699                         println(" catch(Exception ex) {");
1700                         println("ex.printStackTrace();");
1701                         println("throw new Error(\"Exception from callback object instantiation!\");");
1702                         println("}");
1703                 }
1704         }
1705
1706
1707         /**
1708          * HELPER: writeMethodHelperStructJavaSkeleton() writes the struct in skeleton
1709          */
1710         private void writeMethodHelperStructJavaSkeleton(InterfaceDecl intDecl, List<String> methParams,
1711                         List<String> methPrmTypes, String method, Set<String> callbackClasses) {
1712
1713                 // Generate array of parameter objects
1714                 boolean isCallbackMethod = false;
1715                 String callbackType = null;
1716                 print("int paramLen = ");
1717                 writeLengthStructParamClassSkeleton(methParams, methPrmTypes, method, intDecl);
1718                 println(";");
1719                 println("Class<?>[] paramCls = new Class<?>[paramLen];");
1720                 println("Class<?>[] paramClsGen = new Class<?>[paramLen];");
1721                 // Iterate again over the parameters
1722                 for (int i = 0; i < methParams.size(); i++) {
1723                         String paramType = methPrmTypes.get(i);
1724                         String param = methParams.get(i);
1725                         String simpleType = getGenericType(paramType);
1726                         if (isStructClass(simpleType)) {
1727                                 writeStructMembersJavaSkeleton(simpleType, paramType, param, method, intDecl, i);
1728                         } else {
1729                                 String prmType = returnGenericCallbackType(methPrmTypes.get(i));
1730                                 if (callbackClasses.contains(prmType)) {
1731                                         isCallbackMethod = true;
1732                                         callbackType = prmType;
1733                                         println("paramCls[pos] = int.class;");
1734                                         println("paramClsGen[pos++] = null;");
1735                                 } else {        // Generate normal classes if it's not a callback object
1736                                         String paramTypeOth = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
1737                                         println("paramCls[pos] = " + getSimpleType(getEnumType(paramTypeOth)) + ".class;");
1738                                         print("paramClsGen[pos++] = ");
1739                                         String prmTypeOth = methPrmTypes.get(i);
1740                                         if (getParamCategory(prmTypeOth) == ParamCategory.NONPRIMITIVES)
1741                                                 println(getTypeOfGeneric(prmType)[0] + ".class;");
1742                                         else
1743                                                 println("null;");
1744                                 }
1745                         }
1746                 }
1747                 println("Object[] paramObj = rmiObj.getMethodParams(paramCls, paramClsGen);");
1748                 writeStructMembersInitJavaSkeleton(intDecl, methParams, methPrmTypes, method);
1749                 // Write the return value part
1750                 writeMethodHelperReturnJavaSkeleton(intDecl, methParams, methPrmTypes, method, isCallbackMethod, callbackType, true);
1751         }
1752
1753
1754         /**
1755          * HELPER: writeStdMethodHelperBodyJavaSkeleton() writes the standard method body helper in the skeleton class
1756          */
1757         private void writeStdMethodHelperBodyJavaSkeleton(InterfaceDecl intDecl, List<String> methParams,
1758                         List<String> methPrmTypes, String method, Set<String> callbackClasses) {
1759
1760                 // Generate array of parameter objects
1761                 boolean isCallbackMethod = false;
1762                 String callbackType = null;
1763                 print("Object[] paramObj = rmiObj.getMethodParams(new Class<?>[] { ");
1764                 for (int i = 0; i < methParams.size(); i++) {
1765
1766                         String paramType = returnGenericCallbackType(methPrmTypes.get(i));
1767                         if (callbackClasses.contains(paramType)) {
1768                                 isCallbackMethod = true;
1769                                 callbackType = paramType;
1770                                 print("int.class");
1771                         } else {        // Generate normal classes if it's not a callback object
1772                                 String prmType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
1773                                 print(getSimpleType(getEnumType(prmType)) + ".class");
1774                         }
1775                         if (i != methParams.size() - 1)
1776                                 print(", ");
1777                 }
1778                 println(" }, ");
1779                 // Generate generic class if it's a generic type.. null otherwise
1780                 print("new Class<?>[] { ");
1781                 for (int i = 0; i < methParams.size(); i++) {
1782                         String prmType = methPrmTypes.get(i);
1783                         if ((getParamCategory(prmType) == ParamCategory.NONPRIMITIVES) &&
1784                                 !isEnumClass(getGenericType(prmType)))
1785                                         print(getGenericType(prmType) + ".class");
1786                         else
1787                                 print("null");
1788                         if (i != methParams.size() - 1)
1789                                 print(", ");
1790                 }
1791                 println(" });");
1792                 // Write the return value part
1793                 writeMethodHelperReturnJavaSkeleton(intDecl, methParams, methPrmTypes, method, isCallbackMethod, callbackType, false);
1794         }
1795
1796
1797         /**
1798          * HELPER: writeMethodHelperJavaSkeleton() writes the method helper of the skeleton class
1799          */
1800         private void writeMethodHelperJavaSkeleton(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
1801
1802                 // Use this set to handle two same methodIds
1803                 Set<String> uniqueMethodIds = new HashSet<String>();
1804                 for (String method : methods) {
1805
1806                         List<String> methParams = intDecl.getMethodParams(method);
1807                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1808                         if (isStructPresent(methParams, methPrmTypes)) {        // Treat struct differently
1809                                 String methodId = intDecl.getMethodId(method);
1810                                 print("public void ___");
1811                                 String helperMethod = methodId;
1812                                 if (uniqueMethodIds.contains(methodId))
1813                                         helperMethod = helperMethod + intDecl.getMethodNumId(method);
1814                                 else
1815                                         uniqueMethodIds.add(methodId);
1816                                 String retType = intDecl.getMethodType(method);
1817                                 print(helperMethod + "(");
1818                                 boolean begin = true;
1819                                 for (int i = 0; i < methParams.size(); i++) { // Print size variables
1820                                         String paramType = methPrmTypes.get(i);
1821                                         String param = methParams.get(i);
1822                                         String simpleType = getSimpleType(paramType);
1823                                         if (isStructClass(simpleType)) {
1824                                                 if (!begin) {   // Generate comma for not the beginning variable
1825                                                         print(", "); begin = false;
1826                                                 }
1827                                                 int methodNumId = intDecl.getMethodNumId(method);
1828                                                 print("int struct" + methodNumId + "Size" + i);
1829                                         }
1830                                 }
1831                                 // Check if this is "void"
1832                                 if (retType.equals("void"))
1833                                         println(") {");
1834                                 else
1835                                         println(") throws IOException {");
1836                                 writeMethodHelperStructJavaSkeleton(intDecl, methParams, methPrmTypes, method, callbackClasses);
1837                                 println("}\n");
1838                         } else {
1839                                 String methodId = intDecl.getMethodId(method);
1840                                 print("public void ___");
1841                                 String helperMethod = methodId;
1842                                 if (uniqueMethodIds.contains(methodId))
1843                                         helperMethod = helperMethod + intDecl.getMethodNumId(method);
1844                                 else
1845                                         uniqueMethodIds.add(methodId);
1846                                 // Check if this is "void"
1847                                 String retType = intDecl.getMethodType(method);
1848                                 if (retType.equals("void"))
1849                                         println(helperMethod + "() {");
1850                                 else
1851                                         println(helperMethod + "() throws IOException {");
1852                                 // Now, write the helper body of skeleton!
1853                                 writeStdMethodHelperBodyJavaSkeleton(intDecl, methParams, methPrmTypes, method, callbackClasses);
1854                                 println("}\n");
1855                         }
1856                 }
1857                 // Write method helper for structs
1858                 writeMethodHelperStructSetupJavaSkeleton(methods, intDecl);
1859         }
1860
1861
1862         /**
1863          * HELPER: writeMethodHelperStructSetupJavaSkeleton() writes the method helper of struct setup in skeleton class
1864          */
1865         private void writeMethodHelperStructSetupJavaSkeleton(Collection<String> methods, 
1866                         InterfaceDecl intDecl) {
1867
1868                 // Use this set to handle two same methodIds
1869                 for (String method : methods) {
1870
1871                         List<String> methParams = intDecl.getMethodParams(method);
1872                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1873                         // Check for params with structs
1874                         for (int i = 0; i < methParams.size(); i++) {
1875                                 String paramType = methPrmTypes.get(i);
1876                                 String param = methParams.get(i);
1877                                 String simpleType = getSimpleType(paramType);
1878                                 if (isStructClass(simpleType)) {
1879                                         int methodNumId = intDecl.getMethodNumId(method);
1880                                         print("public int ___");
1881                                         String helperMethod = methodNumId + "struct" + i;
1882                                         println(helperMethod + "() {");
1883                                         // Now, write the helper body of skeleton!
1884                                         println("Object[] paramObj = rmiObj.getMethodParams(new Class<?>[] { int.class }, new Class<?>[] { null });");
1885                                         println("return (int) paramObj[0];");
1886                                         println("}\n");
1887                                 }
1888                         }
1889                 }
1890         }
1891
1892
1893         /**
1894          * HELPER: writeMethodHelperStructSetupJavaCallbackSkeleton() writes the method helper of struct setup in callback skeleton class
1895          */
1896         private void writeMethodHelperStructSetupJavaCallbackSkeleton(Collection<String> methods, 
1897                         InterfaceDecl intDecl) {
1898
1899                 // Use this set to handle two same methodIds
1900                 for (String method : methods) {
1901
1902                         List<String> methParams = intDecl.getMethodParams(method);
1903                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1904                         // Check for params with structs
1905                         for (int i = 0; i < methParams.size(); i++) {
1906                                 String paramType = methPrmTypes.get(i);
1907                                 String param = methParams.get(i);
1908                                 String simpleType = getSimpleType(paramType);
1909                                 if (isStructClass(simpleType)) {
1910                                         int methodNumId = intDecl.getMethodNumId(method);
1911                                         print("public int ___");
1912                                         String helperMethod = methodNumId + "struct" + i;
1913                                         println(helperMethod + "(IoTRMIObject rmiObj) {");
1914                                         // Now, write the helper body of skeleton!
1915                                         println("Object[] paramObj = rmiObj.getMethodParams(new Class<?>[] { int.class }, new Class<?>[] { null });");
1916                                         println("return (int) paramObj[0];");
1917                                         println("}\n");
1918                                 }
1919                         }
1920                 }
1921         }
1922
1923
1924         /**
1925          * HELPER: writeCountVarStructSkeleton() writes counter variable of struct for skeleton
1926          */
1927         private void writeCountVarStructSkeleton(Collection<String> methods, InterfaceDecl intDecl) {
1928
1929                 // Use this set to handle two same methodIds
1930                 for (String method : methods) {
1931
1932                         List<String> methParams = intDecl.getMethodParams(method);
1933                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1934                         // Check for params with structs
1935                         for (int i = 0; i < methParams.size(); i++) {
1936                                 String paramType = methPrmTypes.get(i);
1937                                 String param = methParams.get(i);
1938                                 String simpleType = getSimpleType(paramType);
1939                                 if (isStructClass(simpleType)) {
1940                                         int methodNumId = intDecl.getMethodNumId(method);
1941                                         println("int struct" + methodNumId + "Size" + i + " = 0;");
1942                                 }
1943                         }
1944                 }
1945         }
1946         
1947         
1948         /**
1949          * HELPER: writeInputCountVarStructSkeleton() writes input counter variable of struct for skeleton
1950          */
1951         private boolean writeInputCountVarStructSkeleton(String method, InterfaceDecl intDecl) {
1952
1953                 List<String> methParams = intDecl.getMethodParams(method);
1954                 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1955                 boolean structExist = false;
1956                 // Check for params with structs
1957                 for (int i = 0; i < methParams.size(); i++) {
1958                         String paramType = methPrmTypes.get(i);
1959                         String param = methParams.get(i);
1960                         String simpleType = getSimpleType(paramType);
1961                         boolean begin = true;
1962                         if (isStructClass(simpleType)) {
1963                                 structExist = true;
1964                                 if (!begin) {
1965                                         print(", "); begin = false;
1966                                 }
1967                                 int methodNumId = intDecl.getMethodNumId(method);
1968                                 print("struct" + methodNumId + "Size" + i);
1969                         }
1970                 }
1971                 return structExist;
1972         }
1973
1974
1975         /**
1976          * HELPER: writeMethodCallStructSkeleton() writes method call for wait invoke in skeleton
1977          */
1978         private void writeMethodCallStructSkeleton(Collection<String> methods, InterfaceDecl intDecl) {
1979
1980                 // Use this set to handle two same methodIds
1981                 for (String method : methods) {
1982
1983                         List<String> methParams = intDecl.getMethodParams(method);
1984                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1985                         // Check for params with structs
1986                         for (int i = 0; i < methParams.size(); i++) {
1987                                 String paramType = methPrmTypes.get(i);
1988                                 String param = methParams.get(i);
1989                                 String simpleType = getSimpleType(paramType);
1990                                 if (isStructClass(simpleType)) {
1991                                         int methodNumId = intDecl.getMethodNumId(method);
1992                                         print("case ");
1993                                         String helperMethod = methodNumId + "struct" + i;
1994                                         String tempVar = "struct" + methodNumId + "Size" + i;
1995                                         print(intDecl.getHelperMethodNumId(helperMethod) + ": ");
1996                                         print(tempVar + " = ___");
1997                                         println(helperMethod + "(); break;");
1998                                 }
1999                         }
2000                 }
2001         }
2002
2003
2004         /**
2005          * HELPER: writeMethodCallStructCallbackSkeleton() writes method call for wait invoke in skeleton
2006          */
2007         private void writeMethodCallStructCallbackSkeleton(Collection<String> methods, InterfaceDecl intDecl) {
2008
2009                 // Use this set to handle two same methodIds
2010                 for (String method : methods) {
2011
2012                         List<String> methParams = intDecl.getMethodParams(method);
2013                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2014                         // Check for params with structs
2015                         for (int i = 0; i < methParams.size(); i++) {
2016                                 String paramType = methPrmTypes.get(i);
2017                                 String param = methParams.get(i);
2018                                 String simpleType = getSimpleType(paramType);
2019                                 if (isStructClass(simpleType)) {
2020                                         int methodNumId = intDecl.getMethodNumId(method);
2021                                         print("case ");
2022                                         String helperMethod = methodNumId + "struct" + i;
2023                                         String tempVar = "struct" + methodNumId + "Size" + i;
2024                                         print(intDecl.getHelperMethodNumId(helperMethod) + ": ");
2025                                         print(tempVar + " = ___");
2026                                         println(helperMethod + "(rmiObj); break;");
2027                                 }
2028                         }
2029                 }
2030         }
2031
2032
2033         /**
2034          * HELPER: writeJavaMethodPermission() writes permission checks in skeleton
2035          */
2036         private void writeJavaMethodPermission(String intface) {
2037
2038                 // Get all the different stubs
2039                 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
2040                 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
2041                         String newIntface = intMeth.getKey();
2042                         int newObjectId = getNewIntfaceObjectId(newIntface);
2043                         println("if (_objectId == object" + newObjectId + "Id) {");
2044                         println("if (!set" + newObjectId + "Allowed.contains(methodId)) {");
2045                         println("throw new Error(\"Object with object Id: \" + _objectId + \"  is not allowed to access method: \" + methodId);");
2046                         println("}");
2047                         println("}");
2048                         println("else {");
2049                         println("throw new Error(\"Object Id: \" + _objectId + \" not recognized!\");");
2050                         println("}");
2051                 }
2052         }
2053
2054
2055         /**
2056          * HELPER: writeJavaWaitRequestInvokeMethod() writes the main loop of the skeleton class
2057          */
2058         private void writeJavaWaitRequestInvokeMethod(Collection<String> methods, InterfaceDecl intDecl, boolean callbackExist, String intface) {
2059
2060                 // Use this set to handle two same methodIds
2061                 Set<String> uniqueMethodIds = new HashSet<String>();
2062                 println("private void ___waitRequestInvokeMethod() throws IOException {");
2063                 // Write variables here if we have callbacks or enums or structs
2064                 writeCountVarStructSkeleton(methods, intDecl);
2065                 println("while (true) {");
2066                 println("rmiObj.getMethodBytes();");
2067                 println("int _objectId = rmiObj.getObjectId();");
2068                 println("int methodId = rmiObj.getMethodId();");
2069                 // Generate permission check
2070                 writeJavaMethodPermission(intface);
2071                 println("switch (methodId) {");
2072                 // Print methods and method Ids
2073                 for (String method : methods) {
2074                         String methodId = intDecl.getMethodId(method);
2075                         int methodNumId = intDecl.getMethodNumId(method);
2076                         print("case " + methodNumId + ": ___");
2077                         String helperMethod = methodId;
2078                         if (uniqueMethodIds.contains(methodId))
2079                                 helperMethod = helperMethod + methodNumId;
2080                         else
2081                                 uniqueMethodIds.add(methodId);
2082                         print(helperMethod + "(");
2083                         writeInputCountVarStructSkeleton(method, intDecl);
2084                         println("); break;");
2085                 }
2086                 String method = "___initCallBack()";
2087                 // Print case -9999 (callback handler) if callback exists
2088                 if (callbackExist) {
2089                         int methodId = intDecl.getHelperMethodNumId(method);
2090                         println("case " + methodId + ": ___regCB(); break;");
2091                 }
2092                 writeMethodCallStructSkeleton(methods, intDecl);
2093                 println("default: ");
2094                 println("throw new Error(\"Method Id \" + methodId + \" not recognized!\");");
2095                 println("}");
2096                 println("}");
2097                 println("}\n");
2098         }
2099
2100
2101         /**
2102          * generateJavaSkeletonClass() generate skeletons based on the methods list in Java
2103          */
2104         public void generateJavaSkeletonClass() throws IOException {
2105
2106                 // Create a new directory
2107                 String path = createDirectories(dir, subdir);
2108                 for (String intface : mapIntfacePTH.keySet()) {
2109                         // Open a new file to write into
2110                         String newSkelClass = intface + "_Skeleton";
2111                         FileWriter fw = new FileWriter(path + "/" + newSkelClass + ".java");
2112                         pw = new PrintWriter(new BufferedWriter(fw));
2113                         // Pass in set of methods and get import classes
2114                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2115                         InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
2116                         List<String> methods = intDecl.getMethods();
2117                         Set<String> importClasses = getImportClasses(methods, intDecl);
2118                         List<String> stdImportClasses = getStandardJavaImportClasses();
2119                         List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
2120                         printImportStatements(allImportClasses);
2121                         // Find out if there are callback objects
2122                         Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
2123                         boolean callbackExist = !callbackClasses.isEmpty();
2124                         // Write class header
2125                         println("");
2126                         println("public class " + newSkelClass  + " implements " + intface + " {\n");
2127                         // Write properties
2128                         writePropertiesJavaSkeleton(intface, callbackExist, intDecl);
2129                         // Write constructor
2130                         writeConstructorJavaSkeleton(newSkelClass, intface, intDecl, methods, callbackExist);
2131                         // Write methods
2132                         writeMethodJavaSkeleton(methods, intDecl, callbackClasses, false);
2133                         // Write method helper
2134                         writeMethodHelperJavaSkeleton(methods, intDecl, callbackClasses);
2135                         // Write waitRequestInvokeMethod() - main loop
2136                         writeJavaWaitRequestInvokeMethod(methods, intDecl, callbackExist, intface);
2137                         println("}");
2138                         pw.close();
2139                         System.out.println("IoTCompiler: Generated skeleton class " + newSkelClass + ".java...");
2140                 }
2141         }
2142
2143
2144         /**
2145          * HELPER: writePropertiesJavaCallbackSkeleton() writes the properties of the callback skeleton class
2146          */
2147         private void writePropertiesJavaCallbackSkeleton(String intface, boolean callbackExist) {
2148
2149                 println("private " + intface + " mainObj;");
2150                 // For callback skeletons, this is its own object Id
2151                 println("private static int objectId = 0;");
2152                 // Callback
2153                 if (callbackExist) {
2154                         println("private static int objIdCnt = 0;");
2155                         println("private IoTRMICall rmiCall;");
2156                 }
2157                 println("\n");
2158         }
2159
2160
2161         /**
2162          * HELPER: writeConstructorJavaCallbackSkeleton() writes the constructor of the skeleton class
2163          */
2164         private void writeConstructorJavaCallbackSkeleton(String newSkelClass, String intface, InterfaceDecl intDecl, Collection<String> methods) {
2165
2166                 println("public " + newSkelClass + "(" + intface + " _mainObj, int _objectId) throws Exception {");
2167                 println("mainObj = _mainObj;");
2168                 println("objectId = _objectId;");
2169                 writeStructPermissionJavaSkeleton(methods, intDecl, intface);
2170                 println("}\n");
2171         }
2172
2173
2174         /**
2175          * HELPER: writeMethodHelperJavaCallbackSkeleton() writes the method helper of the callback skeleton class
2176          */
2177         private void writeMethodHelperJavaCallbackSkeleton(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
2178
2179                 // Use this set to handle two same methodIds
2180                 Set<String> uniqueMethodIds = new HashSet<String>();
2181                 for (String method : methods) {
2182
2183                         List<String> methParams = intDecl.getMethodParams(method);
2184                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2185                         if (isStructPresent(methParams, methPrmTypes)) {        // Treat struct differently
2186                                 String methodId = intDecl.getMethodId(method);
2187                                 print("public void ___");
2188                                 String helperMethod = methodId;
2189                                 if (uniqueMethodIds.contains(methodId))
2190                                         helperMethod = helperMethod + intDecl.getMethodNumId(method);
2191                                 else
2192                                         uniqueMethodIds.add(methodId);
2193                                 String retType = intDecl.getMethodType(method);
2194                                 print(helperMethod + "(");
2195                                 boolean begin = true;
2196                                 for (int i = 0; i < methParams.size(); i++) { // Print size variables
2197                                         String paramType = methPrmTypes.get(i);
2198                                         String param = methParams.get(i);
2199                                         String simpleType = getSimpleType(paramType);
2200                                         if (isStructClass(simpleType)) {
2201                                                 if (!begin) {   // Generate comma for not the beginning variable
2202                                                         print(", "); begin = false;
2203                                                 }
2204                                                 int methodNumId = intDecl.getMethodNumId(method);
2205                                                 print("int struct" + methodNumId + "Size" + i);
2206                                         }
2207                                 }
2208                                 // Check if this is "void"
2209                                 if (retType.equals("void"))
2210                                         println(", IoTRMIObject rmiObj) {");
2211                                 else
2212                                         println(", IoTRMIObject rmiObj) throws IOException {");
2213                                 writeMethodHelperStructJavaSkeleton(intDecl, methParams, methPrmTypes, method, callbackClasses);
2214                                 println("}\n");
2215                         } else {
2216                                 String methodId = intDecl.getMethodId(method);
2217                                 print("public void ___");
2218                                 String helperMethod = methodId;
2219                                 if (uniqueMethodIds.contains(methodId))
2220                                         helperMethod = helperMethod + intDecl.getMethodNumId(method);
2221                                 else
2222                                         uniqueMethodIds.add(methodId);
2223                                 // Check if this is "void"
2224                                 String retType = intDecl.getMethodType(method);
2225                                 if (retType.equals("void"))
2226                                         println(helperMethod + "(IoTRMIObject rmiObj) {");
2227                                 else
2228                                         println(helperMethod + "(IoTRMIObject rmiObj) throws IOException {");
2229                                 // Now, write the helper body of skeleton!
2230                                 writeStdMethodHelperBodyJavaSkeleton(intDecl, methParams, methPrmTypes, method, callbackClasses);
2231                                 println("}\n");
2232                         }
2233                 }
2234                 // Write method helper for structs
2235                 writeMethodHelperStructSetupJavaCallbackSkeleton(methods, intDecl);
2236         }
2237
2238
2239         /**
2240          * HELPER: writeJavaCallbackWaitRequestInvokeMethod() writes the request invoke method of the callback skeleton class
2241          */
2242         private void writeJavaCallbackWaitRequestInvokeMethod(Collection<String> methods, InterfaceDecl intDecl, boolean callbackExist) {
2243
2244                 // Use this set to handle two same methodIds
2245                 Set<String> uniqueMethodIds = new HashSet<String>();
2246                 println("public void invokeMethod(IoTRMIObject rmiObj) throws IOException {");
2247                 // Write variables here if we have callbacks or enums or structs
2248                 writeCountVarStructSkeleton(methods, intDecl);
2249                 // Write variables here if we have callbacks or enums or structs
2250                 println("int methodId = rmiObj.getMethodId();");
2251                 // TODO: code the permission check here!
2252                 println("switch (methodId) {");
2253                 // Print methods and method Ids
2254                 for (String method : methods) {
2255                         String methodId = intDecl.getMethodId(method);
2256                         int methodNumId = intDecl.getMethodNumId(method);
2257                         print("case " + methodNumId + ": ___");
2258                         String helperMethod = methodId;
2259                         if (uniqueMethodIds.contains(methodId))
2260                                 helperMethod = helperMethod + methodNumId;
2261                         else
2262                                 uniqueMethodIds.add(methodId);
2263                         print(helperMethod + "(");
2264                         if (writeInputCountVarStructSkeleton(method, intDecl))
2265                                 println(", rmiObj); break;");
2266                         else
2267                                 println("rmiObj); break;");
2268                 }
2269                 String method = "___initCallBack()";
2270                 // Print case -9999 (callback handler) if callback exists
2271                 if (callbackExist) {
2272                         int methodId = intDecl.getHelperMethodNumId(method);
2273                         println("case " + methodId + ": ___regCB(rmiObj); break;");
2274                 }
2275                 writeMethodCallStructCallbackSkeleton(methods, intDecl);
2276                 println("default: ");
2277                 println("throw new Error(\"Method Id \" + methodId + \" not recognized!\");");
2278                 println("}");
2279                 println("}\n");
2280         }
2281
2282
2283         /**
2284          * generateJavaCallbackSkeletonClass() generate callback skeletons based on the methods list in Java
2285          */
2286         public void generateJavaCallbackSkeletonClass() throws IOException {
2287
2288                 // Create a new directory
2289                 String path = createDirectories(dir, subdir);
2290                 for (String intface : mapIntfacePTH.keySet()) {
2291                         // Open a new file to write into
2292                         String newSkelClass = intface + "_CallbackSkeleton";
2293                         FileWriter fw = new FileWriter(path + "/" + newSkelClass + ".java");
2294                         pw = new PrintWriter(new BufferedWriter(fw));
2295                         // Pass in set of methods and get import classes
2296                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2297                         InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
2298                         List<String> methods = intDecl.getMethods();
2299                         Set<String> importClasses = getImportClasses(methods, intDecl);
2300                         List<String> stdImportClasses = getStandardJavaImportClasses();
2301                         List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
2302                         printImportStatements(allImportClasses);
2303                         // Find out if there are callback objects
2304                         Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
2305                         boolean callbackExist = !callbackClasses.isEmpty();
2306                         // Write class header
2307                         println("");
2308                         println("public class " + newSkelClass  + " implements " + intface + " {\n");
2309                         // Write properties
2310                         writePropertiesJavaCallbackSkeleton(intface, callbackExist);
2311                         // Write constructor
2312                         writeConstructorJavaCallbackSkeleton(newSkelClass, intface, intDecl, methods);
2313                         // Write methods
2314                         writeMethodJavaSkeleton(methods, intDecl, callbackClasses, true);
2315                         // Write method helper
2316                         writeMethodHelperJavaCallbackSkeleton(methods, intDecl, callbackClasses);
2317                         // Write waitRequestInvokeMethod() - main loop
2318                         writeJavaCallbackWaitRequestInvokeMethod(methods, intDecl, callbackExist);
2319                         println("}");
2320                         pw.close();
2321                         System.out.println("IoTCompiler: Generated callback skeleton class " + newSkelClass + ".java...");
2322                 }
2323         }
2324
2325
2326         /**
2327          * HELPER: writeMethodCplusLocalInterface() writes the method of the local interface
2328          */
2329         private void writeMethodCplusLocalInterface(Collection<String> methods, InterfaceDecl intDecl) {
2330
2331                 for (String method : methods) {
2332
2333                         List<String> methParams = intDecl.getMethodParams(method);
2334                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2335                         print("virtual " + checkAndGetCplusType(intDecl.getMethodType(method)) + " " +
2336                                 intDecl.getMethodId(method) + "(");
2337                         for (int i = 0; i < methParams.size(); i++) {
2338                                 // Check for params with driver class types and exchange it 
2339                                 //              with its remote interface
2340                                 String paramType = checkAndGetParamClass(methPrmTypes.get(i));
2341                                 paramType = checkAndGetCplusType(paramType);
2342                                 // Check for arrays - translate into vector in C++
2343                                 String paramComplete = checkAndGetCplusArray(paramType, methParams.get(i));
2344                                 print(paramComplete);
2345                                 // Check if this is the last element (don't print a comma)
2346                                 if (i != methParams.size() - 1) {
2347                                         print(", ");
2348                                 }
2349                         }
2350                         println(") = 0;");
2351                 }
2352         }
2353
2354
2355         /**
2356          * HELPER: writeMethodCplusInterface() writes the method of the interface
2357          */
2358         private void writeMethodCplusInterface(Collection<String> methods, InterfaceDecl intDecl) {
2359
2360                 for (String method : methods) {
2361
2362                         List<String> methParams = intDecl.getMethodParams(method);
2363                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2364                         print("virtual " + checkAndGetCplusType(intDecl.getMethodType(method)) + " " +
2365                                 intDecl.getMethodId(method) + "(");
2366                         for (int i = 0; i < methParams.size(); i++) {
2367                                 // Check for params with driver class types and exchange it 
2368                                 //              with its remote interface
2369                                 String paramType = methPrmTypes.get(i);
2370                                 paramType = checkAndGetCplusType(paramType);
2371                                 // Check for arrays - translate into vector in C++
2372                                 String paramComplete = checkAndGetCplusArray(paramType, methParams.get(i));
2373                                 print(paramComplete);
2374                                 // Check if this is the last element (don't print a comma)
2375                                 if (i != methParams.size() - 1) {
2376                                         print(", ");
2377                                 }
2378                         }
2379                         println(") = 0;");
2380                 }
2381         }
2382
2383
2384         /**
2385          * HELPER: generateEnumCplus() writes the enumeration declaration
2386          */
2387         public void generateEnumCplus() throws IOException {
2388
2389                 // Create a new directory
2390                 createDirectory(dir);
2391                 for (String intface : mapIntfacePTH.keySet()) {
2392                         // Get the right StructDecl
2393                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2394                         EnumDecl enumDecl = (EnumDecl) decHandler.getEnumDecl(intface);
2395                         Set<String> enumTypes = enumDecl.getEnumDeclarations();
2396                         // Iterate over enum declarations
2397                         for (String enType : enumTypes) {
2398                                 // Open a new file to write into
2399                                 FileWriter fw = new FileWriter(dir + "/" + enType + ".hpp");
2400                                 pw = new PrintWriter(new BufferedWriter(fw));
2401                                 // Write file headers
2402                                 println("#ifndef _" + enType.toUpperCase() + "_HPP__");
2403                                 println("#define _" + enType.toUpperCase() + "_HPP__");
2404                                 println("enum " + enType + " {");
2405                                 List<String> enumMembers = enumDecl.getMembers(enType);
2406                                 for (int i = 0; i < enumMembers.size(); i++) {
2407
2408                                         String member = enumMembers.get(i);
2409                                         print(member);
2410                                         // Check if this is the last element (don't print a comma)
2411                                         if (i != enumMembers.size() - 1)
2412                                                 println(",");
2413                                         else
2414                                                 println("");
2415                                 }
2416                                 println("};\n");
2417                                 println("#endif");
2418                                 pw.close();
2419                                 System.out.println("IoTCompiler: Generated enum " + enType + ".hpp...");
2420                         }
2421                 }
2422         }
2423
2424
2425         /**
2426          * HELPER: generateStructCplus() writes the struct declaration
2427          */
2428         public void generateStructCplus() throws IOException {
2429
2430                 // Create a new directory
2431                 createDirectory(dir);
2432                 for (String intface : mapIntfacePTH.keySet()) {
2433                         // Get the right StructDecl
2434                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2435                         StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
2436                         List<String> structTypes = structDecl.getStructTypes();
2437                         // Iterate over enum declarations
2438                         for (String stType : structTypes) {
2439                                 // Open a new file to write into
2440                                 FileWriter fw = new FileWriter(dir + "/" + stType + ".hpp");
2441                                 pw = new PrintWriter(new BufferedWriter(fw));
2442                                 // Write file headers
2443                                 println("#ifndef _" + stType.toUpperCase() + "_HPP__");
2444                                 println("#define _" + stType.toUpperCase() + "_HPP__");
2445                                 println("struct " + stType + " {");
2446                                 List<String> structMemberTypes = structDecl.getMemberTypes(stType);
2447                                 List<String> structMembers = structDecl.getMembers(stType);
2448                                 for (int i = 0; i < structMembers.size(); i++) {
2449
2450                                         String memberType = structMemberTypes.get(i);
2451                                         String member = structMembers.get(i);
2452                                         String structTypeC = checkAndGetCplusType(memberType);
2453                                         String structComplete = checkAndGetCplusArray(structTypeC, member);
2454                                         println(structComplete + ";");
2455                                 }
2456                                 println("};\n");
2457                                 println("#endif");
2458                                 pw.close();
2459                                 System.out.println("IoTCompiler: Generated struct " + stType + ".hpp...");
2460                         }
2461                 }
2462         }
2463
2464
2465         /**
2466          * generateCplusLocalInterfaces() writes the local interfaces and provides type-checking.
2467          * <p>
2468          * It needs to rewrite and exchange USERDEFINED types in input parameters of stub
2469          * and original interfaces, e.g. exchange Camera and CameraWithVideoAndRecording.
2470          * The local interface has to be the input parameter for the stub and the stub 
2471          * interface has to be the input parameter for the local class.
2472          */
2473         public void generateCplusLocalInterfaces() throws IOException {
2474
2475                 // Create a new directory
2476                 createDirectory(dir);
2477                 for (String intface : mapIntfacePTH.keySet()) {
2478                         // Open a new file to write into
2479                         FileWriter fw = new FileWriter(dir + "/" + intface + ".hpp");
2480                         pw = new PrintWriter(new BufferedWriter(fw));
2481                         // Write file headers
2482                         println("#ifndef _" + intface.toUpperCase() + "_HPP__");
2483                         println("#define _" + intface.toUpperCase() + "_HPP__");
2484                         println("#include <iostream>");
2485                         // Pass in set of methods and get include classes
2486                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2487                         InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
2488                         List<String> methods = intDecl.getMethods();
2489                         Set<String> includeClasses = getIncludeClasses(methods, intDecl, intface, true);
2490                         printIncludeStatements(includeClasses); println("");
2491                         println("using namespace std;\n");
2492                         //writeStructCplus(structDecl);
2493                         println("class " + intface); println("{");
2494                         println("public:");
2495                         // Write methods
2496                         writeMethodCplusLocalInterface(methods, intDecl);
2497                         println("};");
2498                         println("#endif");
2499                         pw.close();
2500                         System.out.println("IoTCompiler: Generated local interface " + intface + ".hpp...");
2501                 }
2502         }
2503
2504
2505         /**
2506          * generateCPlusInterfaces() generate stub interfaces based on the methods list in C++
2507          * <p>
2508          * For C++ we use virtual classe as interface
2509          */
2510         public void generateCPlusInterfaces() throws IOException {
2511
2512                 // Create a new directory
2513                 String path = createDirectories(dir, subdir);
2514                 for (String intface : mapIntfacePTH.keySet()) {
2515
2516                         Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
2517                         for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
2518
2519                                 // Open a new file to write into
2520                                 String newIntface = intMeth.getKey();
2521                                 FileWriter fw = new FileWriter(path + "/" + newIntface + ".hpp");
2522                                 pw = new PrintWriter(new BufferedWriter(fw));
2523                                 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2524                                 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
2525                                 // Write file headers
2526                                 println("#ifndef _" + newIntface.toUpperCase() + "_HPP__");
2527                                 println("#define _" + newIntface.toUpperCase() + "_HPP__");
2528                                 println("#include <iostream>");
2529                                 // Pass in set of methods and get import classes
2530                                 Set<String> includeClasses = getIncludeClasses(intMeth.getValue(), intDecl, intface, false);
2531                                 List<String> stdIncludeClasses = getStandardCplusIncludeClasses();
2532                                 List<String> allIncludeClasses = getAllLibClasses(stdIncludeClasses, includeClasses);
2533                                 printIncludeStatements(allIncludeClasses); println("");                 
2534                                 println("using namespace std;\n");
2535                                 println("class " + newIntface);
2536                                 println("{");
2537                                 println("public:");
2538                                 // Write methods
2539                                 writeMethodCplusInterface(intMeth.getValue(), intDecl);
2540                                 println("};");
2541                                 println("#endif");
2542                                 pw.close();
2543                                 System.out.println("IoTCompiler: Generated interface " + newIntface + ".hpp...");
2544                         }
2545                 }
2546         }
2547
2548
2549         /**
2550          * HELPER: writeMethodCplusStub() writes the methods of the stub
2551          */
2552         private void writeMethodCplusStub(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
2553
2554                 for (String method : methods) {
2555
2556                         List<String> methParams = intDecl.getMethodParams(method);
2557                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2558                         print(checkAndGetCplusType(intDecl.getMethodType(method)) + " " +
2559                                 intDecl.getMethodId(method) + "(");
2560                         boolean isCallbackMethod = false;
2561                         String callbackType = null;
2562                         for (int i = 0; i < methParams.size(); i++) {
2563
2564                                 String paramType = methPrmTypes.get(i);
2565                                 // Check if this has callback object
2566                                 if (callbackClasses.contains(paramType)) {
2567                                         isCallbackMethod = true;
2568                                         callbackType = paramType;       
2569                                         // Even if there're 2 callback arguments, we expect them to be of the same interface
2570                                 }
2571                                 String methPrmType = checkAndGetCplusType(methPrmTypes.get(i));
2572                                 String methParamComplete = checkAndGetCplusArray(methPrmType, methParams.get(i));
2573                                 print(methParamComplete);
2574                                 // Check if this is the last element (don't print a comma)
2575                                 if (i != methParams.size() - 1) {
2576                                         print(", ");
2577                                 }
2578                         }
2579                         println(") { ");
2580                         if (isCallbackMethod)
2581                                 writeCallbackMethodBodyCplusStub(intDecl, methParams, methPrmTypes, method, callbackType);
2582                         else
2583                                 writeStdMethodBodyCplusStub(intDecl, methParams, methPrmTypes, method);
2584                         println("}\n");
2585                         // Write the init callback helper method
2586                         if (isCallbackMethod) {
2587                                 writeInitCallbackCplusStub(callbackType, intDecl);
2588                                 writeInitCallbackSendInfoCplusStub(intDecl);
2589                         }
2590                 }
2591         }
2592
2593
2594         /**
2595          * HELPER: writeCallbackMethodBodyCplusStub() writes the callback method of the stub class
2596          */
2597         private void writeCallbackMethodBodyCplusStub(InterfaceDecl intDecl, List<String> methParams,
2598                         List<String> methPrmTypes, String method, String callbackType) {
2599
2600                 // Check if this is single object, array, or list of objects
2601                 boolean isArrayOrList = false;
2602                 String callbackParam = null;
2603                 for (int i = 0; i < methParams.size(); i++) {
2604
2605                         String paramType = methPrmTypes.get(i);
2606                         if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
2607                                 String param = methParams.get(i);
2608                                 if (isArrayOrList(paramType, param)) {  // Generate loop
2609                                         println("for (" + paramType + "* cb : " + getSimpleIdentifier(param) + ") {");
2610                                         println(callbackType + "_CallbackSkeleton* skel = new " + callbackType + "_CallbackSkeleton(cb, objIdCnt++);");
2611                                         isArrayOrList = true;
2612                                         callbackParam = getSimpleIdentifier(param);
2613                                 } else
2614                                         println(callbackType + "_CallbackSkeleton* skel = new " + callbackType + "_CallbackSkeleton(" +
2615                                                 getSimpleIdentifier(param) + ", objIdCnt++);");
2616                                 println("vecCallbackObj.push_back(skel);");
2617                                 if (isArrayOrList(paramType, param))
2618                                         println("}");
2619                         }
2620                 }
2621                 println("int numParam = " + methParams.size() + ";");
2622                 println("int methodId = " + intDecl.getMethodNumId(method) + ";");
2623                 String retType = intDecl.getMethodType(method);
2624                 //String retTypeC = checkAndGetCplusType(retType);
2625                 //println("string retType = \"" + checkAndGetCplusArrayType(getStructType(getEnumType(retTypeC))) + "\";");
2626                 println("string retType = \"" + checkAndGetCplusRetClsType(getStructType(getEnumType(retType))) + "\";");
2627                 // Generate array of parameter types
2628                 print("string paramCls[] = { ");
2629                 for (int i = 0; i < methParams.size(); i++) {
2630                         String paramType = methPrmTypes.get(i);
2631                         if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
2632                                 print("\"int\"");
2633                         } else { // Generate normal classes if it's not a callback object
2634                                 String paramTypeC = checkAndGetCplusArgClsType(methPrmTypes.get(i), methParams.get(i));
2635                                 print("\"" + paramTypeC + "\"");
2636                         }
2637                         if (i != methParams.size() - 1) // Check if this is the last element
2638                                 print(", ");
2639                 }
2640                 println(" };");
2641                 print("int ___paramCB = ");
2642                 if (isArrayOrList)
2643                         println(callbackParam + ".size();");
2644                 else
2645                         println("1;");
2646                 // Generate array of parameter objects
2647                 print("void* paramObj[] = { ");
2648                 for (int i = 0; i < methParams.size(); i++) {
2649                         String paramType = methPrmTypes.get(i);
2650                         if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
2651                                 print("&___paramCB");
2652                         } else
2653                                 print(getSimpleIdentifier(methParams.get(i)));
2654                         if (i != methParams.size() - 1)
2655                                 print(", ");
2656                 }
2657                 println(" };");
2658                 // Check if this is "void"
2659                 if (retType.equals("void")) {
2660                         println("void* retObj = NULL;");
2661                         println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
2662                 } else { // We do have a return value
2663                         if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
2664                                 println(checkAndGetCplusType(retType) + " retVal;");
2665                         else
2666                                 println(checkAndGetCplusType(retType) + " retVal = " + generateCplusInitializer(retType) + ";");
2667                         println("void* retObj = &retVal;");
2668                         println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
2669                         println("return retVal;");
2670                 }
2671         }
2672
2673
2674         /**
2675          * HELPER: checkAndWriteEnumTypeCplusStub() writes the enum type (convert from enum to int)
2676          */
2677         private void checkAndWriteEnumTypeCplusStub(List<String> methParams, List<String> methPrmTypes) {
2678
2679                 // Iterate and find enum declarations
2680                 for (int i = 0; i < methParams.size(); i++) {
2681                         String paramType = methPrmTypes.get(i);
2682                         String param = methParams.get(i);
2683                         if (isEnumClass(getGenericType(paramType))) {
2684                         // Check if this is enum type
2685                                 if (isArrayOrList(paramType, param)) {  // An array or vector
2686                                         println("int len" + i + " = " + getSimpleIdentifier(param) + ".size();");
2687                                         println("vector<int> paramEnum" + i + "(len" + i + ");");
2688                                         println("for (int i = 0; i < len" + i + "; i++) {");
2689                                         println("paramEnum" + i + "[i] = (int) " + getSimpleIdentifier(param) + "[i];");
2690                                         println("}");
2691                                 } else {        // Just one element
2692                                         println("vector<int> paramEnum" + i + "(1);");
2693                                         println("paramEnum" + i + "[0] = (int) " + param + ";");
2694                                 }
2695                         }
2696                 }
2697         }
2698
2699
2700         /**
2701          * HELPER: checkAndWriteEnumRetTypeCplusStub() writes the enum return type (convert from enum to int)
2702          */
2703         private void checkAndWriteEnumRetTypeCplusStub(String retType) {
2704
2705                 // Strips off array "[]" for return type
2706                 String pureType = getSimpleArrayType(getGenericType(retType));
2707                 // Take the inner type of generic
2708                 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
2709                         pureType = getGenericType(retType);
2710                 if (isEnumClass(pureType)) {
2711                 // Check if this is enum type
2712                         println("vector<int> retEnumInt;");
2713                         println("void* retObj = &retEnumInt;");
2714                         println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
2715                         if (isArrayOrList(retType, retType)) {  // An array or vector
2716                                 println("int retLen = retEnumInt.size();");
2717                                 println("vector<" + pureType + "> retVal(retLen);");
2718                                 println("for (int i = 0; i < retLen; i++) {");
2719                                 println("retVal[i] = (" + pureType + ") retEnumInt[i];");
2720                                 println("}");
2721                         } else {        // Just one element
2722                                 println(pureType + " retVal = (" + pureType + ") retEnumInt[0];");
2723                         }
2724                         println("return retVal;");
2725                 }
2726         }
2727
2728
2729         /**
2730          * HELPER: checkAndWriteStructSetupCplusStub() writes the struct type setup
2731          */
2732         private void checkAndWriteStructSetupCplusStub(List<String> methParams, List<String> methPrmTypes, 
2733                         InterfaceDecl intDecl, String method) {
2734                 
2735                 // Iterate and find struct declarations
2736                 for (int i = 0; i < methParams.size(); i++) {
2737                         String paramType = methPrmTypes.get(i);
2738                         String param = methParams.get(i);
2739                         String simpleType = getSimpleType(paramType);
2740                         if (isStructClass(simpleType)) {
2741                         // Check if this is enum type
2742                                 println("int numParam" + i + " = 1;");
2743                                 int methodNumId = intDecl.getMethodNumId(method);
2744                                 String helperMethod = methodNumId + "struct" + i;
2745                                 println("int methodIdStruct" + i + " = " + intDecl.getHelperMethodNumId(helperMethod) + ";");
2746                                 println("string retTypeStruct" + i + " = \"void\";");
2747                                 println("string paramClsStruct" + i + "[] = { \"int\" };");
2748                                 print("int structLen" + i + " = ");
2749                                 if (isArrayOrList(param, paramType)) {  // An array
2750                                         println(getSimpleArrayType(param) + ".size();");
2751                                 } else {        // Just one element
2752                                         println("1;");
2753                                 }
2754                                 println("void* paramObjStruct" + i + "[] = { &structLen" + i + " };");
2755                                 println("void* retStructLen" + i + " = NULL;");
2756                                 println("rmiCall->remoteCall(objectId, methodIdStruct" + i + 
2757                                                 ", retTypeStruct" + i + ", paramClsStruct" + i + ", paramObjStruct" + i + 
2758                                                 ", numParam" + i + ", retStructLen" + i + ");\n");
2759                         }
2760                 }
2761         }
2762
2763
2764         /**
2765          * HELPER: writeLengthStructParamClassCplusStub() writes lengths of params
2766          */
2767         private void writeLengthStructParamClassCplusStub(List<String> methParams, List<String> methPrmTypes) {
2768
2769                 // Iterate and find struct declarations - count number of params
2770                 for (int i = 0; i < methParams.size(); i++) {
2771                         String paramType = methPrmTypes.get(i);
2772                         String param = methParams.get(i);
2773                         String simpleType = getGenericType(paramType);
2774                         if (isStructClass(simpleType)) {
2775                                 int members = getNumOfMembers(simpleType);
2776                                 if (isArrayOrList(param, paramType)) {                  // An array
2777                                         String structLen = param + ".size()";
2778                                         print(members + "*" + structLen);
2779                                 } else
2780                                         print(Integer.toString(members));
2781                         } else
2782                                 print("1");
2783                         if (i != methParams.size() - 1) {
2784                                 print("+");
2785                         }
2786                 }
2787         }
2788
2789
2790         /**
2791          * HELPER: writeStructMembersCplusStub() writes member parameters of struct
2792          */
2793         private void writeStructMembersCplusStub(String simpleType, String paramType, String param) {
2794
2795                 // Get the struct declaration for this struct and generate initialization code
2796                 StructDecl structDecl = getStructDecl(simpleType);
2797                 List<String> memTypes = structDecl.getMemberTypes(simpleType);
2798                 List<String> members = structDecl.getMembers(simpleType);
2799                 if (isArrayOrList(param, paramType)) {  // An array or list
2800                         println("for(int i = 0; i < " + param + ".size(); i++) {");
2801                 }
2802                 if (isArrayOrList(param, paramType)) {  // An array or list
2803                         for (int i = 0; i < members.size(); i++) {
2804                                 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
2805                                 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
2806                                 println("paramCls[pos] = \"" + getSimpleType(getEnumType(prmType)) + "\";");
2807                                 print("paramObj[pos++] = &" + param + "[i].");
2808                                 print(getSimpleIdentifier(members.get(i)));
2809                                 println(";");
2810                         }
2811                         println("}");
2812                 } else {        // Just one struct element
2813                         for (int i = 0; i < members.size(); i++) {
2814                                 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
2815                                 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
2816                                 println("paramCls[pos] = \"" + getSimpleType(getEnumType(prmType)) + "\";");
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 = checkAndGetCplusType(methPrmTypes.get(i));
2845                                 String prmType = checkAndGetCplusArrayType(prmTypeC, methParams.get(i));
2846                                 println("paramCls[pos] = \"" + getSimpleType(getEnumType(prmType)) + "\";");
2847                                 print("paramObj[pos++] = &");
2848                                 print(getEnumParam(methPrmTypes.get(i), getSimpleIdentifier(methParams.get(i)), i));
2849                                 println(";");
2850                         }
2851                 }
2852                 
2853         }
2854
2855
2856         /**
2857          * HELPER: writeStructRetMembersCplusStub() writes member parameters of struct for return statement
2858          */
2859         private void writeStructRetMembersCplusStub(String simpleType, String retType) {
2860
2861                 // Get the struct declaration for this struct and generate initialization code
2862                 StructDecl structDecl = getStructDecl(simpleType);
2863                 List<String> memTypes = structDecl.getMemberTypes(simpleType);
2864                 List<String> members = structDecl.getMembers(simpleType);
2865                 if (isArrayOrList(retType, retType)) {  // An array or list
2866                         println("for(int i = 0; i < retLen; i++) {");
2867                 }
2868                 if (isArrayOrList(retType, retType)) {  // An array or list
2869                         for (int i = 0; i < members.size(); i++) {
2870                                 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
2871                                 print("structRet[i]." + getSimpleIdentifier(members.get(i)));
2872                                 println(" = retParam" + i + "[i];");
2873                         }
2874                         println("}");
2875                 } else {        // Just one struct element
2876                         for (int i = 0; i < members.size(); i++) {
2877                                 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
2878                                 print("structRet." + getSimpleIdentifier(members.get(i)));
2879                                 println(" = retParam" + i + ";");
2880                         }
2881                 }
2882                 println("return structRet;");
2883         }
2884
2885
2886         /**
2887          * HELPER: writeStructReturnCplusStub() writes member parameters of struct for return statement
2888          */
2889         private void writeStructReturnCplusStub(String simpleType, String retType) {
2890
2891                 // Minimum retLen is 1 if this is a single struct object
2892                 println("int retLen = 0;");
2893                 println("void* retLenObj = { &retLen };");
2894                 // Handle the returned struct!!!
2895                 println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retLenObj);");
2896                 int numMem = getNumOfMembers(simpleType);
2897                 println("int numRet = " + numMem + "*retLen;");
2898                 println("string retCls[numRet];");
2899                 println("void* retObj[numRet];");
2900                 StructDecl structDecl = getStructDecl(simpleType);
2901                 List<String> memTypes = structDecl.getMemberTypes(simpleType);
2902                 List<String> members = structDecl.getMembers(simpleType);
2903                 // Set up variables
2904                 if (isArrayOrList(retType, retType)) {  // An array or list
2905                         for (int i = 0; i < members.size(); i++) {
2906                                 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
2907                                 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
2908                                 println(getSimpleType(getEnumType(prmType)) + " retParam" + i + "[retLen];");
2909                         }
2910                 } else {        // Just one struct element
2911                         for (int i = 0; i < members.size(); i++) {
2912                                 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
2913                                 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
2914                                 println(getSimpleType(getEnumType(prmType)) + " retParam" + i + ";");
2915                         }
2916                 }
2917                 println("int retPos = 0;");
2918                 // Get the struct declaration for this struct and generate initialization code
2919                 if (isArrayOrList(retType, retType)) {  // An array or list
2920                         println("for(int i = 0; i < retLen; i++) {");
2921                         for (int i = 0; i < members.size(); i++) {
2922                                 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
2923                                 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
2924                                 println("retCls[retPos] = \"" + getSimpleType(getEnumType(prmType)) + "\";");
2925                                 println("retObj[retPos++] = &retParam" + i + "[i];");
2926                         }
2927                         println("}");
2928                 } else {        // Just one struct element
2929                         for (int i = 0; i < members.size(); i++) {
2930                                 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
2931                                 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
2932                                 println("retCls[retPos] = \"" + getSimpleType(getEnumType(prmType)) + "\";");
2933                                 println("retObj[retPos++] = &retParam" + i + ";");
2934                         }
2935                 }
2936                 println("rmiCall->getStructObjects(retCls, numRet, retObj);");
2937                 if (isArrayOrList(retType, retType)) {  // An array or list
2938                         println("vector<" + simpleType + "> structRet(retLen);");
2939                 } else
2940                         println(simpleType + " structRet;");
2941                 writeStructRetMembersCplusStub(simpleType, retType);
2942         }
2943
2944
2945         /**
2946          * HELPER: writeStdMethodBodyCplusStub() writes the standard method body in the stub class
2947          */
2948         private void writeStdMethodBodyCplusStub(InterfaceDecl intDecl, List<String> methParams,
2949                         List<String> methPrmTypes, String method) {
2950
2951                 checkAndWriteStructSetupCplusStub(methParams, methPrmTypes, intDecl, method);
2952                 println("int methodId = " + intDecl.getMethodNumId(method) + ";");
2953                 String retType = intDecl.getMethodType(method);
2954                 println("string retType = \"" + checkAndGetCplusRetClsType(getStructType(getEnumType(retType))) + "\";");
2955                 // Generate array of parameter types
2956                 if (isStructPresent(methParams, methPrmTypes)) {
2957                         writeStructParamClassCplusStub(methParams, methPrmTypes);
2958                 } else {
2959                         println("int numParam = " + methParams.size() + ";");
2960                         print("string paramCls[] = { ");
2961                         for (int i = 0; i < methParams.size(); i++) {
2962                                 String paramTypeC = checkAndGetCplusArgClsType(methPrmTypes.get(i), methParams.get(i));
2963                                 print("\"" + paramTypeC + "\"");
2964                                 // Check if this is the last element (don't print a comma)
2965                                 if (i != methParams.size() - 1) {
2966                                         print(", ");
2967                                 }
2968                         }
2969                         println(" };");
2970                         checkAndWriteEnumTypeCplusStub(methParams, methPrmTypes);
2971                         // Generate array of parameter objects
2972                         print("void* paramObj[] = { ");
2973                         for (int i = 0; i < methParams.size(); i++) {
2974                                 print("&" + getEnumParam(methPrmTypes.get(i), getSimpleIdentifier(methParams.get(i)), i));
2975                                 // Check if this is the last element (don't print a comma)
2976                                 if (i != methParams.size() - 1) {
2977                                         print(", ");
2978                                 }
2979                         }
2980                         println(" };");
2981                 }
2982                 // Check if this is "void"
2983                 if (retType.equals("void")) {
2984                         println("void* retObj = NULL;");
2985                         println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
2986                 } else { // We do have a return value
2987                         // Generate array of parameter types
2988                         if (isStructClass(getGenericType(getSimpleArrayType(retType)))) {
2989                                 writeStructReturnCplusStub(getGenericType(getSimpleArrayType(retType)), retType);
2990                         } else {
2991                         // Check if the return value NONPRIMITIVES
2992                                 if (isEnumClass(getSimpleArrayType(getGenericType(retType)))) {
2993                                         checkAndWriteEnumRetTypeCplusStub(retType);
2994                                 } else {
2995                                         //if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
2996                                         if (isArrayOrList(retType,retType))
2997                                                 println(checkAndGetCplusType(retType) + " retVal;");
2998                                         else {
2999                                                 println(checkAndGetCplusType(retType) + " retVal = " + generateCplusInitializer(retType) + ";");
3000                                         }
3001                                         println("void* retObj = &retVal;");
3002                                         println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
3003                                         println("return retVal;");
3004                                 }
3005                         }
3006                 }
3007         }
3008
3009
3010         /**
3011          * HELPER: writePropertiesCplusStub() writes the properties of the stub class
3012          */
3013         private void writePropertiesCplusPermission(String intface) {
3014
3015                 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3016                 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3017                         String newIntface = intMeth.getKey();
3018                         int newObjectId = getNewIntfaceObjectId(newIntface);
3019                         println("const static int object" + newObjectId + "Id = " + newObjectId + ";\t//" + newIntface);
3020                         println("static set<int> set" + newObjectId + "Allowed;");
3021                 }
3022         }       
3023
3024         /**
3025          * HELPER: writePropertiesCplusStub() writes the properties of the stub class
3026          */
3027         private void writePropertiesCplusStub(String intface, String newIntface, boolean callbackExist, Set<String> callbackClasses) {
3028
3029                 println("IoTRMICall *rmiCall;");
3030                 //println("IoTRMIObject\t\t\t*rmiObj;");
3031                 println("string address;");
3032                 println("vector<int> ports;\n");
3033                 // Get the object Id
3034                 Integer objId = mapIntfaceObjId.get(intface);
3035                 println("const static int objectId = " + objId + ";");
3036                 mapNewIntfaceObjId.put(newIntface, objId);
3037                 mapIntfaceObjId.put(intface, objId++);
3038                 if (callbackExist) {
3039                 // We assume that each class only has one callback interface for now
3040                         Iterator it = callbackClasses.iterator();
3041                         String callbackType = (String) it.next();
3042                         println("// Callback properties");
3043                         println("IoTRMIObject *rmiObj;");
3044                         println("vector<" + callbackType + "*> vecCallbackObj;");
3045                         println("static int objIdCnt;");
3046                         // Generate permission stuff for callback stubs
3047                         writePropertiesCplusPermission(callbackType);
3048                 }
3049                 println("\n");
3050         }
3051
3052
3053         /**
3054          * HELPER: writeConstructorCplusStub() writes the constructor of the stub class
3055          */
3056         private void writeConstructorCplusStub(String newStubClass, boolean callbackExist, Set<String> callbackClasses) {
3057
3058                 println(newStubClass + 
3059                         "(int _port, const char* _address, int _rev, bool* _bResult, vector<int> _ports) {");
3060                 println("address = _address;");
3061                 println("ports = _ports;");
3062                 println("rmiCall = new IoTRMICall(_port, _address, _rev, _bResult);");
3063                 if (callbackExist) {
3064                         Iterator it = callbackClasses.iterator();
3065                         String callbackType = (String) it.next();
3066                         println("thread th1 (&" + newStubClass + "::___initCallBack, this);");
3067                         println("th1.detach();");
3068                         println("___regCB();");
3069                 }
3070                 println("}\n");
3071         }
3072
3073
3074         /**
3075          * HELPER: writeDeconstructorCplusStub() writes the deconstructor of the stub class
3076          */
3077         private void writeDeconstructorCplusStub(String newStubClass, boolean callbackExist, Set<String> callbackClasses) {
3078
3079                 println("~" + newStubClass + "() {");
3080                 println("if (rmiCall != NULL) {");
3081                 println("delete rmiCall;");
3082                 println("rmiCall = NULL;");
3083                 println("}");
3084                 if (callbackExist) {
3085                 // We assume that each class only has one callback interface for now
3086                         println("if (rmiObj != NULL) {");
3087                         println("delete rmiObj;");
3088                         println("rmiObj = NULL;");
3089                         println("}");
3090                         Iterator it = callbackClasses.iterator();
3091                         String callbackType = (String) it.next();
3092                         println("for(" + callbackType + "* cb : vecCallbackObj) {");
3093                         println("delete cb;");
3094                         println("cb = NULL;");
3095                         println("}");
3096                 }
3097                 println("}");
3098                 println("");
3099         }
3100
3101
3102         /**
3103          * HELPER: writeCplusMethodCallbackPermission() writes permission checks in stub for callbacks
3104          */
3105         private void writeCplusMethodCallbackPermission(String intface) {
3106
3107                 println("int methodId = IoTRMIObject::getMethodId(method);");
3108                 // Get all the different stubs
3109                 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3110                 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3111                         String newIntface = intMeth.getKey();
3112                         int newObjectId = getNewIntfaceObjectId(newIntface);
3113                         println("if (set" + newObjectId + "Allowed.find(methodId) == set" + newObjectId + "Allowed.end()) {");
3114                         println("cerr << \"Callback object for " + intface + " is not allowed to access method: \" << methodId;");
3115                         println("exit(-1);");
3116                         println("}");
3117                 }
3118         }
3119
3120
3121         /**
3122          * HELPER: writeInitCallbackCplusStub() writes the initialization of callback
3123          */
3124         private void writeInitCallbackCplusStub(String intface, InterfaceDecl intDecl) {
3125
3126                 println("void ___initCallBack() {");
3127                 println("bool bResult = false;");
3128                 println("rmiObj = new IoTRMIObject(ports[0], &bResult);");
3129                 println("while (true) {");
3130                 println("char* method = rmiObj->getMethodBytes();");
3131                 writeCplusMethodCallbackPermission(intface);
3132                 println("int objId = IoTRMIObject::getObjectId(method);");
3133                 println("if (objId < vecCallbackObj.size()) {   // Check if still within range");
3134                 println(intface + "_CallbackSkeleton* skel = dynamic_cast<" + intface + 
3135                         "_CallbackSkeleton*> (vecCallbackObj.at(objId));");
3136                 println("skel->invokeMethod(rmiObj);");
3137                 print("}");
3138                 println(" else {");
3139                 println("cerr << \"Illegal object Id: \" << to_string(objId);");
3140                 // TODO: perhaps need to change this into "throw" to make it cleaner (allow stack unfolding)
3141                 println("exit(-1);");
3142                 println("}");
3143                 println("}");
3144                 println("}\n");
3145         }
3146
3147
3148         /**
3149          * HELPER: writeCplusInitCallbackPermission() writes the permission for callback
3150          */
3151         private void writeCplusInitCallbackPermission(String intface, InterfaceDecl intDecl, boolean callbackExist) {
3152
3153                 if (callbackExist) {
3154                         String method = "___initCallBack()";
3155                         int methodNumId = intDecl.getHelperMethodNumId(method);
3156                         Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3157                         for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3158                                 String newIntface = intMeth.getKey();
3159                                 int newObjectId = getNewIntfaceObjectId(newIntface);
3160                                 println("set" + newObjectId + "Allowed.insert(" + methodNumId + ");");
3161                         }
3162                 }
3163         }
3164
3165
3166         /**
3167          * HELPER: writeInitCallbackSendInfoCplusStub() writes the initialization (send info part) of callback
3168          */
3169         private void writeInitCallbackSendInfoCplusStub(InterfaceDecl intDecl) {
3170
3171                 // Generate info sending part
3172                 println("void ___regCB() {");
3173                 println("int numParam = 3;");
3174                 String method = "___initCallBack()";
3175                 int methodNumId = intDecl.getHelperMethodNumId(method);
3176                 println("int methodId = " + methodNumId + ";");
3177                 //writeCplusCallbackPermission(intface, methodNumId);
3178                 println("string retType = \"void\";");
3179                 println("string paramCls[] = { \"int\", \"string\", \"int\" };");
3180                 println("int rev = 0;");
3181                 println("void* paramObj[] = { &ports[0], &address, &rev };");
3182                 println("void* retObj = NULL;");
3183                 println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
3184                 println("}\n");
3185         }
3186
3187
3188         /**
3189          * generateCPlusStubClasses() generate stubs based on the methods list in C++
3190          */
3191         public void generateCPlusStubClasses() throws IOException {
3192
3193                 // Create a new directory
3194                 String path = createDirectories(dir, subdir);
3195                 for (String intface : mapIntfacePTH.keySet()) {
3196
3197                         Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3198                         for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3199                                 // Open a new file to write into
3200                                 String newIntface = intMeth.getKey();
3201                                 String newStubClass = newIntface + "_Stub";
3202                                 FileWriter fw = new FileWriter(path + "/" + newStubClass + ".hpp");
3203                                 pw = new PrintWriter(new BufferedWriter(fw));
3204                                 // Write file headers
3205                                 println("#ifndef _" + newStubClass.toUpperCase() + "_HPP__");
3206                                 println("#define _" + newStubClass.toUpperCase() + "_HPP__");
3207                                 println("#include <iostream>");
3208                                 // Find out if there are callback objects
3209                                 Set<String> methods = intMeth.getValue();
3210                                 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
3211                                 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
3212                                 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
3213                                 boolean callbackExist = !callbackClasses.isEmpty();
3214                                 if (callbackExist)      // Need thread library if this has callback
3215                                         println("#include <thread>");
3216                                 println("#include \"" + newIntface + ".hpp\""); println("");            
3217                                 println("using namespace std;"); println("");
3218                                 println("class " + newStubClass + " : public " + newIntface); println("{");
3219                                 println("private:\n");
3220                                 writePropertiesCplusStub(intface, newIntface, callbackExist, callbackClasses);
3221                                 println("public:\n");
3222                                 // Add default constructor and destructor
3223                                 println(newStubClass + "() { }"); println("");
3224                                 writeConstructorCplusStub(newStubClass, callbackExist, callbackClasses);
3225                                 writeDeconstructorCplusStub(newStubClass, callbackExist, callbackClasses);
3226                                 // Write methods
3227                                 writeMethodCplusStub(methods, intDecl, callbackClasses);
3228                                 print("}"); println(";");
3229                                 if (callbackExist)
3230                                         writePermissionInitializationCplus(intface, newStubClass, intDecl);
3231                                 writeObjectIdCountInitializationCplus(newStubClass, callbackExist);
3232                                 println("#endif");
3233                                 pw.close();
3234                                 System.out.println("IoTCompiler: Generated stub class " + newStubClass + ".hpp...");
3235                         }
3236                 }
3237         }
3238
3239
3240         /**
3241          * HELPER: writePropertiesCplusCallbackStub() writes the properties of the stub class
3242          */
3243         private void writePropertiesCplusCallbackStub(String intface, String newIntface, boolean callbackExist, Set<String> callbackClasses) {
3244
3245                 println("IoTRMICall *rmiCall;");
3246                 // Get the object Id
3247                 println("int objectId;");
3248                 if (callbackExist) {
3249                 // We assume that each class only has one callback interface for now
3250                         Iterator it = callbackClasses.iterator();
3251                         String callbackType = (String) it.next();
3252                         println("// Callback properties");
3253                         println("IoTRMIObject *rmiObj;");
3254                         println("vector<" + callbackType + "*> vecCallbackObj;");
3255                         println("static int objIdCnt;");
3256                         // TODO: Need to initialize address and ports if we want to have callback-in-callback
3257                         println("string address;");
3258                         println("vector<int> ports;\n");
3259                         writePropertiesCplusPermission(callbackType);
3260                 }
3261                 println("\n");
3262         }
3263
3264
3265         /**
3266          * HELPER: writeConstructorCplusCallbackStub() writes the constructor of the stub class
3267          */
3268         private void writeConstructorCplusCallbackStub(String newStubClass, boolean callbackExist, Set<String> callbackClasses) {
3269
3270                 println(newStubClass + "(IoTRMICall* _rmiCall, int _objectId) {");
3271                 println("objectId = _objectId;");
3272                 println("rmiCall = _rmiCall;");
3273                 if (callbackExist) {
3274                         Iterator it = callbackClasses.iterator();
3275                         String callbackType = (String) it.next();
3276                         println("thread th1 (&" + newStubClass + "::___initCallBack, this);");
3277                         println("th1.detach();");
3278                         println("___regCB();");
3279                 }
3280                 println("}\n");
3281         }
3282
3283
3284         /**
3285          * generateCPlusCallbackStubClasses() generate callback stubs based on the methods list in C++
3286          */
3287         public void generateCPlusCallbackStubClasses() throws IOException {
3288
3289                 // Create a new directory
3290                 String path = createDirectories(dir, subdir);
3291                 for (String intface : mapIntfacePTH.keySet()) {
3292
3293                         Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3294                         for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3295                                 // Open a new file to write into
3296                                 String newIntface = intMeth.getKey();
3297                                 String newStubClass = newIntface + "_CallbackStub";
3298                                 FileWriter fw = new FileWriter(path + "/" + newStubClass + ".hpp");
3299                                 pw = new PrintWriter(new BufferedWriter(fw));
3300                                 // Find out if there are callback objects
3301                                 Set<String> methods = intMeth.getValue();
3302                                 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
3303                                 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
3304                                 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
3305                                 boolean callbackExist = !callbackClasses.isEmpty();
3306                                 // Write file headers
3307                                 println("#ifndef _" + newStubClass.toUpperCase() + "_HPP__");
3308                                 println("#define _" + newStubClass.toUpperCase() + "_HPP__");
3309                                 println("#include <iostream>");
3310                                 if (callbackExist)
3311                                         println("#include <thread>");
3312                                 println("#include \"" + newIntface + ".hpp\""); println("");            
3313                                 println("using namespace std;"); println("");
3314                                 println("class " + newStubClass + " : public " + newIntface); println("{");
3315                                 println("private:\n");
3316                                 writePropertiesCplusCallbackStub(intface, newIntface, callbackExist, callbackClasses);
3317                                 println("public:\n");
3318                                 // Add default constructor and destructor
3319                                 println(newStubClass + "() { }"); println("");
3320                                 writeConstructorCplusCallbackStub(newStubClass, callbackExist, callbackClasses);
3321                                 writeDeconstructorCplusStub(newStubClass, callbackExist, callbackClasses);
3322                                 // Write methods
3323                                 writeMethodCplusStub(methods, intDecl, callbackClasses);
3324                                 println("};");
3325                                 if (callbackExist)
3326                                         writePermissionInitializationCplus(intface, newStubClass, intDecl);
3327                                 writeObjectIdCountInitializationCplus(newStubClass, callbackExist);
3328                                 println("#endif");
3329                                 pw.close();
3330                                 System.out.println("IoTCompiler: Generated callback stub class " + newIntface + ".hpp...");
3331                         }
3332                 }
3333         }
3334
3335
3336         /**
3337          * HELPER: writePropertiesCplusSkeleton() writes the properties of the skeleton class
3338          */
3339         private void writePropertiesCplusSkeleton(String intface, boolean callbackExist, Set<String> callbackClasses) {
3340
3341                 println(intface + " *mainObj;");
3342                 // Callback
3343                 if (callbackExist) {
3344                         Iterator it = callbackClasses.iterator();
3345                         String callbackType = (String) it.next();
3346                         String exchangeType = checkAndGetParamClass(callbackType);
3347                         println("// Callback properties");
3348                         println("static int objIdCnt;");
3349                         println("vector<" + exchangeType + "*> vecCallbackObj;");
3350                         println("IoTRMICall *rmiCall;");
3351                 }
3352                 println("IoTRMIObject *rmiObj;\n");
3353                 // Keep track of object Ids of all stubs registered to this interface
3354                 writePropertiesCplusPermission(intface);
3355                 println("\n");
3356         }
3357
3358
3359         /**
3360          * HELPER: writeObjectIdCountInitializationCplus() writes the initialization of objIdCnt variable
3361          */
3362         private void writeObjectIdCountInitializationCplus(String newSkelClass, boolean callbackExist) {
3363
3364                 if (callbackExist)
3365                         println("int " + newSkelClass + "::objIdCnt = 0;");
3366         }
3367
3368
3369         /**
3370          * HELPER: writePermissionInitializationCplus() writes the initialization of permission set
3371          */
3372         private void writePermissionInitializationCplus(String intface, String newSkelClass, InterfaceDecl intDecl) {
3373
3374                 // Keep track of object Ids of all stubs registered to this interface
3375                 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3376                 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3377                         String newIntface = intMeth.getKey();
3378                         int newObjectId = getNewIntfaceObjectId(newIntface);
3379                         print("set<int> " + newSkelClass + "::set" + newObjectId + "Allowed {");
3380                         Set<String> methodIds = intMeth.getValue();
3381                         int i = 0;
3382                         for (String methodId : methodIds) {
3383                                 int methodNumId = intDecl.getMethodNumId(methodId);
3384                                 print(Integer.toString(methodNumId));
3385                                 // Check if this is the last element (don't print a comma)
3386                                 if (i != methodIds.size() - 1) {
3387                                         print(", ");
3388                                 }
3389                                 i++;
3390                         }
3391                         println(" };");
3392                 }       
3393         }
3394
3395
3396         /**
3397          * HELPER: writeStructPermissionCplusSkeleton() writes permission for struct helper
3398          */
3399         private void writeStructPermissionCplusSkeleton(Collection<String> methods, InterfaceDecl intDecl, String intface) {
3400
3401                 // Use this set to handle two same methodIds
3402                 for (String method : methods) {
3403                         List<String> methParams = intDecl.getMethodParams(method);
3404                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
3405                         // Check for params with structs
3406                         for (int i = 0; i < methParams.size(); i++) {
3407                                 String paramType = methPrmTypes.get(i);
3408                                 String param = methParams.get(i);
3409                                 String simpleType = getSimpleType(paramType);
3410                                 if (isStructClass(simpleType)) {
3411                                         int methodNumId = intDecl.getMethodNumId(method);
3412                                         // Iterate over interfaces to give permissions to
3413                                         Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3414                                         for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3415                                                 String newIntface = intMeth.getKey();
3416                                                 int newObjectId = getNewIntfaceObjectId(newIntface);
3417                                                 println("set" + newObjectId + "Allowed.insert(" + methodNumId + ");");
3418                                         }
3419                                 }
3420                         }
3421                 }
3422         }
3423
3424
3425         /**
3426          * HELPER: writeConstructorCplusSkeleton() writes the constructor of the skeleton class
3427          */
3428         private void writeConstructorCplusSkeleton(String newSkelClass, String intface, boolean callbackExist, InterfaceDecl intDecl, Collection<String> methods) {
3429
3430                 println(newSkelClass + "(" + intface + " *_mainObj, int _port) {");
3431                 println("bool _bResult = false;");
3432                 println("mainObj = _mainObj;");
3433                 println("rmiObj = new IoTRMIObject(_port, &_bResult);");
3434                 writeCplusInitCallbackPermission(intface, intDecl, callbackExist);
3435                 writeStructPermissionCplusSkeleton(methods, intDecl, intface);
3436                 println("___waitRequestInvokeMethod();");
3437                 println("}\n");
3438         }
3439
3440
3441         /**
3442          * HELPER: writeDeconstructorCplusSkeleton() writes the deconstructor of the skeleton class
3443          */
3444         private void writeDeconstructorCplusSkeleton(String newSkelClass, boolean callbackExist, Set<String> callbackClasses) {
3445
3446                 println("~" + newSkelClass + "() {");
3447                 println("if (rmiObj != NULL) {");
3448                 println("delete rmiObj;");
3449                 println("rmiObj = NULL;");
3450                 println("}");
3451                 if (callbackExist) {
3452                 // We assume that each class only has one callback interface for now
3453                         println("if (rmiCall != NULL) {");
3454                         println("delete rmiCall;");
3455                         println("rmiCall = NULL;");
3456                         println("}");
3457                         Iterator it = callbackClasses.iterator();
3458                         String callbackType = (String) it.next();
3459                         String exchangeType = checkAndGetParamClass(callbackType);
3460                         println("for(" + exchangeType + "* cb : vecCallbackObj) {");
3461                         println("delete cb;");
3462                         println("cb = NULL;");
3463                         println("}");
3464                 }
3465                 println("}");
3466                 println("");
3467         }
3468
3469
3470         /**
3471          * HELPER: writeStdMethodBodyCplusSkeleton() writes the standard method body in the skeleton class
3472          */
3473         private void writeStdMethodBodyCplusSkeleton(List<String> methParams, String methodId, String methodType) {
3474
3475                 if (methodType.equals("void"))
3476                         print("mainObj->" + methodId + "(");
3477                 else
3478                         print("return mainObj->" + methodId + "(");
3479                 for (int i = 0; i < methParams.size(); i++) {
3480
3481                         print(getSimpleIdentifier(methParams.get(i)));
3482                         // Check if this is the last element (don't print a comma)
3483                         if (i != methParams.size() - 1) {
3484                                 print(", ");
3485                         }
3486                 }
3487                 println(");");
3488         }
3489
3490
3491         /**
3492          * HELPER: writeInitCallbackCplusSkeleton() writes the init callback method for skeleton class
3493          */
3494         private void writeInitCallbackCplusSkeleton(boolean callbackSkeleton) {
3495
3496                 // This is a callback skeleton generation
3497                 if (callbackSkeleton)
3498                         println("void ___regCB(IoTRMIObject* rmiObj) {");
3499                 else
3500                         println("void ___regCB() {");
3501                 println("int numParam = 3;");
3502                 println("int param1 = 0;");
3503                 println("string param2 = \"\";");
3504                 println("int param3 = 0;");
3505                 println("string paramCls[] = { \"int\", \"string\", \"int\" };");
3506                 println("void* paramObj[] = { &param1, &param2, &param3 };");
3507                 println("rmiObj->getMethodParams(paramCls, numParam, paramObj);");
3508                 println("bool bResult = false;");
3509                 println("rmiCall = new IoTRMICall(param1, param2.c_str(), param3, &bResult);");
3510                 println("}\n");
3511         }
3512
3513
3514         /**
3515          * HELPER: writeMethodCplusSkeleton() writes the method of the skeleton class
3516          */
3517         private void writeMethodCplusSkeleton(Collection<String> methods, InterfaceDecl intDecl, 
3518                         Set<String> callbackClasses, boolean callbackSkeleton) {
3519
3520                 for (String method : methods) {
3521
3522                         List<String> methParams = intDecl.getMethodParams(method);
3523                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
3524                         String methodId = intDecl.getMethodId(method);
3525                         String methodType = checkAndGetCplusType(intDecl.getMethodType(method));
3526                         print(methodType + " " + methodId + "(");
3527                         boolean isCallbackMethod = false;
3528                         String callbackType = null;
3529                         for (int i = 0; i < methParams.size(); i++) {
3530
3531                                 String origParamType = methPrmTypes.get(i);
3532                                 if (callbackClasses.contains(origParamType)) { // Check if this has callback object
3533                                         isCallbackMethod = true;
3534                                         callbackType = origParamType;   
3535                                 }
3536                                 String paramType = checkAndGetParamClass(methPrmTypes.get(i));
3537                                 String methPrmType = checkAndGetCplusType(paramType);
3538                                 String methParamComplete = checkAndGetCplusArray(methPrmType, methParams.get(i));
3539                                 print(methParamComplete);
3540                                 // Check if this is the last element (don't print a comma)
3541                                 if (i != methParams.size() - 1) {
3542                                         print(", ");
3543                                 }
3544                         }
3545                         println(") {");
3546                         // Now, write the body of skeleton!
3547                         writeStdMethodBodyCplusSkeleton(methParams, methodId, intDecl.getMethodType(method));
3548                         println("}\n");
3549                         if (isCallbackMethod)
3550                                 writeInitCallbackCplusSkeleton(callbackSkeleton);
3551                 }
3552         }
3553
3554
3555         /**
3556          * HELPER: writeCallbackCplusNumStubs() writes the numStubs variable
3557          */
3558         private void writeCallbackCplusNumStubs(List<String> methParams, List<String> methPrmTypes, String callbackType) {
3559
3560                 for (int i = 0; i < methParams.size(); i++) {
3561                         String paramType = methPrmTypes.get(i);
3562                         String param = methParams.get(i);
3563                         //if (callbackType.equals(paramType)) {
3564                         if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
3565                                 String exchParamType = checkAndGetParamClass(paramType);
3566                                 // Print array if this is array or list if this is a list of callback objects
3567                                 println("int numStubs" + i + " = 0;");
3568                         }
3569                 }
3570         }
3571
3572
3573         /**
3574          * HELPER: writeCallbackCplusStubGeneration() writes the callback stub generation part
3575          */
3576         private void writeCallbackCplusStubGeneration(List<String> methParams, List<String> methPrmTypes, String callbackType) {
3577
3578                 // Iterate over callback objects
3579                 for (int i = 0; i < methParams.size(); i++) {
3580                         String paramType = methPrmTypes.get(i);
3581                         String param = methParams.get(i);
3582                         // Generate a loop if needed
3583                         if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
3584                                 String exchParamType = checkAndGetParamClass(paramType);
3585                                 if (isArrayOrList(paramType, param)) {
3586                                         println("vector<" + exchParamType + "> stub;");
3587                                         println("for (int objId = 0; objId < numStubs" + i + "; objId++) {");
3588                                         println(exchParamType + "* cb" + i + " = new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt);");
3589                                         println("stub" + i + ".push_back(cb);");
3590                                         println("vecCallbackObj.push_back(cb);");
3591                                         println("objIdCnt++;");
3592                                         println("}");
3593                                 } else {
3594                                         println(exchParamType + "* stub" + i + " = new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt);");
3595                                         println("vecCallbackObj.push_back(stub" + i + ");");
3596                                         println("objIdCnt++;");
3597                                 }
3598                         }
3599                 }
3600         }
3601
3602
3603         /**
3604          * HELPER: checkAndWriteEnumTypeCplusSkeleton() writes the enum type (convert from enum to int)
3605          */
3606         private void checkAndWriteEnumTypeCplusSkeleton(List<String> methParams, List<String> methPrmTypes) {
3607
3608                 // Iterate and find enum declarations
3609                 for (int i = 0; i < methParams.size(); i++) {
3610                         String paramType = methPrmTypes.get(i);
3611                         String param = methParams.get(i);
3612                         String simpleType = getGenericType(paramType);
3613                         if (isEnumClass(simpleType)) {
3614                         // Check if this is enum type
3615                                 if (isArrayOrList(paramType, param)) {  // An array
3616                                         println("int len" + i + " = paramEnumInt" + i + ".size();");
3617                                         println("vector<" + simpleType + "> paramEnum" + i + "(len" + i + ");");
3618                                         println("for (int i=0; i < len" + i + "; i++) {");
3619                                         println("paramEnum" + i + "[i] = (" + simpleType + ") paramEnumInt" + i + "[i];");
3620                                         println("}");
3621                                 } else {        // Just one element
3622                                         println(simpleType + " paramEnum" + i + ";");
3623                                         println("paramEnum" + i + " = (" + simpleType + ") paramEnumInt" + i + "[0];");
3624                                 }
3625                         }
3626                 }
3627         }
3628
3629
3630         /**
3631          * HELPER: checkAndWriteEnumRetTypeCplusSkeleton() writes the enum return type (convert from enum to int)
3632          */
3633         private void checkAndWriteEnumRetTypeCplusSkeleton(String retType) {
3634
3635                 // Strips off array "[]" for return type
3636                 String pureType = getSimpleArrayType(getGenericType(retType));
3637                 // Take the inner type of generic
3638                 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
3639                         pureType = getTypeOfGeneric(retType)[0];
3640                 if (isEnumClass(pureType)) {
3641                 // Check if this is enum type
3642                         // Enum decoder
3643                         if (isArrayOrList(retType, retType)) {  // An array
3644                                 println("int retLen = retEnum.size();");
3645                                 println("vector<int> retEnumInt(retLen);");
3646                                 println("for (int i=0; i < retLen; i++) {");
3647                                 println("retEnumInt[i] = (int) retEnum[i];");
3648                                 println("}");
3649                         } else {        // Just one element
3650                                 println("vector<int> retEnumInt(1);");
3651                                 println("retEnumInt[0] = (int) retEnum;");
3652                         }
3653                 }
3654         }
3655
3656
3657         /**
3658          * HELPER: writeMethodHelperReturnCplusSkeleton() writes the return statement part in skeleton
3659          */
3660         private void writeMethodInputParameters(List<String> methParams, List<String> methPrmTypes, 
3661                         Set<String> callbackClasses, String methodId) {
3662
3663                 print(methodId + "(");
3664                 for (int i = 0; i < methParams.size(); i++) {
3665                         String paramType = returnGenericCallbackType(methPrmTypes.get(i));
3666                         if (callbackClasses.contains(paramType))
3667                                 print("stub" + i);
3668                         else if (isEnumClass(getGenericType(paramType)))        // Check if this is enum type
3669                                 print("paramEnum" + i);
3670                         else if (isStructClass(getGenericType(paramType)))      // Struct type
3671                                 print("paramStruct" + i);
3672                         else
3673                                 print(getSimpleIdentifier(methParams.get(i)));
3674                         if (i != methParams.size() - 1) {
3675                                 print(", ");
3676                         }
3677                 }
3678                 println(");");
3679         }
3680
3681
3682         /**
3683          * HELPER: writeMethodHelperReturnCplusSkeleton() writes the return statement part in skeleton
3684          */
3685         private void writeMethodHelperReturnCplusSkeleton(InterfaceDecl intDecl, List<String> methParams,
3686                         List<String> methPrmTypes, String method, boolean isCallbackMethod, String callbackType,
3687                         String methodId, Set<String> callbackClasses) {
3688
3689                 println("rmiObj->getMethodParams(paramCls, numParam, paramObj);");
3690                 if (isCallbackMethod)
3691                         writeCallbackCplusStubGeneration(methParams, methPrmTypes, callbackType);
3692                 checkAndWriteEnumTypeCplusSkeleton(methParams, methPrmTypes);
3693                 writeStructMembersInitCplusSkeleton(intDecl, methParams, methPrmTypes, method);
3694                 // Check if this is "void"
3695                 String retType = intDecl.getMethodType(method);
3696                 // Check if this is "void"
3697                 if (retType.equals("void")) {
3698                         writeMethodInputParameters(methParams, methPrmTypes, callbackClasses, methodId);
3699                 } else { // We do have a return value
3700                         if (isEnumClass(getSimpleArrayType(getGenericType(retType)))) // Enum type
3701                                 print(checkAndGetCplusType(retType) + " retEnum = ");
3702                         else if (isStructClass(getSimpleArrayType(getGenericType(retType)))) // Struct type
3703                                 print(checkAndGetCplusType(retType) + " retStruct = ");
3704                         else
3705                                 print(checkAndGetCplusType(retType) + " retVal = ");
3706                         writeMethodInputParameters(methParams, methPrmTypes, callbackClasses, methodId);
3707                         checkAndWriteEnumRetTypeCplusSkeleton(retType);
3708                         if (isStructClass(getSimpleArrayType(getGenericType(retType)))) // Struct type
3709                                 writeStructReturnCplusSkeleton(getSimpleArrayType(getGenericType(retType)), retType);
3710                         if (isEnumClass(getSimpleArrayType(getGenericType(retType)))) // Enum type
3711                                 println("void* retObj = &retEnumInt;");
3712                         else
3713                                 if (!isStructClass(getSimpleArrayType(getGenericType(retType)))) // Struct type
3714                                         println("void* retObj = &retVal;");
3715                         String retTypeC = checkAndGetCplusType(retType);
3716                         if (isStructClass(getSimpleArrayType(getGenericType(retType)))) // Struct type
3717                                 println("rmiObj->sendReturnObj(retObj, retCls, numRetObj);");
3718                         else
3719                                 println("rmiObj->sendReturnObj(retObj, \"" + checkAndGetCplusRetClsType(getEnumType(retType)) + "\");");
3720                 }
3721         }
3722
3723
3724         /**
3725          * HELPER: writeStdMethodHelperBodyCplusSkeleton() writes the standard method body helper in the skeleton class
3726          */
3727         private void writeStdMethodHelperBodyCplusSkeleton(InterfaceDecl intDecl, List<String> methParams,
3728                         List<String> methPrmTypes, String method, String methodId, Set<String> callbackClasses) {
3729
3730                 // Generate array of parameter types
3731                 boolean isCallbackMethod = false;
3732                 String callbackType = null;
3733                 print("string paramCls[] = { ");
3734                 for (int i = 0; i < methParams.size(); i++) {
3735                         String paramType = returnGenericCallbackType(methPrmTypes.get(i));
3736                         if (callbackClasses.contains(paramType)) {
3737                                 isCallbackMethod = true;
3738                                 callbackType = paramType;
3739                                 print("\"int\"");
3740                         } else {        // Generate normal classes if it's not a callback object
3741                                 String paramTypeC = checkAndGetCplusArgClsType(methPrmTypes.get(i), methParams.get(i));
3742                                 print("\"" + paramTypeC + "\"");
3743                         }
3744                         if (i != methParams.size() - 1) {
3745                                 print(", ");
3746                         }
3747                 }
3748                 println(" };");
3749                 println("int numParam = " + methParams.size() + ";");
3750                 if (isCallbackMethod)
3751                         writeCallbackCplusNumStubs(methParams, methPrmTypes, callbackType);
3752                 // Generate parameters
3753                 for (int i = 0; i < methParams.size(); i++) {
3754                         String paramType = returnGenericCallbackType(methPrmTypes.get(i));
3755                         if (!callbackClasses.contains(paramType)) {
3756                                 String methParamType = methPrmTypes.get(i);
3757                                 if (isEnumClass(getSimpleArrayType(getGenericType(methParamType)))) {   
3758                                 // Check if this is enum type
3759                                         println("vector<int> paramEnumInt" + i + ";");
3760                                 } else {
3761                                         String methPrmType = checkAndGetCplusType(methParamType);
3762                                         String methParamComplete = checkAndGetCplusArray(methPrmType, methParams.get(i));
3763                     println(methParamComplete + ";");
3764                                 }
3765                         }
3766                 }
3767                 // Generate array of parameter objects
3768                 print("void* paramObj[] = { ");
3769                 for (int i = 0; i < methParams.size(); i++) {
3770                         String paramType = returnGenericCallbackType(methPrmTypes.get(i));
3771                         if (callbackClasses.contains(paramType))
3772                                 print("&numStubs" + i);
3773                         else if (isEnumClass(getGenericType(paramType)))        // Check if this is enum type
3774                                 print("&paramEnumInt" + i);
3775                         else
3776                                 print("&" + getSimpleIdentifier(methParams.get(i)));
3777                         if (i != methParams.size() - 1) {
3778                                 print(", ");
3779                         }
3780                 }
3781                 println(" };");
3782                 // Write the return value part
3783                 writeMethodHelperReturnCplusSkeleton(intDecl, methParams, methPrmTypes, method, isCallbackMethod, 
3784                         callbackType, methodId, callbackClasses);
3785         }
3786
3787
3788         /**
3789          * HELPER: writeStructMembersCplusSkeleton() writes member parameters of struct
3790          */
3791         private void writeStructMembersCplusSkeleton(String simpleType, String paramType, 
3792                         String param, String method, InterfaceDecl intDecl, int iVar) {
3793
3794                 // Get the struct declaration for this struct and generate initialization code
3795                 StructDecl structDecl = getStructDecl(simpleType);
3796                 List<String> memTypes = structDecl.getMemberTypes(simpleType);
3797                 List<String> members = structDecl.getMembers(simpleType);
3798                 int methodNumId = intDecl.getMethodNumId(method);
3799                 String counter = "struct" + methodNumId + "Size" + iVar;
3800                 if (isArrayOrList(param, paramType)) {  // An array or list
3801                         println("for(int i = 0; i < " + counter + "; i++) {");
3802                 }
3803                 // Set up variables
3804                 if (isArrayOrList(param, paramType)) {  // An array or list
3805                         for (int i = 0; i < members.size(); i++) {
3806                                 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
3807                                 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
3808                                 println(getSimpleType(getEnumType(prmType)) + " param" + i + "[" + counter + "];");
3809                         }
3810                 } else {        // Just one struct element
3811                         for (int i = 0; i < members.size(); i++) {
3812                                 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
3813                                 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
3814                                 println(getSimpleType(getEnumType(prmType)) + " param" + i + ";");
3815                         }
3816                 }
3817                 println("int pos = 0;");
3818                 if (isArrayOrList(param, paramType)) {  // An array or list
3819                         println("for(int i = 0; i < retLen; i++) {");
3820                         for (int i = 0; i < members.size(); i++) {
3821                                 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
3822                                 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
3823                                 println("paramCls[pos] = \"" + getSimpleType(getEnumType(prmType)) + "\";");
3824                                 println("paramObj[pos++] = &param" + i + "[i];");
3825                         }
3826                         println("}");
3827                 } else {        // Just one struct element
3828                         for (int i = 0; i < members.size(); i++) {
3829                                 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
3830                                 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
3831                                 println("paramCls[pos] = \"" + getSimpleType(getEnumType(prmType)) + "\";");
3832                                 println("paramObj[pos++] = &param" + i + ";");
3833                         }
3834                 }
3835         }
3836
3837
3838         /**
3839          * HELPER: writeStructMembersInitCplusSkeleton() writes member parameters initialization of struct
3840          */
3841         private void writeStructMembersInitCplusSkeleton(InterfaceDecl intDecl, List<String> methParams,
3842                         List<String> methPrmTypes, String method) {
3843
3844                 for (int i = 0; i < methParams.size(); i++) {
3845                         String paramType = methPrmTypes.get(i);
3846                         String param = methParams.get(i);
3847                         String simpleType = getGenericType(paramType);
3848                         if (isStructClass(simpleType)) {
3849                                 int methodNumId = intDecl.getMethodNumId(method);
3850                                 String counter = "struct" + methodNumId + "Size" + i;
3851                                 // Declaration
3852                                 if (isArrayOrList(param, paramType)) {  // An array or list
3853                                         println("vector<" + simpleType + "> paramStruct" + i + ";");
3854                                 } else
3855                                         println(simpleType + " paramStruct" + i + ";");
3856                                 // Initialize members
3857                                 StructDecl structDecl = getStructDecl(simpleType);
3858                                 List<String> members = structDecl.getMembers(simpleType);
3859                                 List<String> memTypes = structDecl.getMemberTypes(simpleType);
3860                                 if (isArrayOrList(param, paramType)) {  // An array or list
3861                                         println("for(int i = 0; i < " + counter + "; i++) {");
3862                                         for (int j = 0; j < members.size(); j++) {
3863                                                 print("paramStruct" + i + "[i]." + getSimpleIdentifier(members.get(j)));
3864                                                 println(" = param" + j + "[i];");
3865                                         }
3866                                         println("}");
3867                                 } else {        // Just one struct element
3868                                         for (int j = 0; j < members.size(); j++) {
3869                                                 print("paramStruct" + i + "." + getSimpleIdentifier(members.get(j)));
3870                                                 println(" = param" + j + ";");
3871                                         }
3872                                 }
3873                         }
3874                 }
3875         }
3876
3877
3878         /**
3879          * HELPER: writeStructReturnCplusSkeleton() writes parameters of struct for return statement
3880          */
3881         private void writeStructReturnCplusSkeleton(String simpleType, String retType) {
3882
3883                 // Minimum retLen is 1 if this is a single struct object
3884                 if (isArrayOrList(retType, retType))
3885                         println("int retLen = retStruct.size();");
3886                 else    // Just single struct object
3887                         println("int retLen = 1;");
3888                 println("void* retLenObj = &retLen;");
3889                 println("rmiObj->sendReturnObj(retLenObj, \"int\");");
3890                 int numMem = getNumOfMembers(simpleType);
3891                 println("int numRetObj = " + numMem + "*retLen;");
3892                 println("string retCls[numRetObj];");
3893                 println("void* retObj[numRetObj];");
3894                 println("int retPos = 0;");
3895                 // Get the struct declaration for this struct and generate initialization code
3896                 StructDecl structDecl = getStructDecl(simpleType);
3897                 List<String> memTypes = structDecl.getMemberTypes(simpleType);
3898                 List<String> members = structDecl.getMembers(simpleType);
3899                 if (isArrayOrList(retType, retType)) {  // An array or list
3900                         println("for(int i = 0; i < retLen; i++) {");
3901                         for (int i = 0; i < members.size(); i++) {
3902                                 String paramTypeC = checkAndGetCplusType(memTypes.get(i));
3903                                 String prmType = checkAndGetCplusArrayType(paramTypeC, members.get(i));
3904                                 println("retCls[retPos] = \"" + getSimpleType(getEnumType(prmType)) + "\";");
3905                                 print("retObj[retPos++] = &retStruct[i].");
3906                                 print(getEnumParam(memTypes.get(i), getSimpleIdentifier(members.get(i)), i));
3907                                 println(";");
3908                         }
3909                         println("}");
3910                 } else {        // Just one struct element
3911                         for (int i = 0; i < members.size(); i++) {
3912                                 String paramTypeC = checkAndGetCplusType(memTypes.get(i));
3913                                 String prmType = checkAndGetCplusArrayType(paramTypeC, members.get(i));
3914                                 println("retCls[retPos] = \"" + getSimpleType(getEnumType(prmType)) + "\";");
3915                                 print("retObj[retPos++] = &retStruct.");
3916                                 print(getEnumParam(memTypes.get(i), getSimpleIdentifier(members.get(i)), i));
3917                                 println(";");
3918                         }
3919                 }
3920
3921         }
3922
3923
3924         /**
3925          * HELPER: writeMethodHelperStructCplusSkeleton() writes the struct in skeleton
3926          */
3927         private void writeMethodHelperStructCplusSkeleton(InterfaceDecl intDecl, List<String> methParams,
3928                         List<String> methPrmTypes, String method, String methodId, Set<String> callbackClasses) {
3929
3930                 // Generate array of parameter objects
3931                 boolean isCallbackMethod = false;
3932                 String callbackType = null;
3933                 print("int numParam = ");
3934                 writeLengthStructParamClassSkeleton(methParams, methPrmTypes, method, intDecl);
3935                 println(";");
3936                 println("string paramCls[numParam];");
3937                 println("void* paramObj[numParam];");
3938                 // Iterate again over the parameters
3939                 for (int i = 0; i < methParams.size(); i++) {
3940                         String paramType = methPrmTypes.get(i);
3941                         String param = methParams.get(i);
3942                         String simpleType = getGenericType(paramType);
3943                         if (isStructClass(simpleType)) {
3944                                 writeStructMembersCplusSkeleton(simpleType, paramType, param, method, intDecl, i);
3945                         } else {
3946                                 String prmType = returnGenericCallbackType(methPrmTypes.get(i));
3947                                 if (callbackClasses.contains(prmType)) {
3948                                         isCallbackMethod = true;
3949                                         callbackType = paramType;
3950                                         writeCallbackCplusNumStubs(methParams, methPrmTypes, callbackType);
3951                                         println("paramCls[pos] = \"int\";");
3952                                         println("paramObj[pos++] = &numStubs" + i + ";");
3953                                 } else {        // Generate normal classes if it's not a callback object
3954                                         String paramTypeC = checkAndGetCplusType(methPrmTypes.get(i));
3955                                         String prmTypeC = checkAndGetCplusArrayType(paramTypeC, methParams.get(i));
3956                                         if (isEnumClass(getGenericType(paramTypeC))) {  // Check if this is enum type
3957                                                 println("vector<int> paramEnumInt" + i + ";");
3958                                         } else {
3959                                                 String methParamComplete = checkAndGetCplusArray(paramTypeC, methParams.get(i));
3960                                                 println(methParamComplete + ";");
3961                                         }
3962                                         println("paramCls[pos] = \"" + getEnumType(prmTypeC) + "\";");
3963                                         if (isEnumClass(getGenericType(paramType)))     // Check if this is enum type
3964                                                 println("paramObj[pos++] = &paramEnumInt" + i);
3965                                         else
3966                                                 println("paramObj[pos++] = &" + getSimpleIdentifier(methParams.get(i)) + ";");
3967                                 }
3968                         }
3969                 }
3970                 // Write the return value part
3971                 writeMethodHelperReturnCplusSkeleton(intDecl, methParams, methPrmTypes, method, isCallbackMethod, 
3972                         callbackType, methodId, callbackClasses);
3973         }
3974
3975
3976         /**
3977          * HELPER: writeMethodHelperCplusSkeleton() writes the method helper of the skeleton class
3978          */
3979         private void writeMethodHelperCplusSkeleton(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
3980
3981                 // Use this set to handle two same methodIds
3982                 Set<String> uniqueMethodIds = new HashSet<String>();
3983                 for (String method : methods) {
3984
3985                         List<String> methParams = intDecl.getMethodParams(method);
3986                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
3987                         if (isStructPresent(methParams, methPrmTypes)) {        // Treat struct differently
3988                                 String methodId = intDecl.getMethodId(method);
3989                                 print("void ___");
3990                                 String helperMethod = methodId;
3991                                 if (uniqueMethodIds.contains(methodId))
3992                                         helperMethod = helperMethod + intDecl.getMethodNumId(method);
3993                                 else
3994                                         uniqueMethodIds.add(methodId);
3995                                 String retType = intDecl.getMethodType(method);
3996                                 print(helperMethod + "(");
3997                                 boolean begin = true;
3998                                 for (int i = 0; i < methParams.size(); i++) { // Print size variables
3999                                         String paramType = methPrmTypes.get(i);
4000                                         String param = methParams.get(i);
4001                                         String simpleType = getSimpleType(paramType);
4002                                         if (isStructClass(simpleType)) {
4003                                                 if (!begin) {   // Generate comma for not the beginning variable
4004                                                         print(", "); begin = false;
4005                                                 }
4006                                                 int methodNumId = intDecl.getMethodNumId(method);
4007                                                 print("int struct" + methodNumId + "Size" + i);
4008                                         }
4009                                 }
4010                                 println(") {");
4011                                 writeMethodHelperStructCplusSkeleton(intDecl, methParams, methPrmTypes, method, methodId, callbackClasses);
4012                                 println("}\n");
4013                         } else {
4014                                 String methodId = intDecl.getMethodId(method);
4015                                 print("void ___");
4016                                 String helperMethod = methodId;
4017                                 if (uniqueMethodIds.contains(methodId))
4018                                         helperMethod = helperMethod + intDecl.getMethodNumId(method);
4019                                 else
4020                                         uniqueMethodIds.add(methodId);
4021                                 // Check if this is "void"
4022                                 String retType = intDecl.getMethodType(method);
4023                                 println(helperMethod + "() {");
4024                                 // Now, write the helper body of skeleton!
4025                                 writeStdMethodHelperBodyCplusSkeleton(intDecl, methParams, methPrmTypes, method, methodId, callbackClasses);
4026                                 println("}\n");
4027                         }
4028                 }
4029                 // Write method helper for structs
4030                 writeMethodHelperStructSetupCplusSkeleton(methods, intDecl);
4031         }
4032
4033
4034         /**
4035          * HELPER: writeMethodHelperStructSetupCplusSkeleton() writes the method helper of struct in skeleton class
4036          */
4037         private void writeMethodHelperStructSetupCplusSkeleton(Collection<String> methods, 
4038                         InterfaceDecl intDecl) {
4039
4040                 // Use this set to handle two same methodIds
4041                 for (String method : methods) {
4042
4043                         List<String> methParams = intDecl.getMethodParams(method);
4044                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4045                         // Check for params with structs
4046                         for (int i = 0; i < methParams.size(); i++) {
4047                                 String paramType = methPrmTypes.get(i);
4048                                 String param = methParams.get(i);
4049                                 String simpleType = getSimpleType(paramType);
4050                                 if (isStructClass(simpleType)) {
4051                                         int methodNumId = intDecl.getMethodNumId(method);
4052                                         print("int ___");
4053                                         String helperMethod = methodNumId + "struct" + i;
4054                                         println(helperMethod + "() {");
4055                                         // Now, write the helper body of skeleton!
4056                                         println("string paramCls[] = { \"int\" };");
4057                                         println("int numParam = 1;");
4058                                         println("int param0 = 0;");
4059                                         println("void* paramObj[] = { &param0 };");
4060                                         println("rmiObj->getMethodParams(paramCls, numParam, paramObj);");
4061                                         println("return param0;");
4062                                         println("}\n");
4063                                 }
4064                         }
4065                 }
4066         }
4067
4068
4069         /**
4070          * HELPER: writeMethodHelperStructSetupCplusCallbackSkeleton() writes the method helper of struct in skeleton class
4071          */
4072         private void writeMethodHelperStructSetupCplusCallbackSkeleton(Collection<String> methods, 
4073                         InterfaceDecl intDecl) {
4074
4075                 // Use this set to handle two same methodIds
4076                 for (String method : methods) {
4077
4078                         List<String> methParams = intDecl.getMethodParams(method);
4079                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4080                         // Check for params with structs
4081                         for (int i = 0; i < methParams.size(); i++) {
4082                                 String paramType = methPrmTypes.get(i);
4083                                 String param = methParams.get(i);
4084                                 String simpleType = getSimpleType(paramType);
4085                                 if (isStructClass(simpleType)) {
4086                                         int methodNumId = intDecl.getMethodNumId(method);
4087                                         print("int ___");
4088                                         String helperMethod = methodNumId + "struct" + i;
4089                                         println(helperMethod + "(IoTRMIObject* rmiObj) {");
4090                                         // Now, write the helper body of skeleton!
4091                                         println("string paramCls[] = { \"int\" };");
4092                                         println("int numParam = 1;");
4093                                         println("int param0 = 0;");
4094                                         println("void* paramObj[] = { &param0 };");
4095                                         println("rmiObj->getMethodParams(paramCls, numParam, paramObj);");
4096                                         println("return param0;");
4097                                         println("}\n");
4098                                 }
4099                         }
4100                 }
4101         }
4102
4103
4104         /**
4105          * HELPER: writeCplusMethodPermission() writes permission checks in skeleton
4106          */
4107         private void writeCplusMethodPermission(String intface) {
4108
4109                 // Get all the different stubs
4110                 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
4111                 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
4112                         String newIntface = intMeth.getKey();
4113                         int newObjectId = getNewIntfaceObjectId(newIntface);
4114                         println("if (_objectId == object" + newObjectId + "Id) {");
4115                         println("if (set" + newObjectId + "Allowed.find(methodId) == set" + newObjectId + "Allowed.end()) {");
4116                         println("cerr << \"Object with object Id: \" << _objectId << \"  is not allowed to access method: \" << methodId << endl;");
4117                         println("exit(-1);");
4118                         println("}");
4119                         println("}");
4120                         println("else {");
4121                         println("cerr << \"Object Id: \" << _objectId << \" not recognized!\" << endl;");
4122                         println("exit(-1);");
4123                         println("}");
4124                 }
4125         }
4126
4127
4128         /**
4129          * HELPER: writeCplusWaitRequestInvokeMethod() writes the main loop of the skeleton class
4130          */
4131         private void writeCplusWaitRequestInvokeMethod(Collection<String> methods, InterfaceDecl intDecl, boolean callbackExist, String intface) {
4132
4133                 // Use this set to handle two same methodIds
4134                 Set<String> uniqueMethodIds = new HashSet<String>();
4135                 println("void ___waitRequestInvokeMethod() {");
4136                 // Write variables here if we have callbacks or enums or structs
4137                 writeCountVarStructSkeleton(methods, intDecl);
4138                 println("while (true) {");
4139                 println("rmiObj->getMethodBytes();");
4140                 println("int _objectId = rmiObj->getObjectId();");
4141                 println("int methodId = rmiObj->getMethodId();");
4142                 // Generate permission check
4143                 writeCplusMethodPermission(intface);
4144                 println("switch (methodId) {");
4145                 // Print methods and method Ids
4146                 for (String method : methods) {
4147                         String methodId = intDecl.getMethodId(method);
4148                         int methodNumId = intDecl.getMethodNumId(method);
4149                         print("case " + methodNumId + ": ___");
4150                         String helperMethod = methodId;
4151                         if (uniqueMethodIds.contains(methodId))
4152                                 helperMethod = helperMethod + methodNumId;
4153                         else
4154                                 uniqueMethodIds.add(methodId);
4155                         print(helperMethod + "(");
4156                         writeInputCountVarStructSkeleton(method, intDecl);
4157                         println("); break;");
4158                 }
4159                 String method = "___initCallBack()";
4160                 // Print case -9999 (callback handler) if callback exists
4161                 if (callbackExist) {
4162                         int methodId = intDecl.getHelperMethodNumId(method);
4163                         println("case " + methodId + ": ___regCB(); break;");
4164                 }
4165                 writeMethodCallStructSkeleton(methods, intDecl);
4166                 println("default: ");
4167                 println("cerr << \"Method Id \" << methodId << \" not recognized!\" << endl;");
4168                 println("throw exception();");
4169                 println("}");
4170                 println("}");
4171                 println("}\n");
4172         }
4173
4174
4175         /**
4176          * generateCplusSkeletonClass() generate skeletons based on the methods list in C++
4177          */
4178         public void generateCplusSkeletonClass() throws IOException {
4179
4180                 // Create a new directory
4181                 String path = createDirectories(dir, subdir);
4182                 for (String intface : mapIntfacePTH.keySet()) {
4183                         // Open a new file to write into
4184                         String newSkelClass = intface + "_Skeleton";
4185                         FileWriter fw = new FileWriter(path + "/" + newSkelClass + ".hpp");
4186                         pw = new PrintWriter(new BufferedWriter(fw));
4187                         // Write file headers
4188                         println("#ifndef _" + newSkelClass.toUpperCase() + "_HPP__");
4189                         println("#define _" + newSkelClass.toUpperCase() + "_HPP__");
4190                         println("#include <iostream>");
4191                         println("#include \"" + intface + ".hpp\"\n");
4192                         // Pass in set of methods and get import classes
4193                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4194                         InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
4195                         List<String> methods = intDecl.getMethods();
4196                         Set<String> includeClasses = getIncludeClasses(methods, intDecl, intface, true);
4197                         List<String> stdIncludeClasses = getStandardCplusIncludeClasses();
4198                         List<String> allIncludeClasses = getAllLibClasses(stdIncludeClasses, includeClasses);
4199                         printIncludeStatements(allIncludeClasses); println("");
4200                         println("using namespace std;\n");
4201                         // Find out if there are callback objects
4202                         Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
4203                         boolean callbackExist = !callbackClasses.isEmpty();
4204                         // Write class header
4205                         println("class " + newSkelClass + " : public " + intface); println("{");
4206                         println("private:\n");
4207                         // Write properties
4208                         writePropertiesCplusSkeleton(intface, callbackExist, callbackClasses);
4209                         println("public:\n");
4210                         // Write constructor
4211                         writeConstructorCplusSkeleton(newSkelClass, intface, callbackExist, intDecl, methods);
4212                         // Write deconstructor
4213                         writeDeconstructorCplusSkeleton(newSkelClass, callbackExist, callbackClasses);
4214                         // Write methods
4215                         writeMethodCplusSkeleton(methods, intDecl, callbackClasses, false);
4216                         // Write method helper
4217                         writeMethodHelperCplusSkeleton(methods, intDecl, callbackClasses);
4218                         // Write waitRequestInvokeMethod() - main loop
4219                         writeCplusWaitRequestInvokeMethod(methods, intDecl, callbackExist, intface);
4220                         println("};");
4221                         writePermissionInitializationCplus(intface, newSkelClass, intDecl);
4222                         writeObjectIdCountInitializationCplus(newSkelClass, callbackExist);
4223                         println("#endif");
4224                         pw.close();
4225                         System.out.println("IoTCompiler: Generated skeleton class " + newSkelClass + ".hpp...");
4226                 }
4227         }
4228
4229
4230         /**
4231          * HELPER: writePropertiesCplusCallbackSkeleton() writes the properties of the callback skeleton class
4232          */
4233         private void writePropertiesCplusCallbackSkeleton(String intface, boolean callbackExist, Set<String> callbackClasses) {
4234
4235                 println(intface + " *mainObj;");
4236                 // Keep track of object Ids of all stubs registered to this interface
4237                 println("int objectId;");
4238                 // Callback
4239                 if (callbackExist) {
4240                         Iterator it = callbackClasses.iterator();
4241                         String callbackType = (String) it.next();
4242                         String exchangeType = checkAndGetParamClass(callbackType);
4243                         println("// Callback properties");
4244                         println("IoTRMICall* rmiCall;");
4245                         println("vector<" + exchangeType + "*> vecCallbackObj;");
4246                         println("static int objIdCnt;");
4247                 }
4248                 println("\n");
4249         }
4250
4251
4252         /**
4253          * HELPER: writeConstructorCplusCallbackSkeleton() writes the constructor of the skeleton class
4254          */
4255         private void writeConstructorCplusCallbackSkeleton(String newSkelClass, String intface, boolean callbackExist, InterfaceDecl intDecl, Collection<String> methods) {
4256
4257                 println(newSkelClass + "(" + intface + " *_mainObj, int _objectId) {");
4258                 println("mainObj = _mainObj;");
4259                 println("objectId = _objectId;");
4260                 writeStructPermissionCplusSkeleton(methods, intDecl, intface);
4261                 println("}\n");
4262         }
4263
4264
4265         /**
4266          * HELPER: writeDeconstructorCplusStub() writes the deconstructor of the stub class
4267          */
4268         private void writeDeconstructorCplusCallbackSkeleton(String newStubClass, boolean callbackExist, 
4269                         Set<String> callbackClasses) {
4270
4271                 println("~" + newStubClass + "() {");
4272                 if (callbackExist) {
4273                 // We assume that each class only has one callback interface for now
4274                         println("if (rmiCall != NULL) {");
4275                         println("delete rmiCall;");
4276                         println("rmiCall = NULL;");
4277                         println("}");
4278                         Iterator it = callbackClasses.iterator();
4279                         String callbackType = (String) it.next();
4280                         String exchangeType = checkAndGetParamClass(callbackType);
4281                         println("for(" + exchangeType + "* cb : vecCallbackObj) {");
4282                         println("delete cb;");
4283                         println("cb = NULL;");
4284                         println("}");
4285                 }
4286                 println("}");
4287                 println("");
4288         }
4289
4290
4291         /**
4292          * HELPER: writeMethodHelperCplusCallbackSkeleton() writes the method helper of callback skeleton class
4293          */
4294         private void writeMethodHelperCplusCallbackSkeleton(Collection<String> methods, InterfaceDecl intDecl, 
4295                         Set<String> callbackClasses) {
4296
4297                 // Use this set to handle two same methodIds
4298                 Set<String> uniqueMethodIds = new HashSet<String>();
4299                 for (String method : methods) {
4300
4301                         List<String> methParams = intDecl.getMethodParams(method);
4302                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4303                         if (isStructPresent(methParams, methPrmTypes)) {        // Treat struct differently
4304                                 String methodId = intDecl.getMethodId(method);
4305                                 print("void ___");
4306                                 String helperMethod = methodId;
4307                                 if (uniqueMethodIds.contains(methodId))
4308                                         helperMethod = helperMethod + intDecl.getMethodNumId(method);
4309                                 else
4310                                         uniqueMethodIds.add(methodId);
4311                                 String retType = intDecl.getMethodType(method);
4312                                 print(helperMethod + "(");
4313                                 boolean begin = true;
4314                                 for (int i = 0; i < methParams.size(); i++) { // Print size variables
4315                                         String paramType = methPrmTypes.get(i);
4316                                         String param = methParams.get(i);
4317                                         String simpleType = getSimpleType(paramType);
4318                                         if (isStructClass(simpleType)) {
4319                                                 if (!begin) {   // Generate comma for not the beginning variable
4320                                                         print(", "); begin = false;
4321                                                 }
4322                                                 int methodNumId = intDecl.getMethodNumId(method);
4323                                                 print("int struct" + methodNumId + "Size" + i);
4324                                         }
4325                                 }
4326                                 println(", IoTRMIObject* rmiObj) {");
4327                                 writeMethodHelperStructCplusSkeleton(intDecl, methParams, methPrmTypes, method, methodId, callbackClasses);
4328                                 println("}\n");
4329                         } else {
4330                                 String methodId = intDecl.getMethodId(method);
4331                                 print("void ___");
4332                                 String helperMethod = methodId;
4333                                 if (uniqueMethodIds.contains(methodId))
4334                                         helperMethod = helperMethod + intDecl.getMethodNumId(method);
4335                                 else
4336                                         uniqueMethodIds.add(methodId);
4337                                 // Check if this is "void"
4338                                 String retType = intDecl.getMethodType(method);
4339                                 println(helperMethod + "(IoTRMIObject* rmiObj) {");
4340                                 // Now, write the helper body of skeleton!
4341                                 writeStdMethodHelperBodyCplusSkeleton(intDecl, methParams, methPrmTypes, method, methodId, callbackClasses);
4342                                 println("}\n");
4343                         }
4344                 }
4345                 // Write method helper for structs
4346                 writeMethodHelperStructSetupCplusCallbackSkeleton(methods, intDecl);
4347         }
4348
4349
4350         /**
4351          * HELPER: writeCplusCallbackWaitRequestInvokeMethod() writes the request invoke method of the skeleton callback class
4352          */
4353         private void writeCplusCallbackWaitRequestInvokeMethod(Collection<String> methods, InterfaceDecl intDecl, 
4354                         boolean callbackExist) {
4355
4356                 // Use this set to handle two same methodIds
4357                 Set<String> uniqueMethodIds = new HashSet<String>();
4358                 println("void invokeMethod(IoTRMIObject* rmiObj) {");
4359                 // Write variables here if we have callbacks or enums or structs
4360                 writeCountVarStructSkeleton(methods, intDecl);
4361                 // Write variables here if we have callbacks or enums or structs
4362                 println("int methodId = rmiObj->getMethodId();");
4363                 // TODO: code the permission check here!
4364                 println("switch (methodId) {");
4365                 // Print methods and method Ids
4366                 for (String method : methods) {
4367                         String methodId = intDecl.getMethodId(method);
4368                         int methodNumId = intDecl.getMethodNumId(method);
4369                         print("case " + methodNumId + ": ___");
4370                         String helperMethod = methodId;
4371                         if (uniqueMethodIds.contains(methodId))
4372                                 helperMethod = helperMethod + methodNumId;
4373                         else
4374                                 uniqueMethodIds.add(methodId);
4375                         print(helperMethod + "(");
4376                         if (writeInputCountVarStructSkeleton(method, intDecl))
4377                                 println(", rmiObj); break;");
4378                         else
4379                                 println("rmiObj); break;");
4380                 }
4381                 String method = "___initCallBack()";
4382                 // Print case -9999 (callback handler) if callback exists
4383                 if (callbackExist) {
4384                         int methodId = intDecl.getHelperMethodNumId(method);
4385                         println("case " + methodId + ": ___regCB(rmiObj); break;");
4386                 }
4387                 writeMethodCallStructCallbackSkeleton(methods, intDecl);
4388                 println("default: ");
4389                 println("cerr << \"Method Id \" << methodId << \" not recognized!\" << endl;");
4390                 println("throw exception();");
4391                 println("}");
4392                 println("}\n");
4393         }
4394
4395
4396         /**
4397          * generateCplusCallbackSkeletonClass() generate callback skeletons based on the methods list in C++
4398          */
4399         public void generateCplusCallbackSkeletonClass() throws IOException {
4400
4401                 // Create a new directory
4402                 String path = createDirectories(dir, subdir);
4403                 for (String intface : mapIntfacePTH.keySet()) {
4404                         // Open a new file to write into
4405                         String newSkelClass = intface + "_CallbackSkeleton";
4406                         FileWriter fw = new FileWriter(path + "/" + newSkelClass + ".hpp");
4407                         pw = new PrintWriter(new BufferedWriter(fw));
4408                         // Write file headers
4409                         println("#ifndef _" + newSkelClass.toUpperCase() + "_HPP__");
4410                         println("#define _" + newSkelClass.toUpperCase() + "_HPP__");
4411                         println("#include <iostream>");
4412                         println("#include \"" + intface + ".hpp\"\n");
4413                         // Pass in set of methods and get import classes
4414                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4415                         InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
4416                         List<String> methods = intDecl.getMethods();
4417                         Set<String> includeClasses = getIncludeClasses(methods, intDecl, intface, true);
4418                         List<String> stdIncludeClasses = getStandardCplusIncludeClasses();
4419                         List<String> allIncludeClasses = getAllLibClasses(stdIncludeClasses, includeClasses);
4420                         printIncludeStatements(allIncludeClasses); println("");                 
4421                         // Find out if there are callback objects
4422                         Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
4423                         boolean callbackExist = !callbackClasses.isEmpty();
4424                         println("using namespace std;\n");
4425                         // Write class header
4426                         println("class " + newSkelClass + " : public " + intface); println("{");
4427                         println("private:\n");
4428                         // Write properties
4429                         writePropertiesCplusCallbackSkeleton(intface, callbackExist, callbackClasses);
4430                         println("public:\n");
4431                         // Write constructor
4432                         writeConstructorCplusCallbackSkeleton(newSkelClass, intface, callbackExist, intDecl, methods);
4433                         // Write deconstructor
4434                         writeDeconstructorCplusCallbackSkeleton(newSkelClass, callbackExist, callbackClasses);
4435                         // Write methods
4436                         writeMethodCplusSkeleton(methods, intDecl, callbackClasses, true);
4437                         // Write method helper
4438                         writeMethodHelperCplusCallbackSkeleton(methods, intDecl, callbackClasses);
4439                         // Write waitRequestInvokeMethod() - main loop
4440                         writeCplusCallbackWaitRequestInvokeMethod(methods, intDecl, callbackExist);
4441                         println("};");
4442                         writeObjectIdCountInitializationCplus(newSkelClass, callbackExist);
4443                         println("#endif");
4444                         pw.close();
4445                         System.out.println("IoTCompiler: Generated callback skeleton class " + newSkelClass + ".hpp...");
4446                 }
4447         }
4448
4449
4450         /**
4451          * generateInitializer() generate initializer based on type
4452          */
4453         public String generateCplusInitializer(String type) {
4454
4455                 // Generate dummy returns for now
4456                 if (type.equals("short")||
4457                         type.equals("int")      ||
4458                         type.equals("long") ||
4459                         type.equals("float")||
4460                         type.equals("double")) {
4461
4462                         return "0";
4463                 } else if ( type.equals("String") ||
4464                                         type.equals("string")) {
4465   
4466                         return "\"\"";
4467                 } else if ( type.equals("char") ||
4468                                         type.equals("byte")) {
4469
4470                         return "\' \'";
4471                 } else if ( type.equals("boolean")) {
4472
4473                         return "false";
4474                 } else {
4475                         return "NULL";
4476                 }
4477         }
4478
4479
4480         /**
4481          * setDirectory() sets a new directory for stub files
4482          */
4483         public void setDirectory(String _subdir) {
4484
4485                 subdir = _subdir;
4486         }
4487
4488
4489         /**
4490          * printUsage() prints the usage of this compiler
4491          */
4492         public static void printUsage() {
4493
4494                 System.out.println();
4495                 System.out.println("Sentinel interface and stub compiler version 1.0");
4496                 System.out.println("Copyright (c) 2015-2016 University of California, Irvine - Programming Language Group.");
4497                 System.out.println("All rights reserved.");
4498                 System.out.println("Usage:");
4499                 System.out.println("\tjava IoTCompiler -help / --help / -h\n");
4500                 System.out.println("\t\tDisplay this help texts\n\n");
4501                 System.out.println("\tjava IoTCompiler [<main-policy-file> <req-policy-file>]");
4502                 System.out.println("\tjava IoTCompiler [<main-policy-file> <req-policy-file>] [options]\n");
4503                 System.out.println("\t\tTake one or more pairs of main-req policy files, and generate Java and/or C++ files\n");
4504                 System.out.println("Options:");
4505                 System.out.println("\t-java\t<directory>\tGenerate Java stub files");
4506                 System.out.println("\t-cplus\t<directory>\tGenerate C++ stub files");
4507                 System.out.println();
4508         }
4509
4510
4511         /**
4512          * parseFile() prepares Lexer and Parser objects, then parses the file
4513          */
4514         public static ParseNode parseFile(String file) {
4515
4516                 ParseNode pn = null;
4517                 try {
4518                         ComplexSymbolFactory csf = new ComplexSymbolFactory();
4519                         ScannerBuffer lexer = 
4520                                 new ScannerBuffer(new Lexer(new BufferedReader(new FileReader(file)),csf));
4521                         Parser parse = new Parser(lexer,csf);
4522                         pn = (ParseNode) parse.parse().value;
4523                 } catch (Exception e) {
4524                         e.printStackTrace();
4525                         throw new Error("IoTCompiler: ERROR parsing policy file or wrong command line option: " + file + "\n");
4526                 }
4527
4528                 return pn;
4529         }
4530
4531
4532         /**================
4533          * Basic helper functions
4534          **================
4535          */
4536         boolean newline=true;
4537         int tablevel=0;
4538
4539         private void print(String str) {
4540                 if (newline) {
4541                         int tab=tablevel;
4542                         if (str.equals("}"))
4543                                 tab--;
4544                         for(int i=0; i<tab; i++)
4545                                 pw.print("\t");
4546                 }
4547                 pw.print(str);
4548                 updatetabbing(str);
4549                 newline=false;
4550         }
4551
4552
4553         /**
4554          * This function converts Java to C++ type for compilation
4555          */
4556         private String convertType(String type) {
4557
4558                 if (mapPrimitives.containsKey(type))
4559                         return mapPrimitives.get(type);
4560                 else
4561                         return type;
4562         }
4563
4564
4565         /**
4566          * A collection of methods with print-to-file functionality
4567          */
4568         private void println(String str) {
4569                 if (newline) {
4570                         int tab = tablevel;
4571                         if (str.contains("}") && !str.contains("{"))
4572                                 tab--;
4573                         for(int i=0; i<tab; i++)
4574                                 pw.print("\t");
4575                 }
4576                 pw.println(str);
4577                 updatetabbing(str);
4578                 newline = true;
4579         }
4580
4581
4582         private void updatetabbing(String str) {
4583
4584                 tablevel+=count(str,'{')-count(str,'}');
4585         }
4586
4587
4588         private int count(String str, char key) {
4589                 char[] array = str.toCharArray();
4590                 int count = 0;
4591                 for(int i=0; i<array.length; i++) {
4592                         if (array[i] == key)
4593                                 count++;
4594                 }
4595                 return count;
4596         }
4597
4598
4599         private void createDirectory(String dirName) {
4600
4601                 File file = new File(dirName);
4602                 if (!file.exists()) {
4603                         if (file.mkdir()) {
4604                                 System.out.println("IoTCompiler: Directory " + dirName + " has been created!");
4605                         } else {
4606                                 System.out.println("IoTCompiler: Failed to create directory " + dirName + "!");
4607                         }
4608                 } else {
4609                         System.out.println("IoTCompiler: Directory " + dirName + " exists...");
4610                 }
4611         }
4612
4613
4614         // Create a directory and possibly a sub directory
4615         private String createDirectories(String dir, String subdir) {
4616
4617                 String path = dir;
4618                 createDirectory(path);
4619                 if (subdir != null) {
4620                         path = path + "/" + subdir;
4621                         createDirectory(path);
4622                 }
4623                 return path;
4624         }
4625
4626
4627         // Inserting array members into a Map object
4628         // that maps arrKey to arrVal objects
4629         private void arraysToMap(Map map, Object[] arrKey, Object[] arrVal) {
4630
4631                 for(int i = 0; i < arrKey.length; i++) {
4632
4633                         map.put(arrKey[i], arrVal[i]);
4634                 }
4635         }
4636
4637
4638         // Check and find object Id for new interface in mapNewIntfaceObjId (callbacks)
4639         // Throw an error if the new interface is not found!
4640         // Basically the compiler needs to parse the policy (and requires) files for callback class first
4641         private int getNewIntfaceObjectId(String newIntface) {
4642
4643                 if (!mapNewIntfaceObjId.containsKey(newIntface)) {
4644                         throw new Error("IoTCompiler: Need to parse policy and requires files for callback class first! " +
4645                                                         "Please place the two files for callback class in front...\n");
4646                 } else {
4647                         int retObjId = mapNewIntfaceObjId.get(newIntface);
4648                         return retObjId;
4649                 }
4650         }
4651
4652
4653         // Return parameter category, i.e. PRIMITIVES, NONPRIMITIVES, USERDEFINED, ENUM, or STRUCT
4654         private ParamCategory getParamCategory(String paramType) {
4655
4656                 if (mapPrimitives.containsKey(paramType)) {
4657                         return ParamCategory.PRIMITIVES;
4658                 // We can either use mapNonPrimitivesJava or mapNonPrimitivesCplus here
4659                 } else if (mapNonPrimitivesJava.containsKey(getSimpleType(paramType))) {
4660                         return ParamCategory.NONPRIMITIVES;
4661                 } else if (isEnumClass(paramType)) {
4662                         return ParamCategory.ENUM;
4663                 } else if (isStructClass(paramType)) {
4664                         return ParamCategory.STRUCT;
4665                 } else
4666                         return ParamCategory.USERDEFINED;
4667         }
4668
4669
4670         // Return full class name for non-primitives to generate Java import statements
4671         // e.g. java.util.Set for Set
4672         private String getNonPrimitiveJavaClass(String paramNonPrimitives) {
4673
4674                 return mapNonPrimitivesJava.get(paramNonPrimitives);
4675         }
4676
4677
4678         // Return full class name for non-primitives to generate Cplus include statements
4679         // e.g. #include <set> for Set
4680         private String getNonPrimitiveCplusClass(String paramNonPrimitives) {
4681
4682                 return mapNonPrimitivesCplus.get(paramNonPrimitives);
4683         }
4684
4685
4686         // Get simple types, e.g. HashSet for HashSet<...>
4687         // Basically strip off the "<...>"
4688         private String getSimpleType(String paramType) {
4689
4690                 // Check if this is generics
4691                 if(paramType.contains("<")) {
4692                         String[] type = paramType.split("<");
4693                         return type[0];
4694                 } else
4695                         return paramType;
4696         }
4697
4698
4699         // Generate a set of standard classes for import statements
4700         private List<String> getStandardJavaIntfaceImportClasses() {
4701
4702                 List<String> importClasses = new ArrayList<String>();
4703                 // Add the standard list first
4704                 importClasses.add("java.util.List");
4705                 importClasses.add("java.util.ArrayList");
4706
4707                 return importClasses;
4708         }
4709
4710
4711         // Generate a set of standard classes for import statements
4712         private List<String> getStandardJavaImportClasses() {
4713
4714                 List<String> importClasses = new ArrayList<String>();
4715                 // Add the standard list first
4716                 importClasses.add("java.io.IOException");
4717                 importClasses.add("java.util.List");
4718                 importClasses.add("java.util.ArrayList");
4719                 importClasses.add("java.util.Arrays");
4720                 importClasses.add("iotrmi.Java.IoTRMICall");
4721                 importClasses.add("iotrmi.Java.IoTRMIObject");
4722
4723                 return importClasses;
4724         }
4725
4726
4727         // Generate a set of standard classes for import statements
4728         private List<String> getStandardCplusIncludeClasses() {
4729
4730                 List<String> importClasses = new ArrayList<String>();
4731                 // Add the standard list first
4732                 importClasses.add("<vector>");
4733                 importClasses.add("<set>");
4734                 importClasses.add("\"IoTRMICall.hpp\"");
4735                 importClasses.add("\"IoTRMIObject.hpp\"");
4736
4737                 return importClasses;
4738         }
4739
4740
4741         // Combine all classes for import statements
4742         private List<String> getAllLibClasses(Collection<String> stdLibClasses, Collection<String> libClasses) {
4743
4744                 List<String> allLibClasses = new ArrayList<String>(stdLibClasses);
4745                 // Iterate over the list of import classes
4746                 for (String str : libClasses) {
4747                         if (!allLibClasses.contains(str)) {
4748                                 allLibClasses.add(str);
4749                         }
4750                 }
4751                 return allLibClasses;
4752         }
4753
4754
4755
4756         // Generate a set of classes for import statements
4757         private Set<String> getImportClasses(Collection<String> methods, InterfaceDecl intDecl) {
4758
4759                 Set<String> importClasses = new HashSet<String>();
4760                 for (String method : methods) {
4761                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4762                         for (String paramType : methPrmTypes) {
4763
4764                                 String simpleType = getSimpleType(paramType);
4765                                 if (getParamCategory(simpleType) == ParamCategory.NONPRIMITIVES) {
4766                                         importClasses.add(getNonPrimitiveJavaClass(simpleType));
4767                                 }
4768                         }
4769                 }
4770                 return importClasses;
4771         }
4772
4773
4774         // Handle and return the correct enum declaration
4775         // In Java, if we declare enum in Camera interface, then it becomes "Camera.<enum>"
4776         private String getEnumParamDecl(String type, InterfaceDecl intDecl) {
4777
4778                 // Strips off array "[]" for return type
4779                 String pureType = getSimpleArrayType(type);
4780                 // Take the inner type of generic
4781                 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
4782                         pureType = getTypeOfGeneric(type)[0];
4783                 if (isEnumClass(pureType)) {
4784                         String enumType = intDecl.getInterface() + "." + type;
4785                         return enumType;
4786                 } else
4787                         return type;
4788         }
4789
4790
4791         // Handle and return the correct type
4792         private String getEnumParam(String type, String param, int i) {
4793
4794                 // Strips off array "[]" for return type
4795                 String pureType = getSimpleArrayType(type);
4796                 // Take the inner type of generic
4797                 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
4798                         pureType = getTypeOfGeneric(type)[0];
4799                 if (isEnumClass(pureType)) {
4800                         String enumParam = "paramEnum" + i;
4801                         return enumParam;
4802                 } else
4803                         return param;
4804         }
4805
4806
4807         // Handle and return the correct enum declaration translate into int[]
4808         private String getEnumType(String type) {
4809
4810                 // Strips off array "[]" for return type
4811                 String pureType = getSimpleArrayType(type);
4812                 // Take the inner type of generic
4813                 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
4814                         pureType = getGenericType(type);
4815                 if (isEnumClass(pureType)) {
4816                         String enumType = "int[]";
4817                         return enumType;
4818                 } else
4819                         return type;
4820         }
4821
4822         // Handle and return the correct enum declaration translate into int* for C
4823         private String getEnumCplusClsType(String type) {
4824
4825                 // Strips off array "[]" for return type
4826                 String pureType = getSimpleArrayType(type);
4827                 // Take the inner type of generic
4828                 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
4829                         pureType = getGenericType(type);
4830                 if (isEnumClass(pureType)) {
4831                         String enumType = "int*";
4832                         return enumType;
4833                 } else
4834                         return type;
4835         }
4836
4837
4838         // Handle and return the correct struct declaration
4839         private String getStructType(String type) {
4840
4841                 // Strips off array "[]" for return type
4842                 String pureType = getSimpleArrayType(type);
4843                 // Take the inner type of generic
4844                 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
4845                         pureType = getGenericType(type);
4846                 if (isStructClass(pureType)) {
4847                         String structType = "int";
4848                         return structType;
4849                 } else
4850                         return type;
4851         }
4852
4853
4854         // Check if this an enum declaration
4855         private boolean isEnumClass(String type) {
4856
4857                 // Just iterate over the set of interfaces
4858                 for (String intface : mapIntfacePTH.keySet()) {
4859                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4860                         EnumDecl enumDecl = (EnumDecl) decHandler.getEnumDecl(intface);
4861                         Set<String> setEnumDecl = enumDecl.getEnumDeclarations();
4862                         if (setEnumDecl.contains(type))
4863                                 return true;
4864                 }
4865                 return false;
4866         }
4867
4868
4869         // Check if this an struct declaration
4870         private boolean isStructClass(String type) {
4871
4872                 // Just iterate over the set of interfaces
4873                 for (String intface : mapIntfacePTH.keySet()) {
4874                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4875                         StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
4876                         List<String> listStructDecl = structDecl.getStructTypes();
4877                         if (listStructDecl.contains(type))
4878                                 return true;
4879                 }
4880                 return false;
4881         }
4882
4883
4884         // Return a struct declaration
4885         private StructDecl getStructDecl(String type) {
4886
4887                 // Just iterate over the set of interfaces
4888                 for (String intface : mapIntfacePTH.keySet()) {
4889                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4890                         StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
4891                         List<String> listStructDecl = structDecl.getStructTypes();
4892                         if (listStructDecl.contains(type))
4893                                 return structDecl;
4894                 }
4895                 return null;
4896         }
4897
4898
4899         // Return number of members (-1 if not found)
4900         private int getNumOfMembers(String type) {
4901
4902                 // Just iterate over the set of interfaces
4903                 for (String intface : mapIntfacePTH.keySet()) {
4904                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4905                         StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
4906                         List<String> listStructDecl = structDecl.getStructTypes();
4907                         if (listStructDecl.contains(type))
4908                                 return structDecl.getNumOfMembers(type);
4909                 }
4910                 return -1;
4911         }
4912
4913
4914         // Generate a set of classes for include statements
4915         private Set<String> getIncludeClasses(Collection<String> methods, InterfaceDecl intDecl, String intface, boolean needExchange) {
4916
4917                 Set<String> includeClasses = new HashSet<String>();
4918                 for (String method : methods) {
4919
4920                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4921                         List<String> methParams = intDecl.getMethodParams(method);
4922                         for (int i = 0; i < methPrmTypes.size(); i++) {
4923
4924                                 String simpleType = getSimpleType(methPrmTypes.get(i));
4925                                 String param = methParams.get(i);
4926                                 if (getParamCategory(simpleType) == ParamCategory.NONPRIMITIVES) {
4927                                         includeClasses.add("<" + getNonPrimitiveCplusClass(simpleType) + ">");
4928                                 } else if (getParamCategory(simpleType) == ParamCategory.USERDEFINED) {
4929                                         // For original interface, we need it exchanged... not for stub interfaces
4930                                         if (needExchange) {
4931                                                 includeClasses.add("\"" + exchangeParamType(simpleType) + ".hpp\"");
4932                                                 includeClasses.add("\"" + exchangeParamType(simpleType) + "_CallbackStub.hpp\"");
4933                                         } else {
4934                                                 includeClasses.add("\"" + simpleType + ".hpp\"");
4935                                                 includeClasses.add("\"" + simpleType + "_CallbackSkeleton.hpp\"");
4936                                         }
4937                                 } else if (getParamCategory(getSimpleArrayType(simpleType)) == ParamCategory.ENUM) {
4938                                         includeClasses.add("\"" + simpleType + ".hpp\"");
4939                                 } else if (getParamCategory(getSimpleArrayType(simpleType)) == ParamCategory.STRUCT) {
4940                                         includeClasses.add("\"" + simpleType + ".hpp\"");
4941                                 } else if (param.contains("[]")) {
4942                                 // Check if this is array for C++; translate into vector
4943                                         includeClasses.add("<vector>");
4944                                 }
4945                         }
4946                 }
4947                 return includeClasses;
4948         }
4949
4950
4951         // Generate a set of callback classes
4952         private Set<String> getCallbackClasses(Collection<String> methods, InterfaceDecl intDecl) {
4953
4954                 Set<String> callbackClasses = new HashSet<String>();
4955                 for (String method : methods) {
4956
4957                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4958                         List<String> methParams = intDecl.getMethodParams(method);
4959                         for (int i = 0; i < methPrmTypes.size(); i++) {
4960
4961                                 String type = methPrmTypes.get(i);
4962                                 if (getParamCategory(type) == ParamCategory.USERDEFINED) {
4963                                         callbackClasses.add(type);
4964                                 } else if (getParamCategory(type) == ParamCategory.NONPRIMITIVES) {
4965                                 // Can be a List<...> of callback objects ...
4966                                         String genericType = getTypeOfGeneric(type)[0];
4967                                         if (getParamCategory(type) == ParamCategory.USERDEFINED) {
4968                                                 callbackClasses.add(type);
4969                                         }
4970                                 }
4971                         }
4972                 }
4973                 return callbackClasses;
4974         }
4975
4976
4977         // Print import statements into file
4978         private void printImportStatements(Collection<String> importClasses) {
4979
4980                 for(String cls : importClasses) {
4981                         println("import " + cls + ";");
4982                 }
4983         }
4984
4985
4986         // Print include statements into file
4987         private void printIncludeStatements(Collection<String> includeClasses) {
4988
4989                 for(String cls : includeClasses) {
4990                         println("#include " + cls);
4991                 }
4992         }
4993
4994
4995         // Get the C++ version of a non-primitive type
4996         // e.g. set for Set and map for Map
4997         // Input nonPrimitiveType has to be generics in format
4998         private String[] getTypeOfGeneric(String nonPrimitiveType) {
4999
5000                 // Handle <, >, and , for 2-type generic/template
5001                 String[] substr = nonPrimitiveType.split("<")[1].split(">")[0].split(",");
5002                 return substr;
5003         }
5004
5005
5006         // Gets generic type inside "<" and ">"
5007         private String getGenericType(String type) {
5008
5009                 // Handle <, >, and , for 2-type generic/template
5010                 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES) {
5011                         String[] substr = type.split("<")[1].split(">")[0].split(",");
5012                         return substr[0];
5013                 } else
5014                         return type;
5015         }
5016
5017
5018         // This helper function strips off array declaration, e.g. int[] becomes int
5019         private String getSimpleArrayType(String type) {
5020
5021                 // Handle [ for array declaration
5022                 String substr = type;
5023                 if (type.contains("[]")) {
5024                         substr = type.split("\\[\\]")[0];
5025                 }
5026                 return substr;
5027         }
5028
5029
5030         // This helper function strips off array declaration, e.g. D[] becomes D
5031         private String getSimpleIdentifier(String ident) {
5032
5033                 // Handle [ for array declaration
5034                 String substr = ident;
5035                 if (ident.contains("[]")) {
5036                         substr = ident.split("\\[\\]")[0];
5037                 }
5038                 return substr;
5039         }
5040
5041
5042         // Checks and gets type in C++
5043         private String checkAndGetCplusType(String paramType) {
5044
5045                 if (getParamCategory(paramType) == ParamCategory.PRIMITIVES) {
5046                         return convertType(paramType);
5047                 } else if (getParamCategory(paramType) == ParamCategory.NONPRIMITIVES) {
5048
5049                         // Check for generic/template format
5050                         if (paramType.contains("<") && paramType.contains(">")) {
5051
5052                                 String genericClass = getSimpleType(paramType);
5053                                 String[] genericType = getTypeOfGeneric(paramType);
5054                                 String cplusTemplate = null;
5055                                 if (genericType.length == 1) // Generic/template with one type
5056                                         cplusTemplate = getNonPrimitiveCplusClass(genericClass) + 
5057                                                 "<" + convertType(genericType[0]) + ">";
5058                                 else // Generic/template with two types
5059                                         cplusTemplate = getNonPrimitiveCplusClass(genericClass) + 
5060                                                 "<" + convertType(genericType[0]) + "," + convertType(genericType[1]) + ">";
5061                                 return cplusTemplate;
5062                         } else
5063                                 return getNonPrimitiveCplusClass(paramType);
5064                 } else if(paramType.contains("[]")) {   // Array type (used for return type only)
5065                         String cArray = "vector<" + convertType(getSimpleArrayType(paramType)) + ">";
5066                         return cArray;
5067                 } else if(getParamCategory(paramType) == ParamCategory.USERDEFINED) {
5068                         return paramType + "*";
5069                 } else
5070                         // Just return it as is if it's not non-primitives
5071                         return paramType;
5072                         //return checkAndGetParamClass(paramType, true);
5073         }
5074
5075
5076         // Detect array declaration, e.g. int A[],
5077         //              then generate "int A[]" in C++ as "vector<int> A"
5078         private String checkAndGetCplusArray(String paramType, String param) {
5079
5080                 String paramComplete = null;
5081                 // Check for array declaration
5082                 if (param.contains("[]")) {
5083                         paramComplete = "vector<" + paramType + "> " + param.replace("[]","");
5084                 } else
5085                         // Just return it as is if it's not an array
5086                         paramComplete = paramType + " " + param;
5087
5088                 return paramComplete;
5089         }
5090         
5091
5092         // Detect array declaration, e.g. int A[],
5093         //              then generate "int A[]" in C++ as "vector<int> A"
5094         // This method just returns the type
5095         private String checkAndGetCplusArrayType(String paramType) {
5096
5097                 String paramTypeRet = null;
5098                 // Check for array declaration
5099                 if (paramType.contains("[]")) {
5100                         String type = paramType.split("\\[\\]")[0];
5101                         paramTypeRet = checkAndGetCplusType(type) + "[]";
5102                 } else if (paramType.contains("vector")) {
5103                         // Just return it as is if it's not an array
5104                         String type = paramType.split("<")[1].split(">")[0];
5105                         paramTypeRet = checkAndGetCplusType(type) + "[]";
5106                 } else
5107                         paramTypeRet = paramType;
5108
5109                 return paramTypeRet;
5110         }
5111         
5112         
5113         // Detect array declaration, e.g. int A[],
5114         //              then generate "int A[]" in C++ as "vector<int> A"
5115         // This method just returns the type
5116         private String checkAndGetCplusArrayType(String paramType, String param) {
5117
5118                 String paramTypeRet = null;
5119                 // Check for array declaration
5120                 if (param.contains("[]")) {
5121                         paramTypeRet = checkAndGetCplusType(paramType) + "[]";
5122                 } else if (paramType.contains("vector")) {
5123                         // Just return it as is if it's not an array
5124                         String type = paramType.split("<")[1].split(">")[0];
5125                         paramTypeRet = checkAndGetCplusType(type) + "[]";
5126                 } else
5127                         paramTypeRet = paramType;
5128
5129                 return paramTypeRet;
5130         }
5131
5132
5133         // Return the class type for class resolution (for return value)
5134         // - Check and return C++ array class, e.g. int A[] into int*
5135         // - Check and return C++ vector class, e.g. List<Integer> A into vector<int>
5136         private String checkAndGetCplusRetClsType(String paramType) {
5137
5138                 String paramTypeRet = null;
5139                 // Check for array declaration
5140                 if (paramType.contains("[]")) {
5141                         String type = paramType.split("\\[\\]")[0];
5142                         paramTypeRet = getSimpleArrayType(type) + "*";
5143                 } else if (paramType.contains("<") && paramType.contains(">")) {
5144                         // Just return it as is if it's not an array
5145                         String type = paramType.split("<")[1].split(">")[0];
5146                         paramTypeRet = "vector<" + getGenericType(type) + ">";
5147                 } else
5148                         paramTypeRet = paramType;
5149
5150                 return paramTypeRet;
5151         }
5152
5153
5154         // Return the class type for class resolution (for method arguments)
5155         // - Check and return C++ array class, e.g. int A[] into int*
5156         // - Check and return C++ vector class, e.g. List<Integer> A into vector<int>
5157         private String checkAndGetCplusArgClsType(String paramType, String param) {
5158
5159                 String paramTypeRet = getEnumCplusClsType(paramType);
5160                 if (!paramTypeRet.equals(paramType)) 
5161                 // Just return if it is an enum type
5162                 // Type will still be the same if it's not an enum type
5163                         return paramTypeRet;
5164
5165                 // Check for array declaration
5166                 if (param.contains("[]")) {
5167                         paramTypeRet = getSimpleArrayType(paramType) + "*";
5168                 } else if (paramType.contains("<") && paramType.contains(">")) {
5169                         // Just return it as is if it's not an array
5170                         String type = paramType.split("<")[1].split(">")[0];
5171                         paramTypeRet = "vector<" + getGenericType(type) + ">";
5172                 } else
5173                         paramTypeRet = paramType;
5174
5175                 return paramTypeRet;
5176         }
5177
5178
5179         // Detect array declaration, e.g. int A[],
5180         //              then generate type "int[]"
5181         private String checkAndGetArray(String paramType, String param) {
5182
5183                 String paramTypeRet = null;
5184                 // Check for array declaration
5185                 if (param.contains("[]")) {
5186                         paramTypeRet = paramType + "[]";
5187                 } else
5188                         // Just return it as is if it's not an array
5189                         paramTypeRet = paramType;
5190
5191                 return paramTypeRet;
5192         }
5193
5194
5195         // Is array or list?
5196         private boolean isArrayOrList(String paramType, String param) {
5197
5198                 // Check for array declaration
5199                 if (isArray(param))
5200                         return true;
5201                 else if (isList(paramType))
5202                         return true;
5203                 else
5204                         return false;
5205         }
5206
5207
5208         // Is array? 
5209         // For return type we use retType as input parameter
5210         private boolean isArray(String param) {
5211
5212                 // Check for array declaration
5213                 if (param.contains("[]"))
5214                         return true;
5215                 else
5216                         return false;
5217         }
5218
5219
5220         // Is list?
5221         private boolean isList(String paramType) {
5222
5223                 // Check for array declaration
5224                 if (paramType.contains("List"))
5225                         return true;
5226                 else
5227                         return false;
5228         }
5229
5230
5231         // Get the right type for a callback object
5232         private String checkAndGetParamClass(String paramType) {
5233
5234                 // Check if this is generics
5235                 if(getParamCategory(paramType) == ParamCategory.USERDEFINED) {
5236                         return exchangeParamType(paramType);
5237                 } else
5238                         return paramType;
5239         }
5240
5241
5242         // Returns the other interface for type-checking purposes for USERDEFINED
5243         //              classes based on the information provided in multiple policy files
5244         // e.g. return CameraWithXXX instead of Camera
5245         private String exchangeParamType(String intface) {
5246
5247                 // Param type that's passed is the interface name we need to look for
5248                 //              in the map of interfaces, based on available policy files.
5249                 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
5250                 if (decHandler != null) {
5251                 // We've found the required interface policy files
5252                         RequiresDecl reqDecl = (RequiresDecl) decHandler.getRequiresDecl(intface);
5253                         Set<String> setExchInt = reqDecl.getInterfaces();
5254                         if (setExchInt.size() == 1) {
5255                                 Iterator iter = setExchInt.iterator();
5256                                 return (String) iter.next();
5257                         } else {
5258                                 throw new Error("IoTCompiler: Ambiguous stub interfaces: " + setExchInt.toString() + 
5259                                         ". Only one new interface can be declared if the object " + intface +
5260                                         " needs to be passed in as an input parameter!\n");
5261                         }
5262                 } else {
5263                 // NULL value - this means policy files missing
5264                         throw new Error("IoTCompiler: Parameter type lookup failed for " + intface +
5265                                 "... Please provide the necessary policy files for user-defined types." +
5266                                 " If this is an array please type the brackets after the variable name," +
5267                                 " e.g. \"String str[]\", not \"String[] str\"." +
5268                                 " If this is a Collections (Java) / STL (C++) type, this compiler only" +
5269                                 " supports List/ArrayList (Java) or list (C++).\n");
5270                 }
5271         }
5272
5273
5274         public static void main(String[] args) throws Exception {
5275
5276                 // If there is no argument or just "--help" or "-h", then invoke printUsage()
5277                 if ((args[0].equals("-help") ||
5278                          args[0].equals("--help")||
5279                          args[0].equals("-h"))   ||
5280                         (args.length == 0)) {
5281
5282                         IoTCompiler.printUsage();
5283
5284                 } else if (args.length > 1) {
5285
5286                         IoTCompiler comp = new IoTCompiler();
5287                         int i = 0;                              
5288                         do {
5289                                 // Parse main policy file
5290                                 ParseNode pnPol = IoTCompiler.parseFile(args[i]);
5291                                 // Parse "requires" policy file
5292                                 ParseNode pnReq = IoTCompiler.parseFile(args[i+1]);
5293                                 // Get interface name
5294                                 String intface = ParseTreeHandler.getOrigIntface(pnPol);
5295                                 comp.setDataStructures(intface, pnPol, pnReq);
5296                                 comp.getMethodsForIntface(intface);
5297                                 i = i + 2;
5298                         // 1) Check if this is the last option before "-java" or "-cplus"
5299                         // 2) Check if this is really the last option (no "-java" or "-cplus")
5300                         } while(!args[i].equals("-java") &&
5301                                         !args[i].equals("-cplus") &&
5302                                         (i < args.length));
5303
5304                         // Generate everything if we don't see "-java" or "-cplus"
5305                         if (i == args.length) {
5306                                 comp.generateEnumJava();
5307                                 comp.generateStructJava();
5308                                 comp.generateJavaLocalInterfaces();
5309                                 comp.generateJavaInterfaces();
5310                                 comp.generateJavaStubClasses();
5311                                 comp.generateJavaCallbackStubClasses();
5312                                 comp.generateJavaSkeletonClass();
5313                                 comp.generateJavaCallbackSkeletonClass();
5314                                 comp.generateEnumCplus();
5315                                 comp.generateStructCplus();
5316                                 comp.generateCplusLocalInterfaces();
5317                                 comp.generateCPlusInterfaces();
5318                                 comp.generateCPlusStubClasses();
5319                                 comp.generateCPlusCallbackStubClasses();
5320                                 comp.generateCplusSkeletonClass();
5321                                 comp.generateCplusCallbackSkeletonClass();
5322                         } else {
5323                         // Check other options
5324                                 while(i < args.length) {
5325                                         // Error checking
5326                                         if (!args[i].equals("-java") &&
5327                                                 !args[i].equals("-cplus")) {
5328                                                 throw new Error("IoTCompiler: ERROR - unrecognized command line option: " + args[i] + "\n");
5329                                         } else {
5330                                                 if (i + 1 < args.length) {
5331                                                         comp.setDirectory(args[i+1]);
5332                                                 } else
5333                                                         throw new Error("IoTCompiler: ERROR - please provide <directory> after option: " + args[i] + "\n");
5334
5335                                                 if (args[i].equals("-java")) {
5336                                                         comp.generateEnumJava();
5337                                                         comp.generateStructJava();
5338                                                         comp.generateJavaLocalInterfaces();
5339                                                         comp.generateJavaInterfaces();
5340                                                         comp.generateJavaStubClasses();
5341                                                         comp.generateJavaCallbackStubClasses();
5342                                                         comp.generateJavaSkeletonClass();
5343                                                         comp.generateJavaCallbackSkeletonClass();
5344                                                 } else {
5345                                                         comp.generateEnumCplus();
5346                                                         comp.generateStructCplus();
5347                                                         comp.generateCplusLocalInterfaces();
5348                                                         comp.generateCPlusInterfaces();
5349                                                         comp.generateCPlusStubClasses();
5350                                                         comp.generateCPlusCallbackStubClasses();
5351                                                         comp.generateCplusSkeletonClass();
5352                                                         comp.generateCplusCallbackSkeletonClass();
5353                                                 }
5354                                         }
5355                                         i = i + 2;
5356                                 }
5357                         }
5358                 } else {
5359                 // Need to at least have exactly 2 parameters, i.e. main policy file and requires file
5360                         IoTCompiler.printUsage();
5361                         throw new Error("IoTCompiler: At least two arguments (main and requires policy files) have to be provided!\n");
5362                 }
5363         }
5364 }
5365
5366