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