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