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