Fixing a bug in C++ socket server-client: message length was represented just in...
[iot2.git] / iotjava / iotpolicy / IoTCompiler.java
1 package iotpolicy;
2
3 import java_cup.runtime.ComplexSymbolFactory;
4 import java_cup.runtime.ScannerBuffer;
5 import java.io.*;
6 import java.util.Arrays;
7 import java.util.ArrayList;
8 import java.util.Collection;
9 import java.util.Collections;
10 import java.util.HashMap;
11 import java.util.HashSet;
12 import java.util.Iterator;
13 import java.util.List;
14 import java.util.Map;
15 import java.util.Set;
16
17 import iotpolicy.parser.Lexer;
18 import iotpolicy.parser.Parser;
19 import iotpolicy.tree.ParseNode;
20 import iotpolicy.tree.ParseNodeVector;
21 import iotpolicy.tree.ParseTreeHandler;
22 import iotpolicy.tree.Declaration;
23 import iotpolicy.tree.DeclarationHandler;
24 import iotpolicy.tree.CapabilityDecl;
25 import iotpolicy.tree.InterfaceDecl;
26 import iotpolicy.tree.RequiresDecl;
27 import iotpolicy.tree.EnumDecl;
28 import iotpolicy.tree.StructDecl;
29
30 import iotrmi.Java.IoTRMITypes;
31
32
33 /** Class IoTCompiler is the main interface/stub compiler for
34  *  files generation. This class calls helper classes
35  *  such as Parser, Lexer, InterfaceDecl, CapabilityDecl,
36  *  RequiresDecl, ParseTreeHandler, etc.
37  *
38  * @author      Rahmadi Trimananda <rahmadi.trimananda @ uci.edu>
39  * @version     1.0
40  * @since       2016-09-22
41  */
42 public class IoTCompiler {
43
44         /**
45          * Class properties
46          */
47         // Maps multiple interfaces to multiple objects of ParseTreeHandler
48         private Map<String,ParseTreeHandler> mapIntfacePTH;
49         private Map<String,DeclarationHandler> mapIntDeclHand;
50         private Map<String,Map<String,Set<String>>> mapInt2NewInts;
51         // Data structure to store our types (primitives and non-primitives) for compilation
52         private Map<String,String> mapPrimitives;
53         private Map<String,String> mapNonPrimitivesJava;
54         private Map<String,String> mapNonPrimitivesCplus;
55         // Other data structures
56         private Map<String,Integer> mapIntfaceObjId;            // Maps interface name to object Id
57         private Map<String,Integer> mapNewIntfaceObjId;         // Maps new interface name to its object Id (keep track of stubs)
58         private PrintWriter pw;
59         private String dir;
60         private String subdir;
61
62
63         /**
64          * Class constants
65          */
66         private final static String OUTPUT_DIRECTORY = "output_files";
67
68         private enum ParamCategory {
69
70                 PRIMITIVES,             // All the primitive types, e.g. byte, short, int, long, etc.
71                 NONPRIMITIVES,  // Non-primitive types, e.g. Set, Map, List, etc.
72                 ENUM,                   // Enum type
73                 STRUCT,                 // Struct type
74                 USERDEFINED             // Assumed as driver classes
75         }
76
77
78         /**
79          * Class constructors
80          */
81         public IoTCompiler() {
82
83                 mapIntfacePTH = new HashMap<String,ParseTreeHandler>();
84                 mapIntDeclHand = new HashMap<String,DeclarationHandler>();
85                 mapInt2NewInts = new HashMap<String,Map<String,Set<String>>>();
86                 mapIntfaceObjId = new HashMap<String,Integer>();
87                 mapNewIntfaceObjId = new HashMap<String,Integer>();
88                 mapPrimitives = new HashMap<String,String>();
89                         arraysToMap(mapPrimitives, IoTRMITypes.primitivesJava, IoTRMITypes.primitivesCplus);
90                 mapNonPrimitivesJava = new HashMap<String,String>();
91                         arraysToMap(mapNonPrimitivesJava, IoTRMITypes.nonPrimitivesJava, IoTRMITypes.nonPrimitiveJavaLibs);
92                 mapNonPrimitivesCplus = new HashMap<String,String>();
93                         arraysToMap(mapNonPrimitivesCplus, IoTRMITypes.nonPrimitivesJava, IoTRMITypes.nonPrimitivesCplus);
94                 pw = null;
95                 dir = OUTPUT_DIRECTORY;
96                 subdir = null;
97         }
98
99
100         /**
101          * setDataStructures() sets parse tree and other data structures based on policy files.
102          * <p>
103          * It also generates parse tree (ParseTreeHandler) and
104          * copies useful information from parse tree into
105          * InterfaceDecl, CapabilityDecl, and RequiresDecl 
106          * data structures.
107          * Additionally, the data structure handles are
108          * returned from tree-parsing for further process.
109          */
110         public void setDataStructures(String origInt, ParseNode pnPol, ParseNode pnReq) {
111
112                 ParseTreeHandler ptHandler = new ParseTreeHandler(origInt, pnPol, pnReq);
113                 DeclarationHandler decHandler = new DeclarationHandler();
114                 // Process ParseNode and generate Declaration objects
115                 // Interface
116                 ptHandler.processInterfaceDecl();
117                 InterfaceDecl intDecl = ptHandler.getInterfaceDecl();
118                 decHandler.addInterfaceDecl(origInt, intDecl);
119                 // Capabilities
120                 ptHandler.processCapabilityDecl();
121                 CapabilityDecl capDecl = ptHandler.getCapabilityDecl();
122                 decHandler.addCapabilityDecl(origInt, capDecl);
123                 // Requires
124                 ptHandler.processRequiresDecl();
125                 RequiresDecl reqDecl = ptHandler.getRequiresDecl();
126                 decHandler.addRequiresDecl(origInt, reqDecl);
127                 // Enumeration
128                 ptHandler.processEnumDecl();
129                 EnumDecl enumDecl = ptHandler.getEnumDecl();
130                 decHandler.addEnumDecl(origInt, enumDecl);
131                 // Struct
132                 ptHandler.processStructDecl();
133                 StructDecl structDecl = ptHandler.getStructDecl();
134                 decHandler.addStructDecl(origInt, structDecl);
135
136                 mapIntfacePTH.put(origInt, ptHandler);
137                 mapIntDeclHand.put(origInt, decHandler);
138                 // Set object Id counter to 0 for each interface
139                 mapIntfaceObjId.put(origInt, new Integer(0));
140         }
141
142
143         /**
144          * getMethodsForIntface() reads for methods in the data structure
145          * <p>
146          * It is going to give list of methods for a certain interface
147          *              based on the declaration of capabilities.
148          */
149         public void getMethodsForIntface(String origInt) {
150
151                 ParseTreeHandler ptHandler = mapIntfacePTH.get(origInt);
152                 Map<String,Set<String>> mapNewIntMethods = new HashMap<String,Set<String>>();
153                 // Get set of new interfaces, e.g. CameraWithCaptureAndData
154                 // Generate this new interface with all the methods it needs
155                 //              from different capabilities it declares
156                 DeclarationHandler decHandler = mapIntDeclHand.get(origInt);
157                 RequiresDecl reqDecl = (RequiresDecl) decHandler.getRequiresDecl(origInt);
158                 Set<String> setIntfaces = reqDecl.getInterfaces();
159                 for (String strInt : setIntfaces) {
160
161                         // Initialize a set of methods
162                         Set<String> setMethods = new HashSet<String>();
163                         // Get list of capabilities, e.g. ImageCapture, VideoRecording, etc.
164                         List<String> listCapab = reqDecl.getCapabList(strInt);
165                         for (String strCap : listCapab) {
166
167                                 // Get list of methods for each capability
168                                 CapabilityDecl capDecl = (CapabilityDecl) decHandler.getCapabilityDecl(origInt);
169                                 List<String> listCapabMeth = capDecl.getMethods(strCap);
170                                 for (String strMeth : listCapabMeth) {
171
172                                         // Add methods into setMethods
173                                         // This is to also handle redundancies (say two capabilities
174                                         //              share the same methods)
175                                         setMethods.add(strMeth);
176                                 }
177                         }
178                         // Add interface and methods information into map
179                         mapNewIntMethods.put(strInt, setMethods);
180                 }
181                 // Map the map of interface-methods to the original interface
182                 mapInt2NewInts.put(origInt, mapNewIntMethods);
183         }
184
185
186         /**
187          * HELPER: writeMethodJavaLocalInterface() writes the method of the local interface
188          */
189         private void writeMethodJavaLocalInterface(Collection<String> methods, InterfaceDecl intDecl) {
190
191                 for (String method : methods) {
192
193                         List<String> methParams = intDecl.getMethodParams(method);
194                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
195                         print("public " + intDecl.getMethodType(method) + " " +
196                                 intDecl.getMethodId(method) + "(");
197                         for (int i = 0; i < methParams.size(); i++) {
198                                 // Check for params with driver class types and exchange it 
199                                 //              with its remote interface
200                                 String paramType = checkAndGetParamClass(methPrmTypes.get(i));
201                                 print(paramType + " " + methParams.get(i));
202                                 // Check if this is the last element (don't print a comma)
203                                 if (i != methParams.size() - 1) {
204                                         print(", ");
205                                 }
206                         }
207                         println(");");
208                 }
209         }
210
211
212         /**
213          * HELPER: writeMethodJavaInterface() writes the method of the interface
214          */
215         private void writeMethodJavaInterface(Collection<String> methods, InterfaceDecl intDecl) {
216
217                 for (String method : methods) {
218
219                         List<String> methParams = intDecl.getMethodParams(method);
220                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
221                         print("public " + intDecl.getMethodType(method) + " " +
222                                 intDecl.getMethodId(method) + "(");
223                         for (int i = 0; i < methParams.size(); i++) {
224                                 // Check for params with driver class types and exchange it 
225                                 //              with its remote interface
226                                 String paramType = methPrmTypes.get(i);
227                                 print(paramType + " " + methParams.get(i));
228                                 // Check if this is the last element (don't print a comma)
229                                 if (i != methParams.size() - 1) {
230                                         print(", ");
231                                 }
232                         }
233                         println(");");
234                 }
235         }
236
237
238         /**
239          * HELPER: generateEnumJava() writes the enumeration declaration
240          */
241         private void generateEnumJava() throws IOException {
242
243                 // Create a new directory
244                 createDirectory(dir);
245                 for (String intface : mapIntfacePTH.keySet()) {
246                         // Get the right EnumDecl
247                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
248                         EnumDecl enumDecl = (EnumDecl) decHandler.getEnumDecl(intface);
249                         Set<String> enumTypes = enumDecl.getEnumDeclarations();
250                         // Iterate over enum declarations
251                         for (String enType : enumTypes) {
252                                 // Open a new file to write into
253                                 FileWriter fw = new FileWriter(dir + "/" + enType + ".java");
254                                 pw = new PrintWriter(new BufferedWriter(fw));
255                                 println("public enum " + enType + " {");
256                                 List<String> enumMembers = enumDecl.getMembers(enType);
257                                 for (int i = 0; i < enumMembers.size(); i++) {
258
259                                         String member = enumMembers.get(i);
260                                         print(member);
261                                         // Check if this is the last element (don't print a comma)
262                                         if (i != enumMembers.size() - 1)
263                                                 println(",");
264                                         else
265                                                 println("");
266                                 }
267                                 println("}\n");
268                                 pw.close();
269                                 System.out.println("IoTCompiler: Generated enum class " + enType + ".java...");
270                         }
271                 }
272         }
273
274
275         /**
276          * HELPER: generateStructJava() writes the struct declaration
277          */
278         private void generateStructJava() throws IOException {
279
280                 // Create a new directory
281                 createDirectory(dir);
282                 for (String intface : mapIntfacePTH.keySet()) {
283                         // Get the right StructDecl
284                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
285                         StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
286                         List<String> structTypes = structDecl.getStructTypes();
287                         // Iterate over enum declarations
288                         for (String stType : structTypes) {
289                                 // Open a new file to write into
290                                 FileWriter fw = new FileWriter(dir + "/" + stType + ".java");
291                                 pw = new PrintWriter(new BufferedWriter(fw));
292                                 println("public class " + stType + " {");
293                                 List<String> structMemberTypes = structDecl.getMemberTypes(stType);
294                                 List<String> structMembers = structDecl.getMembers(stType);
295                                 for (int i = 0; i < structMembers.size(); i++) {
296
297                                         String memberType = structMemberTypes.get(i);
298                                         String member = structMembers.get(i);
299                                         println("public static " + memberType + " " + member + ";");
300                                 }
301                                 println("}\n");
302                                 pw.close();
303                                 System.out.println("IoTCompiler: Generated struct class " + stType + ".java...");
304                         }
305                 }
306         }
307
308
309         /**
310          * generateJavaLocalInterface() writes the local interface and provides type-checking.
311          * <p>
312          * It needs to rewrite and exchange USERDEFINED types in input parameters of stub
313          * and original interfaces, e.g. exchange Camera and CameraWithVideoAndRecording.
314          * The local interface has to be the input parameter for the stub and the stub 
315          * interface has to be the input parameter for the local class.
316          */
317         public void generateJavaLocalInterfaces() throws IOException {
318
319                 // Create a new directory
320                 createDirectory(dir);
321                 for (String intface : mapIntfacePTH.keySet()) {
322                         // Open a new file to write into
323                         FileWriter fw = new FileWriter(dir + "/" + intface + ".java");
324                         pw = new PrintWriter(new BufferedWriter(fw));
325                         // Pass in set of methods and get import classes
326                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
327                         InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
328                         List<String> methods = intDecl.getMethods();
329                         Set<String> importClasses = getImportClasses(methods, intDecl);
330                         List<String> stdImportClasses = getStandardJavaIntfaceImportClasses();
331                         List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
332                         printImportStatements(allImportClasses);
333                         // Write interface header
334                         println("");
335                         println("public interface " + intface + " {");
336                         // Write methods
337                         writeMethodJavaLocalInterface(methods, intDecl);
338                         println("}");
339                         pw.close();
340                         System.out.println("IoTCompiler: Generated local interface " + intface + ".java...");
341                 }
342         }
343
344
345         /**
346          * generateJavaInterfaces() generate stub interfaces based on the methods list in Java
347          */
348         public void generateJavaInterfaces() throws IOException {
349
350                 // Create a new directory
351                 String path = createDirectories(dir, subdir);
352                 for (String intface : mapIntfacePTH.keySet()) {
353
354                         Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
355                         for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
356
357                                 // Open a new file to write into
358                                 String newIntface = intMeth.getKey();
359                                 FileWriter fw = new FileWriter(path + "/" + newIntface + ".java");
360                                 pw = new PrintWriter(new BufferedWriter(fw));
361                                 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
362                                 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
363                                 // Pass in set of methods and get import classes
364                                 List<String> methods = intDecl.getMethods();
365                                 Set<String> importClasses = getImportClasses(methods, intDecl);
366                                 List<String> stdImportClasses = getStandardJavaIntfaceImportClasses();
367                                 List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
368                                 printImportStatements(allImportClasses);
369                                 // Write interface header
370                                 println("");
371                                 println("public interface " + newIntface + " {\n");
372                                 // Write methods
373                                 writeMethodJavaInterface(methods, intDecl);
374                                 println("}");
375                                 pw.close();
376                                 System.out.println("IoTCompiler: Generated interface " + newIntface + ".java...");
377                         }
378                 }
379         }
380
381
382         /**
383          * HELPER: writePropertiesJavaPermission() writes the permission in properties
384          */
385         private void writePropertiesJavaPermission(String intface, InterfaceDecl intDecl) {
386
387                 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
388                 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
389                         String newIntface = intMeth.getKey();
390                         int newObjectId = getNewIntfaceObjectId(newIntface);
391                         println("private final static int object" + newObjectId + "Id = " + 
392                                 newObjectId + ";\t//" + newIntface);
393                         Set<String> methodIds = intMeth.getValue();
394                         print("private static Integer[] object" + newObjectId + "Permission = { ");
395                         int i = 0;
396                         for (String methodId : methodIds) {
397                                 int methodNumId = intDecl.getMethodNumId(methodId);
398                                 print(Integer.toString(methodNumId));
399                                 // Check if this is the last element (don't print a comma)
400                                 if (i != methodIds.size() - 1) {
401                                         print(", ");
402                                 }
403                                 i++;
404                         }
405                         println(" };");
406                         println("private static List<Integer> set" + newObjectId + "Allowed;");
407                 }
408         }
409
410
411         /**
412          * HELPER: writePropertiesJavaStub() writes the properties of the stub class
413          */
414         private void writePropertiesJavaStub(String intface, String newIntface, boolean callbackExist, Set<String> callbackClasses) {
415
416                 println("private IoTRMICall rmiCall;");
417                 println("private String address;");
418                 println("private int[] ports;\n");
419                 // Get the object Id
420                 Integer objId = mapIntfaceObjId.get(intface);
421                 println("private final static int objectId = " + objId + ";");
422                 mapNewIntfaceObjId.put(newIntface, objId);
423                 mapIntfaceObjId.put(intface, objId++);
424                 if (callbackExist) {
425                 // We assume that each class only has one callback interface for now
426                         Iterator it = callbackClasses.iterator();
427                         String callbackType = (String) it.next();
428                         println("// Callback properties");
429                         println("private IoTRMIObject rmiObj;");
430                         println("List<" + callbackType + "> listCallbackObj;");
431                         println("private static int objIdCnt = 0;");
432                         // Generate permission stuff for callback stubs
433                         DeclarationHandler decHandler = mapIntDeclHand.get(callbackType);
434                         InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(callbackType);
435                         writePropertiesJavaPermission(callbackType, intDecl);
436                 }
437                 println("\n");
438         }
439
440
441         /**
442          * HELPER: writeConstructorJavaPermission() writes the permission in constructor
443          */
444         private void writeConstructorJavaPermission(String intface) {
445
446                 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
447                 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
448                         String newIntface = intMeth.getKey();
449                         int newObjectId = getNewIntfaceObjectId(newIntface);
450                         println("set" + newObjectId + "Allowed = new ArrayList<Integer>(Arrays.asList(object" + newObjectId +"Permission));");
451                 }
452         }
453
454
455         /**
456          * HELPER: writeConstructorJavaStub() writes the constructor of the stub class
457          */
458         private void writeConstructorJavaStub(String intface, String newStubClass, boolean callbackExist, Set<String> callbackClasses) {
459
460                 println("public " + newStubClass + "(int _port, String _address, int _rev, int[] _ports) throws Exception {");
461                 println("address = _address;");
462                 println("ports = _ports;");
463                 println("rmiCall = new IoTRMICall(_port, _address, _rev);");
464                 if (callbackExist) {
465                         Iterator it = callbackClasses.iterator();
466                         String callbackType = (String) it.next();
467                         writeConstructorJavaPermission(intface);
468                         println("listCallbackObj = new ArrayList<" + callbackType + ">();");
469                         println("___initCallBack();");
470                 }
471                 println("}\n");
472         }
473
474
475         /**
476          * HELPER: writeJavaMethodCallbackPermission() writes permission checks in stub for callbacks
477          */
478         private void writeJavaMethodCallbackPermission(String intface) {
479
480                 println("int methodId = IoTRMIObject.getMethodId(method);");
481                 // Get all the different stubs
482                 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
483                 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
484                         String newIntface = intMeth.getKey();
485                         int newObjectId = getNewIntfaceObjectId(newIntface);
486                         println("if (!set" + newObjectId + "Allowed.contains(methodId)) {");
487                         println("throw new Error(\"Callback object for " + intface + " is not allowed to access method: \" + methodId);");
488                         println("}");
489                 }
490         }
491
492
493         /**
494          * HELPER: writeJavaInitCallbackPermission() writes the permission for callback
495          */
496         private void writeJavaInitCallbackPermission(String intface, InterfaceDecl intDecl, boolean callbackExist) {
497
498                 if (callbackExist) {
499                         String method = "___initCallBack()";
500                         int methodNumId = intDecl.getHelperMethodNumId(method);
501                         Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
502                         for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
503                                 String newIntface = intMeth.getKey();
504                                 int newObjectId = getNewIntfaceObjectId(newIntface);
505                                 println("set" + newObjectId + "Allowed.add(" + methodNumId + ");");
506                         }
507                 }
508         }
509
510
511         /**
512          * HELPER: writeInitCallbackJavaStub() writes callback initialization in stub
513          */
514         private void writeInitCallbackJavaStub(String intface, InterfaceDecl intDecl) {
515
516                 println("public void ___initCallBack() {");
517                 // Generate main thread for callbacks
518                 println("Thread thread = new Thread() {");
519                 println("public void run() {");
520                 println("try {");
521                 println("rmiObj = new IoTRMIObject(ports[0]);");
522                 println("while (true) {");
523                 println("byte[] method = rmiObj.getMethodBytes();");
524                 writeJavaMethodCallbackPermission(intface);
525                 println("int objId = IoTRMIObject.getObjectId(method);");
526                 println(intface + "_CallbackSkeleton skel = (" + intface + "_CallbackSkeleton) listCallbackObj.get(objId);");
527                 println("if (skel != null) {");
528                 println("skel.invokeMethod(rmiObj);");
529                 print("}");
530                 println(" else {");
531                 println("throw new Error(\"" + intface + ": Object with Id \" + objId + \" not found!\");");
532                 println("}");
533                 println("}");
534                 print("}");
535                 println(" catch (Exception ex) {");
536                 println("ex.printStackTrace();");
537                 println("throw new Error(\"Error instantiating class " + intface + "_CallbackSkeleton!\");");
538                 println("}");
539                 println("}");
540                 println("};");
541                 println("thread.start();\n");
542                 // Generate info sending part
543                 String method = "___initCallBack()";
544                 int methodNumId = intDecl.getHelperMethodNumId(method);
545                 println("int methodId = " + methodNumId + ";");
546                 println("Class<?> retType = void.class;");
547                 println("Class<?>[] paramCls = new Class<?>[] { int.class, String.class, int.class };");
548                 println("Object[] paramObj = new Object[] { ports[0], address, 0 };");
549                 println("rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
550                 println("}\n");
551         }
552
553
554         /**
555          * HELPER: checkAndWriteEnumTypeJavaStub() writes the enum type (convert from enum to int)
556          */
557         private void checkAndWriteEnumTypeJavaStub(List<String> methParams, List<String> methPrmTypes) {
558
559                 // Iterate and find enum declarations
560                 for (int i = 0; i < methParams.size(); i++) {
561                         String paramType = methPrmTypes.get(i);
562                         String param = methParams.get(i);
563                         String simpleType = getGenericType(paramType);
564                         if (isEnumClass(simpleType)) {
565                         // Check if this is enum type
566                                 if (isArray(param)) {   // An array
567                                         println("int len" + i + " = " + getSimpleIdentifier(param) + ".length;");
568                                         println("int paramEnum" + i + "[] = new int[len" + i + "];");
569                                         println("for (int i = 0; i < len" + i + "; i++) {");
570                                         println("paramEnum" + i + "[i] = " + getSimpleIdentifier(param) + "[i].ordinal();");
571                                         println("}");
572                                 } else if (isList(paramType)) { // A list
573                                         println("int len" + i + " = " + getSimpleIdentifier(param) + ".size();");
574                                         println("int paramEnum" + i + "[] = new int[len" + i + "];");
575                                         println("for (int i = 0; i < len" + i + "; i++) {");
576                                         println("paramEnum" + i + "[i] = " + getSimpleIdentifier(param) + ".get(i).ordinal();");
577                                         println("}");
578                                 } else {        // Just one element
579                                         println("int paramEnum" + i + "[] = new int[1];");
580                                         println("paramEnum" + i + "[0] = " + param + ".ordinal();");
581                                 }
582                         }
583                 }
584         }
585
586
587         /**
588          * HELPER: checkAndWriteEnumRetTypeJavaStub() writes the enum return type (convert from enum to int)
589          */
590         private void checkAndWriteEnumRetTypeJavaStub(String retType) {
591
592                 // Strips off array "[]" for return type
593                 String pureType = getSimpleArrayType(getGenericType(retType));
594                 // Take the inner type of generic
595                 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
596                         pureType = getGenericType(retType);
597                 if (isEnumClass(pureType)) {
598                 // Check if this is enum type
599                         // Enum decoder
600                         println("int[] retEnum = (int[]) retObj;");
601                         println(pureType + "[] enumVals = " + pureType + ".values();");
602                         if (isArray(retType)) {                 // An array
603                                 println("int retLen = retEnum.length;");
604                                 println(pureType + "[] enumRetVal = new " + pureType + "[retLen];");
605                                 println("for (int i = 0; i < retLen; i++) {");
606                                 println("enumRetVal[i] = enumVals[retEnum[i]];");
607                                 println("}");
608                         } else if (isList(retType)) {   // A list
609                                 println("int retLen = retEnum.length;");
610                                 println("List<" + pureType + "> enumRetVal = new ArrayList<" + pureType + ">();");
611                                 println("for (int i = 0; i < retLen; i++) {");
612                                 println("enumRetVal.add(enumVals[retEnum[i]]);");
613                                 println("}");
614                         } else {        // Just one element
615                                 println(pureType + " enumRetVal = enumVals[retEnum[0]];");
616                         }
617                         println("return enumRetVal;");
618                 }
619         }
620
621
622         /**
623          * HELPER: checkAndWriteStructSetupJavaStub() writes the struct type setup
624          */
625         private void checkAndWriteStructSetupJavaStub(List<String> methParams, List<String> methPrmTypes, 
626                         InterfaceDecl intDecl, String method) {
627                 
628                 // Iterate and find struct declarations
629                 for (int i = 0; i < methParams.size(); i++) {
630                         String paramType = methPrmTypes.get(i);
631                         String param = methParams.get(i);
632                         String simpleType = getGenericType(paramType);
633                         if (isStructClass(simpleType)) {
634                         // Check if this is enum type
635                                 int methodNumId = intDecl.getMethodNumId(method);
636                                 String helperMethod = methodNumId + "struct" + i;
637                                 println("int methodIdStruct" + i + " = " + intDecl.getHelperMethodNumId(helperMethod) + ";");
638                                 println("Class<?> retTypeStruct" + i + " = void.class;");
639                                 println("Class<?>[] paramClsStruct" + i + " = new Class<?>[] { int.class };");
640                                 if (isArray(param)) {   // An array
641                                         println("Object[] paramObjStruct" + i + " = new Object[] { " + getSimpleArrayType(param) + ".length };");
642                                 } else if (isList(paramType)) { // A list
643                                         println("Object[] paramObjStruct" + i + " = new Object[] { " + getSimpleArrayType(param) + ".size() };");
644                                 } else {        // Just one element
645                                         println("Object[] paramObjStruct" + i + " = new Object[] { new Integer(1) };");
646                                 }
647                                 println("rmiCall.remoteCall(objectId, methodIdStruct" + i + 
648                                                 ", retTypeStruct" + i + ", null, paramClsStruct" + i + 
649                                                 ", paramObjStruct" + i + ");\n");
650                         }
651                 }
652         }
653
654
655         /**
656          * HELPER: isStructPresent() checks presence of struct
657          */
658         private boolean isStructPresent(List<String> methParams, List<String> methPrmTypes) {
659
660                 // Iterate and find enum declarations
661                 for (int i = 0; i < methParams.size(); i++) {
662                         String paramType = methPrmTypes.get(i);
663                         String param = methParams.get(i);
664                         String simpleType = getGenericType(paramType);
665                         if (isStructClass(simpleType))
666                                 return true;
667                 }
668                 return false;
669         }
670
671
672         /**
673          * HELPER: writeLengthStructParamClassJavaStub() writes lengths of parameters
674          */
675         private void writeLengthStructParamClassJavaStub(List<String> methParams, List<String> methPrmTypes) {
676
677                 // Iterate and find struct declarations - count number of params
678                 for (int i = 0; i < methParams.size(); i++) {
679                         String paramType = methPrmTypes.get(i);
680                         String param = methParams.get(i);
681                         String simpleType = getGenericType(paramType);
682                         if (isStructClass(simpleType)) {
683                                 int members = getNumOfMembers(simpleType);
684                                 if (isArray(param)) {                   // An array
685                                         String structLen = getSimpleArrayType(param) + ".length";
686                                         print(members + "*" + structLen);
687                                 } else if (isList(paramType)) { // A list
688                                         String structLen = getSimpleArrayType(param) + ".size()";
689                                         print(members + "*" + structLen);
690                                 } else
691                                         print(Integer.toString(members));
692                         } else
693                                 print("1");
694                         if (i != methParams.size() - 1) {
695                                 print("+");
696                         }
697                 }
698         }
699
700
701         /**
702          * HELPER: writeStructMembersJavaStub() writes parameters of struct
703          */
704         private void writeStructMembersJavaStub(String simpleType, String paramType, String param) {
705
706                 // Get the struct declaration for this struct and generate initialization code
707                 StructDecl structDecl = getStructDecl(simpleType);
708                 List<String> memTypes = structDecl.getMemberTypes(simpleType);
709                 List<String> members = structDecl.getMembers(simpleType);
710                 if (isArray(param)) {                   // An array
711                         println("for(int i = 0; i < " + getSimpleIdentifier(param) + ".length; i++) {");
712                         for (int i = 0; i < members.size(); i++) {
713                                 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
714                                 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
715                                 print("paramObj[pos++] = " + getSimpleIdentifier(param) + "[i].");
716                                 print(getSimpleIdentifier(members.get(i)));
717                                 println(";");
718                         }
719                         println("}");
720                 } else if (isList(paramType)) { // A list
721                         println("for(int i = 0; i < " + getSimpleIdentifier(param) + ".size(); i++) {");
722                         for (int i = 0; i < members.size(); i++) {
723                                 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
724                                 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
725                                 print("paramObj[pos++] = " + getSimpleIdentifier(param) + ".get(i).");
726                                 print(getSimpleIdentifier(members.get(i)));
727                                 println(";");
728                         }
729                         println("}");
730                 } else {        // Just one struct element
731                         for (int i = 0; i < members.size(); i++) {
732                                 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
733                                 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
734                                 print("paramObj[pos++] = " + getSimpleIdentifier(param) + ".");
735                                 print(getSimpleIdentifier(members.get(i)));
736                                 println(";");
737                         }
738                 }
739         }
740
741
742         /**
743          * HELPER: writeStructParamClassJavaStub() writes parameters if struct is present
744          */
745         private void writeStructParamClassJavaStub(List<String> methParams, List<String> methPrmTypes, String callbackType) {
746
747                 print("int paramLen = ");
748                 writeLengthStructParamClassJavaStub(methParams, methPrmTypes);
749                 println(";");
750                 println("Object[] paramObj = new Object[paramLen];");
751                 println("Class<?>[] paramCls = new Class<?>[paramLen];");
752                 println("int pos = 0;");
753                 // Iterate again over the parameters
754                 for (int i = 0; i < methParams.size(); i++) {
755                         String paramType = methPrmTypes.get(i);
756                         String param = methParams.get(i);
757                         String simpleType = getGenericType(paramType);
758                         if (isStructClass(simpleType)) {
759                                 writeStructMembersJavaStub(simpleType, paramType, param);
760                         } else if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
761                                 println("paramCls[pos] = int.class;");
762                                 print("paramObj[pos++] = ");
763                                 if (isArray(methParams.get(i)))
764                                         print(getSimpleIdentifier(methParams.get(i)) + ".length");
765                                 else if (isList(methPrmTypes.get(i)))
766                                         print(getSimpleIdentifier(methParams.get(i)) + ".size()");
767                                 else
768                                         print("new Integer(1)");
769                                 println(";");
770                         } else {
771                                 String prmType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
772                                 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
773                                 print("paramObj[pos++] = ");
774                                 print(getEnumParam(methPrmTypes.get(i), getSimpleIdentifier(methParams.get(i)), i));
775                                 println(";");
776                         }
777                 }
778                 
779         }
780
781
782         /**
783          * HELPER: writeStructRetMembersJavaStub() writes parameters of struct for return statement
784          */
785         private void writeStructRetMembersJavaStub(String simpleType, String retType) {
786
787                 // Get the struct declaration for this struct and generate initialization code
788                 StructDecl structDecl = getStructDecl(simpleType);
789                 List<String> memTypes = structDecl.getMemberTypes(simpleType);
790                 List<String> members = structDecl.getMembers(simpleType);
791                 if (isArrayOrList(retType, retType)) {  // An array or list
792                         println("for(int i = 0; i < retLen; i++) {");
793                 }
794                 if (isArray(retType)) { // An array
795                         for (int i = 0; i < members.size(); i++) {
796                                 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
797                                 print("structRet[i]." + getSimpleIdentifier(members.get(i)));
798                                 println(" = (" + getSimpleType(getEnumType(prmType)) + ") retObj[retObjPos++];");
799                         }
800                         println("}");
801                 } else if (isList(retType)) {   // A list
802                         println(simpleType + " structRetMem = new " + simpleType + "();");
803                         for (int i = 0; i < members.size(); i++) {
804                                 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
805                                 print("structRetMem." + getSimpleIdentifier(members.get(i)));
806                                 println(" = (" + getSimpleType(getEnumType(prmType)) + ") retObj[retObjPos++];");
807                         }
808                         println("structRet.add(structRetMem);");
809                         println("}");
810                 } else {        // Just one struct element
811                         for (int i = 0; i < members.size(); i++) {
812                                 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
813                                 print("structRet." + getSimpleIdentifier(members.get(i)));
814                                 println(" = (" + getSimpleType(getEnumType(prmType)) + ") retObj[retObjPos++];");
815                         }
816                 }
817                 println("return structRet;");
818         }
819
820
821         /**
822          * HELPER: writeStructReturnJavaStub() writes parameters if struct is present for return statement
823          */
824         private void writeStructReturnJavaStub(String simpleType, String retType) {
825
826                 // Handle the returned struct!!!
827                 println("Object retLenObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
828                 // Minimum retLen is 1 if this is a single struct object
829                 println("int retLen = (int) retLenObj;");
830                 int numMem = getNumOfMembers(simpleType);
831                 println("Class<?>[] retCls = new Class<?>[" + numMem + "*retLen];");
832                 println("Class<?>[] retClsVal = new Class<?>[" + numMem + "*retLen];");
833                 println("int retPos = 0;");
834                 // Get the struct declaration for this struct and generate initialization code
835                 StructDecl structDecl = getStructDecl(simpleType);
836                 List<String> memTypes = structDecl.getMemberTypes(simpleType);
837                 List<String> members = structDecl.getMembers(simpleType);
838                 if (isArrayOrList(retType, retType)) {  // An array or list
839                         println("for(int i = 0; i < retLen; i++) {");
840                         for (int i = 0; i < members.size(); i++) {
841                                 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
842                                 println("retCls[retPos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
843                                 println("retClsVal[retPos++] = null;");
844                         }
845                         println("}");
846                 } else {        // Just one struct element
847                         for (int i = 0; i < members.size(); i++) {
848                                 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
849                                 println("retCls[retPos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
850                                 println("retClsVal[retPos++] = null;");
851                         }
852                 }
853                 println("Object[] retObj = rmiCall.getStructObjects(retCls, retClsVal);");
854                 if (isArray(retType)) {                 // An array
855                         println(simpleType + "[] structRet = new " + simpleType + "[retLen];");
856                         println("for(int i = 0; i < retLen; i++) {");
857                         println("structRet[i] = new " + simpleType + "();");
858                         println("}");
859                 } else if (isList(retType)) {   // A list
860                         println("List<" + simpleType + "> structRet = new ArrayList<" + simpleType + ">();");
861                 } else
862                         println(simpleType + " structRet = new " + simpleType + "();");
863                 println("int retObjPos = 0;");
864                 writeStructRetMembersJavaStub(simpleType, retType);
865         }
866
867
868         /**
869          * HELPER: writeStdMethodBodyJavaStub() writes the standard method body in the stub class
870          */
871         private void writeStdMethodBodyJavaStub(InterfaceDecl intDecl, List<String> methParams,
872                         List<String> methPrmTypes, String method, String callbackType) {
873
874                 checkAndWriteStructSetupJavaStub(methParams, methPrmTypes, intDecl, method);
875                 println("int methodId = " + intDecl.getMethodNumId(method) + ";");
876                 String retType = intDecl.getMethodType(method);
877                 println("Class<?> retType = " + getSimpleType(getStructType(getEnumType(retType))) + ".class;");
878                 checkAndWriteEnumTypeJavaStub(methParams, methPrmTypes);
879                 // Generate array of parameter types
880                 if (isStructPresent(methParams, methPrmTypes)) {
881                         writeStructParamClassJavaStub(methParams, methPrmTypes, callbackType);
882                 } else {
883                         print("Class<?>[] paramCls = new Class<?>[] { ");
884                         for (int i = 0; i < methParams.size(); i++) {
885                                 String prmType = methPrmTypes.get(i);
886                                 if (checkCallbackType(prmType, callbackType)) { // Check if this has callback object
887                                         print("int.class");
888                                 } else { // Generate normal classes if it's not a callback object
889                                         String paramType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
890                                         print(getSimpleType(getEnumType(paramType)) + ".class");
891                                 }
892                                 // Check if this is the last element (don't print a comma)
893                                 if (i != methParams.size() - 1) {
894                                         print(", ");
895                                 }
896                         }
897                         println(" };");
898                         // Generate array of parameter objects
899                         print("Object[] paramObj = new Object[] { ");
900                         for (int i = 0; i < methParams.size(); i++) {
901                                 String paramType = methPrmTypes.get(i);
902                                 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
903                                         //if (isArray(methPrmTypes.get(i), methParams.get(i)))
904                                         if (isArray(methParams.get(i)))
905                                                 print(getSimpleIdentifier(methParams.get(i)) + ".length");
906                                         else if (isList(methPrmTypes.get(i)))
907                                                 print(getSimpleIdentifier(methParams.get(i)) + ".size()");
908                                         else
909                                                 print("new Integer(1)");
910                                 } else
911                                         print(getEnumParam(methPrmTypes.get(i), getSimpleIdentifier(methParams.get(i)), i));
912                                 // Check if this is the last element (don't print a comma)
913                                 if (i != methParams.size() - 1) {
914                                         print(", ");
915                                 }
916                         }
917                         println(" };");
918                 }
919                 // Check if this is "void"
920                 if (retType.equals("void")) {
921                         println("rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
922                 } else { // We do have a return value
923                         // Generate array of parameter types
924                         if (isStructClass(getGenericType(getSimpleArrayType(retType)))) {
925                                 writeStructReturnJavaStub(getGenericType(getSimpleArrayType(retType)), retType);
926                         } else {
927                                 // This is an enum type
928                                 if (getParamCategory(getGenericType(getSimpleArrayType(retType))) == ParamCategory.ENUM) {
929                                         println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
930                                         checkAndWriteEnumRetTypeJavaStub(retType);
931                                 } else if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES) {
932                                 // Check if the return value NONPRIMITIVES
933                                         String retGenValType = getGenericType(retType);
934                                         println("Class<?> retGenValType = " + retGenValType + ".class;");
935                                         println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, retGenValType, paramCls, paramObj);");
936                                         println("return (" + retType + ")retObj;");
937                                 } else {
938                                         println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
939                                         println("return (" + retType + ")retObj;");
940                                 }
941                         }
942                 }
943         }
944
945
946         /**
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("IoTRMIObject\t\t\t*rmiObj;");
3088                 println("string address;");
3089                 println("vector<int> ports;\n");
3090                 // Get the object Id
3091                 Integer objId = mapIntfaceObjId.get(intface);
3092                 println("const static int objectId = " + objId + ";");
3093                 mapNewIntfaceObjId.put(newIntface, objId);
3094                 mapIntfaceObjId.put(intface, objId++);
3095                 if (callbackExist) {
3096                 // We assume that each class only has one callback interface for now
3097                         Iterator it = callbackClasses.iterator();
3098                         String callbackType = (String) it.next();
3099                         println("// Callback properties");
3100                         println("IoTRMIObject *rmiObj;");
3101                         println("vector<" + callbackType + "*> vecCallbackObj;");
3102                         println("static int objIdCnt;");
3103                         // Generate permission stuff for callback stubs
3104                         writePropertiesCplusPermission(callbackType);
3105                 }
3106                 println("\n");
3107         }
3108
3109
3110         /**
3111          * HELPER: writeConstructorCplusStub() writes the constructor of the stub class
3112          */
3113         private void writeConstructorCplusStub(String newStubClass, boolean callbackExist, Set<String> callbackClasses) {
3114
3115                 println(newStubClass + 
3116                         "(int _port, const char* _address, int _rev, bool* _bResult, vector<int> _ports) {");
3117                 println("address = _address;");
3118                 println("ports = _ports;");
3119                 println("rmiCall = new IoTRMICall(_port, _address, _rev, _bResult);");
3120                 if (callbackExist) {
3121                         Iterator it = callbackClasses.iterator();
3122                         String callbackType = (String) it.next();
3123                         println("thread th1 (&" + newStubClass + "::___initCallBack, this);");
3124                         println("th1.detach();");
3125                         println("___regCB();");
3126                 }
3127                 println("}\n");
3128         }
3129
3130
3131         /**
3132          * HELPER: writeDeconstructorCplusStub() writes the deconstructor of the stub class
3133          */
3134         private void writeDeconstructorCplusStub(String newStubClass, boolean callbackExist, Set<String> callbackClasses) {
3135
3136                 println("~" + newStubClass + "() {");
3137                 println("if (rmiCall != NULL) {");
3138                 println("delete rmiCall;");
3139                 println("rmiCall = NULL;");
3140                 println("}");
3141                 if (callbackExist) {
3142                 // We assume that each class only has one callback interface for now
3143                         println("if (rmiObj != NULL) {");
3144                         println("delete rmiObj;");
3145                         println("rmiObj = NULL;");
3146                         println("}");
3147                         Iterator it = callbackClasses.iterator();
3148                         String callbackType = (String) it.next();
3149                         println("for(" + callbackType + "* cb : vecCallbackObj) {");
3150                         println("delete cb;");
3151                         println("cb = NULL;");
3152                         println("}");
3153                 }
3154                 println("}");
3155                 println("");
3156         }
3157
3158
3159         /**
3160          * HELPER: writeCplusMethodCallbackPermission() writes permission checks in stub for callbacks
3161          */
3162         private void writeCplusMethodCallbackPermission(String intface) {
3163
3164                 println("int methodId = IoTRMIObject::getMethodId(method);");
3165                 // Get all the different stubs
3166                 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3167                 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3168                         String newIntface = intMeth.getKey();
3169                         int newObjectId = getNewIntfaceObjectId(newIntface);
3170                         println("if (set" + newObjectId + "Allowed.find(methodId) == set" + newObjectId + "Allowed.end()) {");
3171                         println("cerr << \"Callback object for " + intface + " is not allowed to access method: \" << methodId;");
3172                         println("return;");
3173                         println("}");
3174                 }
3175         }
3176
3177
3178         /**
3179          * HELPER: writeInitCallbackCplusStub() writes the initialization of callback
3180          */
3181         private void writeInitCallbackCplusStub(String intface, InterfaceDecl intDecl) {
3182
3183                 println("void ___initCallBack() {");
3184                 println("bool bResult = false;");
3185                 println("rmiObj = new IoTRMIObject(ports[0], &bResult);");
3186                 println("while (true) {");
3187                 println("char* method = rmiObj->getMethodBytes();");
3188                 writeCplusMethodCallbackPermission(intface);
3189                 println("int objId = IoTRMIObject::getObjectId(method);");
3190                 println("if (objId < vecCallbackObj.size()) {   // Check if still within range");
3191                 println(intface + "_CallbackSkeleton* skel = dynamic_cast<" + intface + 
3192                         "_CallbackSkeleton*> (vecCallbackObj.at(objId));");
3193                 println("skel->invokeMethod(rmiObj);");
3194                 print("}");
3195                 println(" else {");
3196                 println("cerr << \"Illegal object Id: \" << to_string(objId);");
3197                 // TODO: perhaps need to change this into "throw" to make it cleaner (allow stack unfolding)
3198                 println("return;");
3199                 println("}");
3200                 println("}");
3201                 println("}\n");
3202         }
3203
3204
3205         /**
3206          * HELPER: writeCplusInitCallbackPermission() writes the permission for callback
3207          */
3208         private void writeCplusInitCallbackPermission(String intface, InterfaceDecl intDecl, boolean callbackExist) {
3209
3210                 if (callbackExist) {
3211                         String method = "___initCallBack()";
3212                         int methodNumId = intDecl.getHelperMethodNumId(method);
3213                         Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3214                         for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3215                                 String newIntface = intMeth.getKey();
3216                                 int newObjectId = getNewIntfaceObjectId(newIntface);
3217                                 println("set" + newObjectId + "Allowed.insert(" + methodNumId + ");");
3218                         }
3219                 }
3220         }
3221
3222
3223         /**
3224          * HELPER: writeInitCallbackSendInfoCplusStub() writes the initialization (send info part) of callback
3225          */
3226         private void writeInitCallbackSendInfoCplusStub(InterfaceDecl intDecl) {
3227
3228                 // Generate info sending part
3229                 println("void ___regCB() {");
3230                 println("int numParam = 3;");
3231                 String method = "___initCallBack()";
3232                 int methodNumId = intDecl.getHelperMethodNumId(method);
3233                 println("int methodId = " + methodNumId + ";");
3234                 //writeCplusCallbackPermission(intface, methodNumId);
3235                 println("string retType = \"void\";");
3236                 println("string paramCls[] = { \"int\", \"String\", \"int\" };");
3237                 println("int rev = 0;");
3238                 println("void* paramObj[] = { &ports[0], &address, &rev };");
3239                 println("void* retObj = NULL;");
3240                 println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
3241                 println("}\n");
3242         }
3243
3244
3245         /**
3246          * generateCPlusStubClasses() generate stubs based on the methods list in C++
3247          */
3248         public void generateCPlusStubClasses() throws IOException {
3249
3250                 // Create a new directory
3251                 String path = createDirectories(dir, subdir);
3252                 for (String intface : mapIntfacePTH.keySet()) {
3253
3254                         Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3255                         for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3256                                 // Open a new file to write into
3257                                 String newIntface = intMeth.getKey();
3258                                 String newStubClass = newIntface + "_Stub";
3259                                 FileWriter fw = new FileWriter(path + "/" + newStubClass + ".hpp");
3260                                 pw = new PrintWriter(new BufferedWriter(fw));
3261                                 // Write file headers
3262                                 println("#ifndef _" + newStubClass.toUpperCase() + "_HPP__");
3263                                 println("#define _" + newStubClass.toUpperCase() + "_HPP__");
3264                                 println("#include <iostream>");
3265                                 // Find out if there are callback objects
3266                                 Set<String> methods = intMeth.getValue();
3267                                 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
3268                                 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
3269                                 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
3270                                 boolean callbackExist = !callbackClasses.isEmpty();
3271                                 if (callbackExist)      // Need thread library if this has callback
3272                                         println("#include <thread>");
3273                                 println("#include \"" + newIntface + ".hpp\""); println("");            
3274                                 println("using namespace std;"); println("");
3275                                 println("class " + newStubClass + " : public " + newIntface); println("{");
3276                                 println("private:\n");
3277                                 writePropertiesCplusStub(intface, newIntface, callbackExist, callbackClasses);
3278                                 println("public:\n");
3279                                 // Add default constructor and destructor
3280                                 println(newStubClass + "() { }"); println("");
3281                                 writeConstructorCplusStub(newStubClass, callbackExist, callbackClasses);
3282                                 writeDeconstructorCplusStub(newStubClass, callbackExist, callbackClasses);
3283                                 // Write methods
3284                                 writeMethodCplusStub(methods, intDecl, callbackClasses);
3285                                 print("}"); println(";");
3286                                 if (callbackExist) {
3287                                         Iterator it = callbackClasses.iterator();
3288                                         String callbackType = (String) it.next();
3289                                         // Generate permission stuff for callback stubs
3290                                         DeclarationHandler decHandlerCallback = mapIntDeclHand.get(callbackType);
3291                                         InterfaceDecl intDeclCallback = (InterfaceDecl) decHandlerCallback.getInterfaceDecl(callbackType);
3292                                         writePermissionInitializationCplus(callbackType, newStubClass, intDeclCallback);
3293                                 }
3294                                 writeObjectIdCountInitializationCplus(newStubClass, callbackExist);
3295                                 println("#endif");
3296                                 pw.close();
3297                                 System.out.println("IoTCompiler: Generated stub class " + newStubClass + ".hpp...");
3298                         }
3299                 }
3300         }
3301
3302
3303         /**
3304          * HELPER: writePropertiesCplusCallbackStub() writes the properties of the stub class
3305          */
3306         private void writePropertiesCplusCallbackStub(String intface, String newIntface, boolean callbackExist, Set<String> callbackClasses) {
3307
3308                 println("IoTRMICall *rmiCall;");
3309                 // Get the object Id
3310                 println("int objectId;");
3311                 if (callbackExist) {
3312                 // We assume that each class only has one callback interface for now
3313                         Iterator it = callbackClasses.iterator();
3314                         String callbackType = (String) it.next();
3315                         println("// Callback properties");
3316                         println("IoTRMIObject *rmiObj;");
3317                         println("vector<" + callbackType + "*> vecCallbackObj;");
3318                         println("static int objIdCnt;");
3319                         // TODO: Need to initialize address and ports if we want to have callback-in-callback
3320                         println("string address;");
3321                         println("vector<int> ports;\n");
3322                         writePropertiesCplusPermission(callbackType);
3323                 }
3324                 println("\n");
3325         }
3326
3327
3328         /**
3329          * HELPER: writeConstructorCplusCallbackStub() writes the constructor of the stub class
3330          */
3331         private void writeConstructorCplusCallbackStub(String newStubClass, boolean callbackExist, Set<String> callbackClasses) {
3332
3333                 println(newStubClass + "(IoTRMICall* _rmiCall, int _objectId) {");
3334                 println("objectId = _objectId;");
3335                 println("rmiCall = _rmiCall;");
3336                 if (callbackExist) {
3337                         Iterator it = callbackClasses.iterator();
3338                         String callbackType = (String) it.next();
3339                         println("thread th1 (&" + newStubClass + "::___initCallBack, this);");
3340                         println("th1.detach();");
3341                         println("___regCB();");
3342                 }
3343                 println("}\n");
3344         }
3345
3346
3347         /**
3348          * generateCPlusCallbackStubClasses() generate callback stubs based on the methods list in C++
3349          */
3350         public void generateCPlusCallbackStubClasses() throws IOException {
3351
3352                 // Create a new directory
3353                 String path = createDirectories(dir, subdir);
3354                 for (String intface : mapIntfacePTH.keySet()) {
3355
3356                         Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3357                         for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3358                                 // Open a new file to write into
3359                                 String newIntface = intMeth.getKey();
3360                                 String newStubClass = newIntface + "_CallbackStub";
3361                                 FileWriter fw = new FileWriter(path + "/" + newStubClass + ".hpp");
3362                                 pw = new PrintWriter(new BufferedWriter(fw));
3363                                 // Find out if there are callback objects
3364                                 Set<String> methods = intMeth.getValue();
3365                                 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
3366                                 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
3367                                 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
3368                                 boolean callbackExist = !callbackClasses.isEmpty();
3369                                 // Write file headers
3370                                 println("#ifndef _" + newStubClass.toUpperCase() + "_HPP__");
3371                                 println("#define _" + newStubClass.toUpperCase() + "_HPP__");
3372                                 println("#include <iostream>");
3373                                 if (callbackExist)
3374                                         println("#include <thread>");
3375                                 println("#include \"" + newIntface + ".hpp\""); println("");            
3376                                 println("using namespace std;"); println("");
3377                                 println("class " + newStubClass + " : public " + newIntface); println("{");
3378                                 println("private:\n");
3379                                 writePropertiesCplusCallbackStub(intface, newIntface, callbackExist, callbackClasses);
3380                                 println("public:\n");
3381                                 // Add default constructor and destructor
3382                                 println(newStubClass + "() { }"); println("");
3383                                 writeConstructorCplusCallbackStub(newStubClass, callbackExist, callbackClasses);
3384                                 writeDeconstructorCplusStub(newStubClass, callbackExist, callbackClasses);
3385                                 // Write methods
3386                                 writeMethodCplusStub(methods, intDecl, callbackClasses);
3387                                 println("};");
3388                                 if (callbackExist) {
3389                                         Iterator it = callbackClasses.iterator();
3390                                         String callbackType = (String) it.next();
3391                                         // Generate permission stuff for callback stubs
3392                                         DeclarationHandler decHandlerCallback = mapIntDeclHand.get(callbackType);
3393                                         InterfaceDecl intDeclCallback = (InterfaceDecl) decHandlerCallback.getInterfaceDecl(callbackType);
3394                                         writePermissionInitializationCplus(callbackType, newStubClass, intDeclCallback);
3395                                 }
3396                                 writeObjectIdCountInitializationCplus(newStubClass, callbackExist);
3397                                 println("#endif");
3398                                 pw.close();
3399                                 System.out.println("IoTCompiler: Generated callback stub class " + newIntface + ".hpp...");
3400                         }
3401                 }
3402         }
3403
3404
3405         /**
3406          * HELPER: writePropertiesCplusSkeleton() writes the properties of the skeleton class
3407          */
3408         private void writePropertiesCplusSkeleton(String intface, boolean callbackExist, Set<String> callbackClasses) {
3409
3410                 println(intface + " *mainObj;");
3411                 // Callback
3412                 if (callbackExist) {
3413                         Iterator it = callbackClasses.iterator();
3414                         String callbackType = (String) it.next();
3415                         String exchangeType = checkAndGetParamClass(callbackType);
3416                         println("// Callback properties");
3417                         println("static int objIdCnt;");
3418                         println("vector<" + exchangeType + "*> vecCallbackObj;");
3419                         println("IoTRMICall *rmiCall;");
3420                 }
3421                 println("IoTRMIObject *rmiObj;\n");
3422                 // Keep track of object Ids of all stubs registered to this interface
3423                 writePropertiesCplusPermission(intface);
3424                 println("\n");
3425         }
3426
3427
3428         /**
3429          * HELPER: writeObjectIdCountInitializationCplus() writes the initialization of objIdCnt variable
3430          */
3431         private void writeObjectIdCountInitializationCplus(String newSkelClass, boolean callbackExist) {
3432
3433                 if (callbackExist)
3434                         println("int " + newSkelClass + "::objIdCnt = 0;");
3435         }
3436
3437
3438         /**
3439          * HELPER: writePermissionInitializationCplus() writes the initialization of permission set
3440          */
3441         private void writePermissionInitializationCplus(String intface, String newSkelClass, InterfaceDecl intDecl) {
3442
3443                 // Keep track of object Ids of all stubs registered to this interface
3444                 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3445                 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3446                         String newIntface = intMeth.getKey();
3447                         int newObjectId = getNewIntfaceObjectId(newIntface);
3448                         print("set<int> " + newSkelClass + "::set" + newObjectId + "Allowed { ");
3449                         Set<String> methodIds = intMeth.getValue();
3450                         int i = 0;
3451                         for (String methodId : methodIds) {
3452                                 int methodNumId = intDecl.getMethodNumId(methodId);
3453                                 print(Integer.toString(methodNumId));
3454                                 // Check if this is the last element (don't print a comma)
3455                                 if (i != methodIds.size() - 1) {
3456                                         print(", ");
3457                                 }
3458                                 i++;
3459                         }
3460                         println(" };");
3461                 }       
3462         }
3463
3464
3465         /**
3466          * HELPER: writeStructPermissionCplusSkeleton() writes permission for struct helper
3467          */
3468         private void writeStructPermissionCplusSkeleton(Collection<String> methods, InterfaceDecl intDecl, String intface) {
3469
3470                 // Use this set to handle two same methodIds
3471                 for (String method : methods) {
3472                         List<String> methParams = intDecl.getMethodParams(method);
3473                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
3474                         // Check for params with structs
3475                         for (int i = 0; i < methParams.size(); i++) {
3476                                 String paramType = methPrmTypes.get(i);
3477                                 String param = methParams.get(i);
3478                                 String simpleType = getGenericType(paramType);
3479                                 if (isStructClass(simpleType)) {
3480                                         int methodNumId = intDecl.getMethodNumId(method);
3481                                         String helperMethod = methodNumId + "struct" + i;
3482                                         int helperMethodNumId = intDecl.getHelperMethodNumId(helperMethod);
3483                                         // Iterate over interfaces to give permissions to
3484                                         Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3485                                         for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3486                                                 String newIntface = intMeth.getKey();
3487                                                 int newObjectId = getNewIntfaceObjectId(newIntface);
3488                                                 println("set" + newObjectId + "Allowed.insert(" + helperMethodNumId + ");");
3489                                         }
3490                                 }
3491                         }
3492                 }
3493         }
3494
3495
3496         /**
3497          * HELPER: writeConstructorCplusSkeleton() writes the constructor of the skeleton class
3498          */
3499         private void writeConstructorCplusSkeleton(String newSkelClass, String intface, boolean callbackExist, InterfaceDecl intDecl, Collection<String> methods) {
3500
3501                 println(newSkelClass + "(" + intface + " *_mainObj, int _port) {");
3502                 println("bool _bResult = false;");
3503                 println("mainObj = _mainObj;");
3504                 println("rmiObj = new IoTRMIObject(_port, &_bResult);");
3505                 writeCplusInitCallbackPermission(intface, intDecl, callbackExist);
3506                 writeStructPermissionCplusSkeleton(methods, intDecl, intface);
3507                 println("___waitRequestInvokeMethod();");
3508                 println("}\n");
3509         }
3510
3511
3512         /**
3513          * HELPER: writeDeconstructorCplusSkeleton() writes the deconstructor of the skeleton class
3514          */
3515         private void writeDeconstructorCplusSkeleton(String newSkelClass, boolean callbackExist, Set<String> callbackClasses) {
3516
3517                 println("~" + newSkelClass + "() {");
3518                 println("if (rmiObj != NULL) {");
3519                 println("delete rmiObj;");
3520                 println("rmiObj = NULL;");
3521                 println("}");
3522                 if (callbackExist) {
3523                 // We assume that each class only has one callback interface for now
3524                         println("if (rmiCall != NULL) {");
3525                         println("delete rmiCall;");
3526                         println("rmiCall = NULL;");
3527                         println("}");
3528                         Iterator it = callbackClasses.iterator();
3529                         String callbackType = (String) it.next();
3530                         String exchangeType = checkAndGetParamClass(callbackType);
3531                         println("for(" + exchangeType + "* cb : vecCallbackObj) {");
3532                         println("delete cb;");
3533                         println("cb = NULL;");
3534                         println("}");
3535                 }
3536                 println("}");
3537                 println("");
3538         }
3539
3540
3541         /**
3542          * HELPER: writeStdMethodBodyCplusSkeleton() writes the standard method body in the skeleton class
3543          */
3544         private void writeStdMethodBodyCplusSkeleton(List<String> methParams, String methodId, String methodType) {
3545
3546                 if (methodType.equals("void"))
3547                         print("mainObj->" + methodId + "(");
3548                 else
3549                         print("return mainObj->" + methodId + "(");
3550                 for (int i = 0; i < methParams.size(); i++) {
3551
3552                         print(getSimpleIdentifier(methParams.get(i)));
3553                         // Check if this is the last element (don't print a comma)
3554                         if (i != methParams.size() - 1) {
3555                                 print(", ");
3556                         }
3557                 }
3558                 println(");");
3559         }
3560
3561
3562         /**
3563          * HELPER: writeInitCallbackCplusSkeleton() writes the init callback method for skeleton class
3564          */
3565         private void writeInitCallbackCplusSkeleton(boolean callbackSkeleton) {
3566
3567                 // This is a callback skeleton generation
3568                 if (callbackSkeleton)
3569                         println("void ___regCB(IoTRMIObject* rmiObj) {");
3570                 else
3571                         println("void ___regCB() {");
3572                 println("int numParam = 3;");
3573                 println("int param1 = 0;");
3574                 println("string param2 = \"\";");
3575                 println("int param3 = 0;");
3576                 println("string paramCls[] = { \"int\", \"String\", \"int\" };");
3577                 println("void* paramObj[] = { &param1, &param2, &param3 };");
3578                 println("rmiObj->getMethodParams(paramCls, numParam, paramObj);");
3579                 println("bool bResult = false;");
3580                 println("rmiCall = new IoTRMICall(param1, param2.c_str(), param3, &bResult);");
3581                 println("}\n");
3582         }
3583
3584
3585         /**
3586          * HELPER: writeMethodCplusSkeleton() writes the method of the skeleton class
3587          */
3588         private void writeMethodCplusSkeleton(Collection<String> methods, InterfaceDecl intDecl, 
3589                         Set<String> callbackClasses, boolean callbackSkeleton) {
3590
3591                 boolean isDefined = false;
3592                 for (String method : methods) {
3593
3594                         List<String> methParams = intDecl.getMethodParams(method);
3595                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
3596                         String methodId = intDecl.getMethodId(method);
3597                         String methodType = checkAndGetCplusType(intDecl.getMethodType(method));
3598                         print(methodType + " " + methodId + "(");
3599                         boolean isCallbackMethod = false;
3600                         String callbackType = null;
3601                         for (int i = 0; i < methParams.size(); i++) {
3602
3603                                 String origParamType = methPrmTypes.get(i);
3604                                 if (callbackClasses.contains(origParamType)) { // Check if this has callback object
3605                                         isCallbackMethod = true;
3606                                         callbackType = origParamType;   
3607                                 }
3608                                 String paramType = checkAndGetParamClass(methPrmTypes.get(i));
3609                                 String methPrmType = checkAndGetCplusType(paramType);
3610                                 String methParamComplete = checkAndGetCplusArray(methPrmType, methParams.get(i));
3611                                 print(methParamComplete);
3612                                 // Check if this is the last element (don't print a comma)
3613                                 if (i != methParams.size() - 1) {
3614                                         print(", ");
3615                                 }
3616                         }
3617                         println(") {");
3618                         // Now, write the body of skeleton!
3619                         writeStdMethodBodyCplusSkeleton(methParams, methodId, intDecl.getMethodType(method));
3620                         println("}\n");
3621                         if (isCallbackMethod && !isDefined) {
3622                                 writeInitCallbackCplusSkeleton(callbackSkeleton);
3623                                 isDefined = true;
3624                         }
3625                 }
3626         }
3627
3628
3629         /**
3630          * HELPER: writeCallbackCplusNumStubs() writes the numStubs variable
3631          */
3632         private void writeCallbackCplusNumStubs(List<String> methParams, List<String> methPrmTypes, String callbackType) {
3633
3634                 for (int i = 0; i < methParams.size(); i++) {
3635                         String paramType = methPrmTypes.get(i);
3636                         String param = methParams.get(i);
3637                         //if (callbackType.equals(paramType)) {
3638                         if (checkCallbackType(paramType, callbackType)) // Check if this has callback object
3639                                 println("int numStubs" + i + " = 0;");
3640                 }
3641         }
3642
3643
3644         /**
3645          * HELPER: writeCallbackCplusStubGeneration() writes the callback stub generation part
3646          */
3647         private void writeCallbackCplusStubGeneration(List<String> methParams, List<String> methPrmTypes, String callbackType) {
3648
3649                 // Iterate over callback objects
3650                 for (int i = 0; i < methParams.size(); i++) {
3651                         String paramType = methPrmTypes.get(i);
3652                         String param = methParams.get(i);
3653                         // Generate a loop if needed
3654                         if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
3655                                 String exchParamType = checkAndGetParamClass(getGenericType(paramType));
3656                                 if (isArrayOrList(paramType, param)) {
3657                                         println("vector<" + exchParamType + "*> stub" + i + ";");
3658                                         println("for (int objId = 0; objId < numStubs" + i + "; objId++) {");
3659                                         println(exchParamType + "* cb" + i + " = new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt);");
3660                                         println("stub" + i + ".push_back(cb" + i + ");");
3661                                         println("vecCallbackObj.push_back(cb" + i + ");");
3662                                         println("objIdCnt++;");
3663                                         println("}");
3664                                 } else {
3665                                         println(exchParamType + "* stub" + i + " = new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt);");
3666                                         println("vecCallbackObj.push_back(stub" + i + ");");
3667                                         println("objIdCnt++;");
3668                                 }
3669                         }
3670                 }
3671         }
3672
3673
3674         /**
3675          * HELPER: checkAndWriteEnumTypeCplusSkeleton() writes the enum type (convert from enum to int)
3676          */
3677         private void checkAndWriteEnumTypeCplusSkeleton(List<String> methParams, List<String> methPrmTypes) {
3678
3679                 // Iterate and find enum declarations
3680                 for (int i = 0; i < methParams.size(); i++) {
3681                         String paramType = methPrmTypes.get(i);
3682                         String param = methParams.get(i);
3683                         String simpleType = getGenericType(paramType);
3684                         if (isEnumClass(simpleType)) {
3685                         // Check if this is enum type
3686                                 if (isArrayOrList(paramType, param)) {  // An array
3687                                         println("int len" + i + " = paramEnumInt" + i + ".size();");
3688                                         println("vector<" + simpleType + "> paramEnum" + i + "(len" + i + ");");
3689                                         println("for (int i=0; i < len" + i + "; i++) {");
3690                                         println("paramEnum" + i + "[i] = (" + simpleType + ") paramEnumInt" + i + "[i];");
3691                                         println("}");
3692                                 } else {        // Just one element
3693                                         println(simpleType + " paramEnum" + i + ";");
3694                                         println("paramEnum" + i + " = (" + simpleType + ") paramEnumInt" + i + "[0];");
3695                                 }
3696                         }
3697                 }
3698         }
3699
3700
3701         /**
3702          * HELPER: checkAndWriteEnumRetTypeCplusSkeleton() writes the enum return type (convert from enum to int)
3703          */
3704         private void checkAndWriteEnumRetTypeCplusSkeleton(String retType) {
3705
3706                 // Strips off array "[]" for return type
3707                 String pureType = getSimpleArrayType(getGenericType(retType));
3708                 // Take the inner type of generic
3709                 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
3710                         pureType = getGenericType(retType);
3711                 if (isEnumClass(pureType)) {
3712                 // Check if this is enum type
3713                         // Enum decoder
3714                         if (isArrayOrList(retType, retType)) {  // An array
3715                                 println("int retLen = retEnum.size();");
3716                                 println("vector<int> retEnumInt(retLen);");
3717                                 println("for (int i=0; i < retLen; i++) {");
3718                                 println("retEnumInt[i] = (int) retEnum[i];");
3719                                 println("}");
3720                         } else {        // Just one element
3721                                 println("vector<int> retEnumInt(1);");
3722                                 println("retEnumInt[0] = (int) retEnum;");
3723                         }
3724                 }
3725         }
3726
3727
3728         /**
3729          * HELPER: writeMethodInputParameters() writes the parameter variables for C++ skeleton
3730          */
3731         private void writeMethodInputParameters(List<String> methParams, List<String> methPrmTypes, 
3732                         Set<String> callbackClasses, String methodId) {
3733
3734                 print(methodId + "(");
3735                 for (int i = 0; i < methParams.size(); i++) {
3736                         String paramType = returnGenericCallbackType(methPrmTypes.get(i));
3737                         if (callbackClasses.contains(paramType))
3738                                 print("stub" + i);
3739                         else if (isEnumClass(getGenericType(paramType)))        // Check if this is enum type
3740                                 print("paramEnum" + i);
3741                         else if (isStructClass(getGenericType(paramType)))      // Struct type
3742                                 print("paramStruct" + i);
3743                         else
3744                                 print(getSimpleIdentifier(methParams.get(i)));
3745                         if (i != methParams.size() - 1) {
3746                                 print(", ");
3747                         }
3748                 }
3749                 println(");");
3750         }
3751
3752
3753         /**
3754          * HELPER: writeMethodHelperReturnCplusSkeleton() writes the return statement part in skeleton
3755          */
3756         private void writeMethodHelperReturnCplusSkeleton(InterfaceDecl intDecl, List<String> methParams,
3757                         List<String> methPrmTypes, String method, boolean isCallbackMethod, String callbackType,
3758                         String methodId, Set<String> callbackClasses) {
3759
3760                 println("rmiObj->getMethodParams(paramCls, numParam, paramObj);");
3761                 if (isCallbackMethod)
3762                         writeCallbackCplusStubGeneration(methParams, methPrmTypes, callbackType);
3763                 checkAndWriteEnumTypeCplusSkeleton(methParams, methPrmTypes);
3764                 writeStructMembersInitCplusSkeleton(intDecl, methParams, methPrmTypes, method);
3765                 // Check if this is "void"
3766                 String retType = intDecl.getMethodType(method);
3767                 // Check if this is "void"
3768                 if (retType.equals("void")) {
3769                         writeMethodInputParameters(methParams, methPrmTypes, callbackClasses, methodId);
3770                 } else { // We do have a return value
3771                         if (isEnumClass(getSimpleArrayType(getGenericType(retType)))) // Enum type
3772                                 print(checkAndGetCplusType(retType) + " retEnum = ");
3773                         else if (isStructClass(getSimpleArrayType(getGenericType(retType)))) // Struct type
3774                                 print(checkAndGetCplusType(retType) + " retStruct = ");
3775                         else
3776                                 print(checkAndGetCplusType(retType) + " retVal = ");
3777                         writeMethodInputParameters(methParams, methPrmTypes, callbackClasses, methodId);
3778                         checkAndWriteEnumRetTypeCplusSkeleton(retType);
3779                         if (isStructClass(getSimpleArrayType(getGenericType(retType)))) // Struct type
3780                                 writeStructReturnCplusSkeleton(getSimpleArrayType(getGenericType(retType)), retType);
3781                         if (isEnumClass(getSimpleArrayType(getGenericType(retType)))) // Enum type
3782                                 println("void* retObj = &retEnumInt;");
3783                         else
3784                                 if (!isStructClass(getSimpleArrayType(getGenericType(retType)))) // Struct type
3785                                         println("void* retObj = &retVal;");
3786                         String retTypeC = checkAndGetCplusType(retType);
3787                         if (isStructClass(getSimpleArrayType(getGenericType(retType)))) // Struct type
3788                                 println("rmiObj->sendReturnObj(retObj, retCls, numRetObj);");
3789                         else
3790                                 println("rmiObj->sendReturnObj(retObj, \"" + checkAndGetCplusRetClsType(getEnumType(retType)) + "\");");
3791                 }
3792         }
3793
3794
3795         /**
3796          * HELPER: writeStdMethodHelperBodyCplusSkeleton() writes the standard method body helper in the skeleton class
3797          */
3798         private void writeStdMethodHelperBodyCplusSkeleton(InterfaceDecl intDecl, List<String> methParams,
3799                         List<String> methPrmTypes, String method, String methodId, Set<String> callbackClasses) {
3800
3801                 // Generate array of parameter types
3802                 boolean isCallbackMethod = false;
3803                 String callbackType = null;
3804                 print("string paramCls[] = { ");
3805                 for (int i = 0; i < methParams.size(); i++) {
3806                         String paramType = returnGenericCallbackType(methPrmTypes.get(i));
3807                         if (callbackClasses.contains(paramType)) {
3808                                 isCallbackMethod = true;
3809                                 callbackType = paramType;
3810                                 print("\"int\"");
3811                         } else {        // Generate normal classes if it's not a callback object
3812                                 String paramTypeC = checkAndGetCplusArgClsType(methPrmTypes.get(i), methParams.get(i));
3813                                 print("\"" + paramTypeC + "\"");
3814                         }
3815                         if (i != methParams.size() - 1) {
3816                                 print(", ");
3817                         }
3818                 }
3819                 println(" };");
3820                 println("int numParam = " + methParams.size() + ";");
3821                 if (isCallbackMethod)
3822                         writeCallbackCplusNumStubs(methParams, methPrmTypes, callbackType);
3823                 // Generate parameters
3824                 for (int i = 0; i < methParams.size(); i++) {
3825                         String paramType = returnGenericCallbackType(methPrmTypes.get(i));
3826                         if (!callbackClasses.contains(paramType)) {
3827                                 String methParamType = methPrmTypes.get(i);
3828                                 if (isEnumClass(getSimpleArrayType(getGenericType(methParamType)))) {   
3829                                 // Check if this is enum type
3830                                         println("vector<int> paramEnumInt" + i + ";");
3831                                 } else {
3832                                         String methPrmType = checkAndGetCplusType(methParamType);
3833                                         String methParamComplete = checkAndGetCplusArray(methPrmType, methParams.get(i));
3834                     println(methParamComplete + ";");
3835                                 }
3836                         }
3837                 }
3838                 // Generate array of parameter objects
3839                 print("void* paramObj[] = { ");
3840                 for (int i = 0; i < methParams.size(); i++) {
3841                         String paramType = returnGenericCallbackType(methPrmTypes.get(i));
3842                         if (callbackClasses.contains(paramType))
3843                                 print("&numStubs" + i);
3844                         else if (isEnumClass(getGenericType(paramType)))        // Check if this is enum type
3845                                 print("&paramEnumInt" + i);
3846                         else
3847                                 print("&" + getSimpleIdentifier(methParams.get(i)));
3848                         if (i != methParams.size() - 1) {
3849                                 print(", ");
3850                         }
3851                 }
3852                 println(" };");
3853                 // Write the return value part
3854                 writeMethodHelperReturnCplusSkeleton(intDecl, methParams, methPrmTypes, method, isCallbackMethod, 
3855                         callbackType, methodId, callbackClasses);
3856         }
3857
3858
3859         /**
3860          * HELPER: writeStructMembersCplusSkeleton() writes member parameters of struct
3861          */
3862         private void writeStructMembersCplusSkeleton(String simpleType, String paramType, 
3863                         String param, String method, InterfaceDecl intDecl, int iVar) {
3864
3865                 // Get the struct declaration for this struct and generate initialization code
3866                 StructDecl structDecl = getStructDecl(simpleType);
3867                 List<String> memTypes = structDecl.getMemberTypes(simpleType);
3868                 List<String> members = structDecl.getMembers(simpleType);
3869                 int methodNumId = intDecl.getMethodNumId(method);
3870                 String counter = "struct" + methodNumId + "Size" + iVar;
3871                 // Set up variables
3872                 if (isArrayOrList(paramType, param)) {  // An array or list
3873                         for (int i = 0; i < members.size(); i++) {
3874                                 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
3875                                 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
3876                                 println(getSimpleType(getEnumType(prmType)) + " param" + iVar + i + "[" + counter + "];");
3877                         }
3878                 } else {        // Just one struct element
3879                         for (int i = 0; i < members.size(); i++) {
3880                                 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
3881                                 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
3882                                 println(getSimpleType(getEnumType(prmType)) + " param" + iVar + i + ";");
3883                         }
3884                 }
3885                 if (isArrayOrList(paramType, param)) {  // An array or list
3886                         println("for(int i = 0; i < " + counter + "; i++) {");
3887                 }
3888                 if (isArrayOrList(paramType, param)) {  // An array or list
3889                         for (int i = 0; i < members.size(); i++) {
3890                                 String prmTypeC = checkAndGetCplusArgClsType(memTypes.get(i), members.get(i));
3891                                 println("paramCls[pos] = \"" + prmTypeC + "\";");
3892                                 println("paramObj[pos++] = &param" + iVar + i + "[i];");
3893                         }
3894                         println("}");
3895                 } else {        // Just one struct element
3896                         for (int i = 0; i < members.size(); i++) {
3897                                 String prmTypeC = checkAndGetCplusArgClsType(memTypes.get(i), members.get(i));
3898                                 println("paramCls[pos] = \"" + prmTypeC + "\";");
3899                                 println("paramObj[pos++] = &param" + iVar + i + ";");
3900                         }
3901                 }
3902         }
3903
3904
3905         /**
3906          * HELPER: writeStructMembersInitCplusSkeleton() writes member parameters initialization of struct
3907          */
3908         private void writeStructMembersInitCplusSkeleton(InterfaceDecl intDecl, List<String> methParams,
3909                         List<String> methPrmTypes, String method) {
3910
3911                 for (int i = 0; i < methParams.size(); i++) {
3912                         String paramType = methPrmTypes.get(i);
3913                         String param = methParams.get(i);
3914                         String simpleType = getGenericType(paramType);
3915                         if (isStructClass(simpleType)) {
3916                                 int methodNumId = intDecl.getMethodNumId(method);
3917                                 String counter = "struct" + methodNumId + "Size" + i;
3918                                 // Declaration
3919                                 if (isArrayOrList(paramType, param)) {  // An array or list
3920                                         println("vector<" + simpleType + "> paramStruct" + i + "(" + counter + ");");
3921                                 } else
3922                                         println(simpleType + " paramStruct" + i + ";");
3923                                 // Initialize members
3924                                 StructDecl structDecl = getStructDecl(simpleType);
3925                                 List<String> members = structDecl.getMembers(simpleType);
3926                                 List<String> memTypes = structDecl.getMemberTypes(simpleType);
3927                                 if (isArrayOrList(paramType, param)) {  // An array or list
3928                                         println("for(int i = 0; i < " + counter + "; i++) {");
3929                                         for (int j = 0; j < members.size(); j++) {
3930                                                 print("paramStruct" + i + "[i]." + getSimpleIdentifier(members.get(j)));
3931                                                 println(" = param" + i + j + "[i];");
3932                                         }
3933                                         println("}");
3934                                 } else {        // Just one struct element
3935                                         for (int j = 0; j < members.size(); j++) {
3936                                                 print("paramStruct" + i + "." + getSimpleIdentifier(members.get(j)));
3937                                                 println(" = param" + i + j + ";");
3938                                         }
3939                                 }
3940                         }
3941                 }
3942         }
3943
3944
3945         /**
3946          * HELPER: writeStructReturnCplusSkeleton() writes parameters of struct for return statement
3947          */
3948         private void writeStructReturnCplusSkeleton(String simpleType, String retType) {
3949
3950                 // Minimum retLen is 1 if this is a single struct object
3951                 if (isArrayOrList(retType, retType))
3952                         println("int retLen = retStruct.size();");
3953                 else    // Just single struct object
3954                         println("int retLen = 1;");
3955                 println("void* retLenObj = &retLen;");
3956                 println("rmiObj->sendReturnObj(retLenObj, \"int\");");
3957                 int numMem = getNumOfMembers(simpleType);
3958                 println("int numRetObj = " + numMem + "*retLen;");
3959                 println("string retCls[numRetObj];");
3960                 println("void* retObj[numRetObj];");
3961                 println("int retPos = 0;");
3962                 // Get the struct declaration for this struct and generate initialization code
3963                 StructDecl structDecl = getStructDecl(simpleType);
3964                 List<String> memTypes = structDecl.getMemberTypes(simpleType);
3965                 List<String> members = structDecl.getMembers(simpleType);
3966                 if (isArrayOrList(retType, retType)) {  // An array or list
3967                         println("for(int i = 0; i < retLen; i++) {");
3968                         for (int i = 0; i < members.size(); i++) {
3969                                 String prmTypeC = checkAndGetCplusArgClsType(memTypes.get(i), members.get(i));
3970                                 println("retCls[retPos] = \"" + prmTypeC + "\";");
3971                                 print("retObj[retPos++] = &retStruct[i].");
3972                                 print(getEnumParam(memTypes.get(i), getSimpleIdentifier(members.get(i)), i));
3973                                 println(";");
3974                         }
3975                         println("}");
3976                 } else {        // Just one struct element
3977                         for (int i = 0; i < members.size(); i++) {
3978                                 String prmTypeC = checkAndGetCplusArgClsType(memTypes.get(i), members.get(i));
3979                                 println("retCls[retPos] = \"" + prmTypeC + "\";");
3980                                 print("retObj[retPos++] = &retStruct.");
3981                                 print(getEnumParam(memTypes.get(i), getSimpleIdentifier(members.get(i)), i));
3982                                 println(";");
3983                         }
3984                 }
3985
3986         }
3987
3988
3989         /**
3990          * HELPER: writeMethodHelperStructCplusSkeleton() writes the struct in skeleton
3991          */
3992         private void writeMethodHelperStructCplusSkeleton(InterfaceDecl intDecl, List<String> methParams,
3993                         List<String> methPrmTypes, String method, String methodId, Set<String> callbackClasses) {
3994
3995                 // Generate array of parameter objects
3996                 boolean isCallbackMethod = false;
3997                 String callbackType = null;
3998                 print("int numParam = ");
3999                 writeLengthStructParamClassSkeleton(methParams, methPrmTypes, method, intDecl);
4000                 println(";");
4001                 println("string paramCls[numParam];");
4002                 println("void* paramObj[numParam];");
4003                 println("int pos = 0;");
4004                 // Iterate again over the parameters
4005                 for (int i = 0; i < methParams.size(); i++) {
4006                         String paramType = methPrmTypes.get(i);
4007                         String param = methParams.get(i);
4008                         String simpleType = getGenericType(paramType);
4009                         if (isStructClass(simpleType)) {
4010                                 writeStructMembersCplusSkeleton(simpleType, paramType, param, method, intDecl, i);
4011                         } else {
4012                                 String prmType = returnGenericCallbackType(methPrmTypes.get(i));
4013                                 if (callbackClasses.contains(prmType)) {
4014                                         isCallbackMethod = true;
4015                                         callbackType = prmType;
4016                                         println("int numStubs" + i + " = 0;");
4017                                         println("paramCls[pos] = \"int\";");
4018                                         println("paramObj[pos++] = &numStubs" + i + ";");
4019                                 } else {        // Generate normal classes if it's not a callback object
4020                                         String paramTypeC = checkAndGetCplusType(methPrmTypes.get(i));
4021                                         if (isEnumClass(getGenericType(paramTypeC))) {  // Check if this is enum type
4022                                                 println("vector<int> paramEnumInt" + i + ";");
4023                                         } else {
4024                                                 String methParamComplete = checkAndGetCplusArray(paramTypeC, methParams.get(i));
4025                                                 println(methParamComplete + ";");
4026                                         }
4027                                         String prmTypeC = checkAndGetCplusArgClsType(methPrmTypes.get(i), methParams.get(i));
4028                                         println("paramCls[pos] = \"" + prmTypeC + "\";");
4029                                         if (isEnumClass(getGenericType(paramType)))     // Check if this is enum type
4030                                                 println("paramObj[pos++] = &paramEnumInt" + i + ";");
4031                                         else
4032                                                 println("paramObj[pos++] = &" + getSimpleIdentifier(methParams.get(i)) + ";");
4033                                 }
4034                         }
4035                 }
4036                 // Write the return value part
4037                 writeMethodHelperReturnCplusSkeleton(intDecl, methParams, methPrmTypes, method, isCallbackMethod, 
4038                         callbackType, methodId, callbackClasses);
4039         }
4040
4041
4042         /**
4043          * HELPER: writeMethodHelperCplusSkeleton() writes the method helper of the skeleton class
4044          */
4045         private void writeMethodHelperCplusSkeleton(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
4046
4047                 // Use this set to handle two same methodIds
4048                 Set<String> uniqueMethodIds = new HashSet<String>();
4049                 for (String method : methods) {
4050
4051                         List<String> methParams = intDecl.getMethodParams(method);
4052                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4053                         if (isStructPresent(methParams, methPrmTypes)) {        // Treat struct differently
4054                                 String methodId = intDecl.getMethodId(method);
4055                                 print("void ___");
4056                                 String helperMethod = methodId;
4057                                 if (uniqueMethodIds.contains(methodId))
4058                                         helperMethod = helperMethod + intDecl.getMethodNumId(method);
4059                                 else
4060                                         uniqueMethodIds.add(methodId);
4061                                 String retType = intDecl.getMethodType(method);
4062                                 print(helperMethod + "(");
4063                                 boolean begin = true;
4064                                 for (int i = 0; i < methParams.size(); i++) { // Print size variables
4065                                         String paramType = methPrmTypes.get(i);
4066                                         String param = methParams.get(i);
4067                                         String simpleType = getGenericType(paramType);
4068                                         if (isStructClass(simpleType)) {
4069                                                 if (!begin)     // Generate comma for not the beginning variable
4070                                                         print(", ");
4071                                                 else
4072                                                         begin = false;
4073                                                 int methodNumId = intDecl.getMethodNumId(method);
4074                                                 print("int struct" + methodNumId + "Size" + i);
4075                                         }
4076                                 }
4077                                 println(") {");
4078                                 writeMethodHelperStructCplusSkeleton(intDecl, methParams, methPrmTypes, method, methodId, callbackClasses);
4079                                 println("}\n");
4080                         } else {
4081                                 String methodId = intDecl.getMethodId(method);
4082                                 print("void ___");
4083                                 String helperMethod = methodId;
4084                                 if (uniqueMethodIds.contains(methodId))
4085                                         helperMethod = helperMethod + intDecl.getMethodNumId(method);
4086                                 else
4087                                         uniqueMethodIds.add(methodId);
4088                                 // Check if this is "void"
4089                                 String retType = intDecl.getMethodType(method);
4090                                 println(helperMethod + "() {");
4091                                 // Now, write the helper body of skeleton!
4092                                 writeStdMethodHelperBodyCplusSkeleton(intDecl, methParams, methPrmTypes, method, methodId, callbackClasses);
4093                                 println("}\n");
4094                         }
4095                 }
4096                 // Write method helper for structs
4097                 writeMethodHelperStructSetupCplusSkeleton(methods, intDecl);
4098         }
4099
4100
4101         /**
4102          * HELPER: writeMethodHelperStructSetupCplusSkeleton() writes the method helper of struct in skeleton class
4103          */
4104         private void writeMethodHelperStructSetupCplusSkeleton(Collection<String> methods, 
4105                         InterfaceDecl intDecl) {
4106
4107                 // Use this set to handle two same methodIds
4108                 for (String method : methods) {
4109
4110                         List<String> methParams = intDecl.getMethodParams(method);
4111                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4112                         // Check for params with structs
4113                         for (int i = 0; i < methParams.size(); i++) {
4114                                 String paramType = methPrmTypes.get(i);
4115                                 String param = methParams.get(i);
4116                                 String simpleType = getGenericType(paramType);
4117                                 if (isStructClass(simpleType)) {
4118                                         int methodNumId = intDecl.getMethodNumId(method);
4119                                         print("int ___");
4120                                         String helperMethod = methodNumId + "struct" + i;
4121                                         println(helperMethod + "() {");
4122                                         // Now, write the helper body of skeleton!
4123                                         println("string paramCls[] = { \"int\" };");
4124                                         println("int numParam = 1;");
4125                                         println("int param0 = 0;");
4126                                         println("void* paramObj[] = { &param0 };");
4127                                         println("rmiObj->getMethodParams(paramCls, numParam, paramObj);");
4128                                         println("return param0;");
4129                                         println("}\n");
4130                                 }
4131                         }
4132                 }
4133         }
4134
4135
4136         /**
4137          * HELPER: writeMethodHelperStructSetupCplusCallbackSkeleton() writes the method helper of struct in skeleton class
4138          */
4139         private void writeMethodHelperStructSetupCplusCallbackSkeleton(Collection<String> methods, 
4140                         InterfaceDecl intDecl) {
4141
4142                 // Use this set to handle two same methodIds
4143                 for (String method : methods) {
4144
4145                         List<String> methParams = intDecl.getMethodParams(method);
4146                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4147                         // Check for params with structs
4148                         for (int i = 0; i < methParams.size(); i++) {
4149                                 String paramType = methPrmTypes.get(i);
4150                                 String param = methParams.get(i);
4151                                 String simpleType = getGenericType(paramType);
4152                                 if (isStructClass(simpleType)) {
4153                                         int methodNumId = intDecl.getMethodNumId(method);
4154                                         print("int ___");
4155                                         String helperMethod = methodNumId + "struct" + i;
4156                                         println(helperMethod + "(IoTRMIObject* rmiObj) {");
4157                                         // Now, write the helper body of skeleton!
4158                                         println("string paramCls[] = { \"int\" };");
4159                                         println("int numParam = 1;");
4160                                         println("int param0 = 0;");
4161                                         println("void* paramObj[] = { &param0 };");
4162                                         println("rmiObj->getMethodParams(paramCls, numParam, paramObj);");
4163                                         println("return param0;");
4164                                         println("}\n");
4165                                 }
4166                         }
4167                 }
4168         }
4169
4170
4171         /**
4172          * HELPER: writeCplusMethodPermission() writes permission checks in skeleton
4173          */
4174         private void writeCplusMethodPermission(String intface) {
4175
4176                 // Get all the different stubs
4177                 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
4178                 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
4179                         String newIntface = intMeth.getKey();
4180                         int newObjectId = getNewIntfaceObjectId(newIntface);
4181                         println("if (_objectId == object" + newObjectId + "Id) {");
4182                         println("if (set" + newObjectId + "Allowed.find(methodId) == set" + newObjectId + "Allowed.end()) {");
4183                         println("cerr << \"Object with object Id: \" << _objectId << \"  is not allowed to access method: \" << methodId << endl;");
4184                         println("return;");
4185                         println("}");
4186                         println("}");
4187                         println("else {");
4188                         println("cerr << \"Object Id: \" << _objectId << \" not recognized!\" << endl;");
4189                         println("return;");
4190                         println("}");
4191                 }
4192         }
4193
4194
4195         /**
4196          * HELPER: writeCplusWaitRequestInvokeMethod() writes the main loop of the skeleton class
4197          */
4198         private void writeCplusWaitRequestInvokeMethod(Collection<String> methods, InterfaceDecl intDecl, boolean callbackExist, String intface) {
4199
4200                 // Use this set to handle two same methodIds
4201                 Set<String> uniqueMethodIds = new HashSet<String>();
4202                 println("void ___waitRequestInvokeMethod() {");
4203                 // Write variables here if we have callbacks or enums or structs
4204                 writeCountVarStructSkeleton(methods, intDecl);
4205                 println("while (true) {");
4206                 println("rmiObj->getMethodBytes();");
4207                 println("int _objectId = rmiObj->getObjectId();");
4208                 println("int methodId = rmiObj->getMethodId();");
4209                 // Generate permission check
4210                 writeCplusMethodPermission(intface);
4211                 println("switch (methodId) {");
4212                 // Print methods and method Ids
4213                 for (String method : methods) {
4214                         String methodId = intDecl.getMethodId(method);
4215                         int methodNumId = intDecl.getMethodNumId(method);
4216                         print("case " + methodNumId + ": ___");
4217                         String helperMethod = methodId;
4218                         if (uniqueMethodIds.contains(methodId))
4219                                 helperMethod = helperMethod + methodNumId;
4220                         else
4221                                 uniqueMethodIds.add(methodId);
4222                         print(helperMethod + "(");
4223                         writeInputCountVarStructSkeleton(method, intDecl);
4224                         println("); break;");
4225                 }
4226                 String method = "___initCallBack()";
4227                 // Print case -9999 (callback handler) if callback exists
4228                 if (callbackExist) {
4229                         int methodId = intDecl.getHelperMethodNumId(method);
4230                         println("case " + methodId + ": ___regCB(); break;");
4231                 }
4232                 writeMethodCallStructSkeleton(methods, intDecl);
4233                 println("default: ");
4234                 println("cerr << \"Method Id \" << methodId << \" not recognized!\" << endl;");
4235                 println("throw exception();");
4236                 println("}");
4237                 println("}");
4238                 println("}\n");
4239         }
4240
4241
4242         /**
4243          * generateCplusSkeletonClass() generate skeletons based on the methods list in C++
4244          */
4245         public void generateCplusSkeletonClass() throws IOException {
4246
4247                 // Create a new directory
4248                 String path = createDirectories(dir, subdir);
4249                 for (String intface : mapIntfacePTH.keySet()) {
4250                         // Open a new file to write into
4251                         String newSkelClass = intface + "_Skeleton";
4252                         FileWriter fw = new FileWriter(path + "/" + newSkelClass + ".hpp");
4253                         pw = new PrintWriter(new BufferedWriter(fw));
4254                         // Write file headers
4255                         println("#ifndef _" + newSkelClass.toUpperCase() + "_HPP__");
4256                         println("#define _" + newSkelClass.toUpperCase() + "_HPP__");
4257                         println("#include <iostream>");
4258                         println("#include \"" + intface + ".hpp\"\n");
4259                         // Pass in set of methods and get import classes
4260                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4261                         InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
4262                         List<String> methods = intDecl.getMethods();
4263                         Set<String> includeClasses = getIncludeClasses(methods, intDecl, intface, true);
4264                         List<String> stdIncludeClasses = getStandardCplusIncludeClasses();
4265                         List<String> allIncludeClasses = getAllLibClasses(stdIncludeClasses, includeClasses);
4266                         printIncludeStatements(allIncludeClasses); println("");
4267                         println("using namespace std;\n");
4268                         // Find out if there are callback objects
4269                         Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
4270                         boolean callbackExist = !callbackClasses.isEmpty();
4271                         // Write class header
4272                         println("class " + newSkelClass + " : public " + intface); println("{");
4273                         println("private:\n");
4274                         // Write properties
4275                         writePropertiesCplusSkeleton(intface, callbackExist, callbackClasses);
4276                         println("public:\n");
4277                         // Write constructor
4278                         writeConstructorCplusSkeleton(newSkelClass, intface, callbackExist, intDecl, methods);
4279                         // Write deconstructor
4280                         writeDeconstructorCplusSkeleton(newSkelClass, callbackExist, callbackClasses);
4281                         // Write methods
4282                         writeMethodCplusSkeleton(methods, intDecl, callbackClasses, false);
4283                         // Write method helper
4284                         writeMethodHelperCplusSkeleton(methods, intDecl, callbackClasses);
4285                         // Write waitRequestInvokeMethod() - main loop
4286                         writeCplusWaitRequestInvokeMethod(methods, intDecl, callbackExist, intface);
4287                         println("};");
4288                         writePermissionInitializationCplus(intface, newSkelClass, intDecl);
4289                         writeObjectIdCountInitializationCplus(newSkelClass, callbackExist);
4290                         println("#endif");
4291                         pw.close();
4292                         System.out.println("IoTCompiler: Generated skeleton class " + newSkelClass + ".hpp...");
4293                 }
4294         }
4295
4296
4297         /**
4298          * HELPER: writePropertiesCplusCallbackSkeleton() writes the properties of the callback skeleton class
4299          */
4300         private void writePropertiesCplusCallbackSkeleton(String intface, boolean callbackExist, Set<String> callbackClasses) {
4301
4302                 println(intface + " *mainObj;");
4303                 // Keep track of object Ids of all stubs registered to this interface
4304                 println("int objectId;");
4305                 // Callback
4306                 if (callbackExist) {
4307                         Iterator it = callbackClasses.iterator();
4308                         String callbackType = (String) it.next();
4309                         String exchangeType = checkAndGetParamClass(callbackType);
4310                         println("// Callback properties");
4311                         println("IoTRMICall* rmiCall;");
4312                         println("vector<" + exchangeType + "*> vecCallbackObj;");
4313                         println("static int objIdCnt;");
4314                 }
4315                 println("\n");
4316         }
4317
4318
4319         /**
4320          * HELPER: writeConstructorCplusCallbackSkeleton() writes the constructor of the skeleton class
4321          */
4322         private void writeConstructorCplusCallbackSkeleton(String newSkelClass, String intface, boolean callbackExist, InterfaceDecl intDecl, Collection<String> methods) {
4323
4324                 println(newSkelClass + "(" + intface + " *_mainObj, int _objectId) {");
4325                 println("mainObj = _mainObj;");
4326                 println("objectId = _objectId;");
4327                 println("}\n");
4328         }
4329
4330
4331         /**
4332          * HELPER: writeDeconstructorCplusStub() writes the deconstructor of the stub class
4333          */
4334         private void writeDeconstructorCplusCallbackSkeleton(String newStubClass, boolean callbackExist, 
4335                         Set<String> callbackClasses) {
4336
4337                 println("~" + newStubClass + "() {");
4338                 if (callbackExist) {
4339                 // We assume that each class only has one callback interface for now
4340                         println("if (rmiCall != NULL) {");
4341                         println("delete rmiCall;");
4342                         println("rmiCall = NULL;");
4343                         println("}");
4344                         Iterator it = callbackClasses.iterator();
4345                         String callbackType = (String) it.next();
4346                         String exchangeType = checkAndGetParamClass(callbackType);
4347                         println("for(" + exchangeType + "* cb : vecCallbackObj) {");
4348                         println("delete cb;");
4349                         println("cb = NULL;");
4350                         println("}");
4351                 }
4352                 println("}");
4353                 println("");
4354         }
4355
4356
4357         /**
4358          * HELPER: writeMethodHelperCplusCallbackSkeleton() writes the method helper of callback skeleton class
4359          */
4360         private void writeMethodHelperCplusCallbackSkeleton(Collection<String> methods, InterfaceDecl intDecl, 
4361                         Set<String> callbackClasses) {
4362
4363                 // Use this set to handle two same methodIds
4364                 Set<String> uniqueMethodIds = new HashSet<String>();
4365                 for (String method : methods) {
4366
4367                         List<String> methParams = intDecl.getMethodParams(method);
4368                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4369                         if (isStructPresent(methParams, methPrmTypes)) {        // Treat struct differently
4370                                 String methodId = intDecl.getMethodId(method);
4371                                 print("void ___");
4372                                 String helperMethod = methodId;
4373                                 if (uniqueMethodIds.contains(methodId))
4374                                         helperMethod = helperMethod + intDecl.getMethodNumId(method);
4375                                 else
4376                                         uniqueMethodIds.add(methodId);
4377                                 String retType = intDecl.getMethodType(method);
4378                                 print(helperMethod + "(");
4379                                 boolean begin = true;
4380                                 for (int i = 0; i < methParams.size(); i++) { // Print size variables
4381                                         String paramType = methPrmTypes.get(i);
4382                                         String param = methParams.get(i);
4383                                         String simpleType = getGenericType(paramType);
4384                                         if (isStructClass(simpleType)) {
4385                                                 if (!begin)     // Generate comma for not the beginning variable
4386                                                         print(", ");
4387                                                 else
4388                                                         begin = false;
4389                                                 int methodNumId = intDecl.getMethodNumId(method);
4390                                                 print("int struct" + methodNumId + "Size" + i);
4391                                         }
4392                                 }
4393                                 println(", IoTRMIObject* rmiObj) {");
4394                                 writeMethodHelperStructCplusSkeleton(intDecl, methParams, methPrmTypes, method, methodId, callbackClasses);
4395                                 println("}\n");
4396                         } else {
4397                                 String methodId = intDecl.getMethodId(method);
4398                                 print("void ___");
4399                                 String helperMethod = methodId;
4400                                 if (uniqueMethodIds.contains(methodId))
4401                                         helperMethod = helperMethod + intDecl.getMethodNumId(method);
4402                                 else
4403                                         uniqueMethodIds.add(methodId);
4404                                 // Check if this is "void"
4405                                 String retType = intDecl.getMethodType(method);
4406                                 println(helperMethod + "(IoTRMIObject* rmiObj) {");
4407                                 // Now, write the helper body of skeleton!
4408                                 writeStdMethodHelperBodyCplusSkeleton(intDecl, methParams, methPrmTypes, method, methodId, callbackClasses);
4409                                 println("}\n");
4410                         }
4411                 }
4412                 // Write method helper for structs
4413                 writeMethodHelperStructSetupCplusCallbackSkeleton(methods, intDecl);
4414         }
4415
4416
4417         /**
4418          * HELPER: writeCplusCallbackWaitRequestInvokeMethod() writes the request invoke method of the skeleton callback class
4419          */
4420         private void writeCplusCallbackWaitRequestInvokeMethod(Collection<String> methods, InterfaceDecl intDecl, 
4421                         boolean callbackExist) {
4422
4423                 // Use this set to handle two same methodIds
4424                 Set<String> uniqueMethodIds = new HashSet<String>();
4425                 println("void invokeMethod(IoTRMIObject* rmiObj) {");
4426                 // Write variables here if we have callbacks or enums or structs
4427                 writeCountVarStructSkeleton(methods, intDecl);
4428                 // Write variables here if we have callbacks or enums or structs
4429                 println("int methodId = rmiObj->getMethodId();");
4430                 // TODO: code the permission check here!
4431                 println("switch (methodId) {");
4432                 // Print methods and method Ids
4433                 for (String method : methods) {
4434                         String methodId = intDecl.getMethodId(method);
4435                         int methodNumId = intDecl.getMethodNumId(method);
4436                         print("case " + methodNumId + ": ___");
4437                         String helperMethod = methodId;
4438                         if (uniqueMethodIds.contains(methodId))
4439                                 helperMethod = helperMethod + methodNumId;
4440                         else
4441                                 uniqueMethodIds.add(methodId);
4442                         print(helperMethod + "(");
4443                         if (writeInputCountVarStructSkeleton(method, intDecl))
4444                                 println(", rmiObj); break;");
4445                         else
4446                                 println("rmiObj); break;");
4447                 }
4448                 String method = "___initCallBack()";
4449                 // Print case -9999 (callback handler) if callback exists
4450                 if (callbackExist) {
4451                         int methodId = intDecl.getHelperMethodNumId(method);
4452                         println("case " + methodId + ": ___regCB(rmiObj); break;");
4453                 }
4454                 writeMethodCallStructCallbackSkeleton(methods, intDecl);
4455                 println("default: ");
4456                 println("cerr << \"Method Id \" << methodId << \" not recognized!\" << endl;");
4457                 println("throw exception();");
4458                 println("}");
4459                 println("}\n");
4460         }
4461
4462
4463         /**
4464          * generateCplusCallbackSkeletonClass() generate callback skeletons based on the methods list in C++
4465          */
4466         public void generateCplusCallbackSkeletonClass() throws IOException {
4467
4468                 // Create a new directory
4469                 String path = createDirectories(dir, subdir);
4470                 for (String intface : mapIntfacePTH.keySet()) {
4471                         // Open a new file to write into
4472                         String newSkelClass = intface + "_CallbackSkeleton";
4473                         FileWriter fw = new FileWriter(path + "/" + newSkelClass + ".hpp");
4474                         pw = new PrintWriter(new BufferedWriter(fw));
4475                         // Write file headers
4476                         println("#ifndef _" + newSkelClass.toUpperCase() + "_HPP__");
4477                         println("#define _" + newSkelClass.toUpperCase() + "_HPP__");
4478                         println("#include <iostream>");
4479                         println("#include \"" + intface + ".hpp\"\n");
4480                         // Pass in set of methods and get import classes
4481                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4482                         InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
4483                         List<String> methods = intDecl.getMethods();
4484                         Set<String> includeClasses = getIncludeClasses(methods, intDecl, intface, true);
4485                         List<String> stdIncludeClasses = getStandardCplusIncludeClasses();
4486                         List<String> allIncludeClasses = getAllLibClasses(stdIncludeClasses, includeClasses);
4487                         printIncludeStatements(allIncludeClasses); println("");                 
4488                         // Find out if there are callback objects
4489                         Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
4490                         boolean callbackExist = !callbackClasses.isEmpty();
4491                         println("using namespace std;\n");
4492                         // Write class header
4493                         println("class " + newSkelClass + " : public " + intface); println("{");
4494                         println("private:\n");
4495                         // Write properties
4496                         writePropertiesCplusCallbackSkeleton(intface, callbackExist, callbackClasses);
4497                         println("public:\n");
4498                         // Write constructor
4499                         writeConstructorCplusCallbackSkeleton(newSkelClass, intface, callbackExist, intDecl, methods);
4500                         // Write deconstructor
4501                         writeDeconstructorCplusCallbackSkeleton(newSkelClass, callbackExist, callbackClasses);
4502                         // Write methods
4503                         writeMethodCplusSkeleton(methods, intDecl, callbackClasses, true);
4504                         // Write method helper
4505                         writeMethodHelperCplusCallbackSkeleton(methods, intDecl, callbackClasses);
4506                         // Write waitRequestInvokeMethod() - main loop
4507                         writeCplusCallbackWaitRequestInvokeMethod(methods, intDecl, callbackExist);
4508                         println("};");
4509                         writeObjectIdCountInitializationCplus(newSkelClass, callbackExist);
4510                         println("#endif");
4511                         pw.close();
4512                         System.out.println("IoTCompiler: Generated callback skeleton class " + newSkelClass + ".hpp...");
4513                 }
4514         }
4515
4516
4517         /**
4518          * generateInitializer() generate initializer based on type
4519          */
4520         public String generateCplusInitializer(String type) {
4521
4522                 // Generate dummy returns for now
4523                 if (type.equals("short")||
4524                         type.equals("int")      ||
4525                         type.equals("long") ||
4526                         type.equals("float")||
4527                         type.equals("double")) {
4528
4529                         return "0";
4530                 } else if ( type.equals("String") ||
4531                                         type.equals("string")) {
4532   
4533                         return "\"\"";
4534                 } else if ( type.equals("char") ||
4535                                         type.equals("byte")) {
4536
4537                         return "\' \'";
4538                 } else if ( type.equals("boolean")) {
4539
4540                         return "false";
4541                 } else {
4542                         return "NULL";
4543                 }
4544         }
4545
4546
4547         /**
4548          * setDirectory() sets a new directory for stub files
4549          */
4550         public void setDirectory(String _subdir) {
4551
4552                 subdir = _subdir;
4553         }
4554
4555
4556         /**
4557          * printUsage() prints the usage of this compiler
4558          */
4559         public static void printUsage() {
4560
4561                 System.out.println();
4562                 System.out.println("Sentinel interface and stub compiler version 1.0");
4563                 System.out.println("Copyright (c) 2015-2016 University of California, Irvine - Programming Language Group.");
4564                 System.out.println("All rights reserved.");
4565                 System.out.println("Usage:");
4566                 System.out.println("\tjava IoTCompiler -help / --help / -h\n");
4567                 System.out.println("\t\tDisplay this help texts\n\n");
4568                 System.out.println("\tjava IoTCompiler [<main-policy-file> <req-policy-file>]");
4569                 System.out.println("\tjava IoTCompiler [<main-policy-file> <req-policy-file>] [options]\n");
4570                 System.out.println("\t\tTake one or more pairs of main-req policy files, and generate Java and/or C++ files\n");
4571                 System.out.println("Options:");
4572                 System.out.println("\t-java\t<directory>\tGenerate Java stub files");
4573                 System.out.println("\t-cplus\t<directory>\tGenerate C++ stub files");
4574                 System.out.println();
4575         }
4576
4577
4578         /**
4579          * parseFile() prepares Lexer and Parser objects, then parses the file
4580          */
4581         public static ParseNode parseFile(String file) {
4582
4583                 ParseNode pn = null;
4584                 try {
4585                         ComplexSymbolFactory csf = new ComplexSymbolFactory();
4586                         ScannerBuffer lexer = 
4587                                 new ScannerBuffer(new Lexer(new BufferedReader(new FileReader(file)),csf));
4588                         Parser parse = new Parser(lexer,csf);
4589                         pn = (ParseNode) parse.parse().value;
4590                 } catch (Exception e) {
4591                         e.printStackTrace();
4592                         throw new Error("IoTCompiler: ERROR parsing policy file or wrong command line option: " + file + "\n");
4593                 }
4594
4595                 return pn;
4596         }
4597
4598
4599         /**================
4600          * Basic helper functions
4601          **================
4602          */
4603         boolean newline=true;
4604         int tablevel=0;
4605
4606         private void print(String str) {
4607                 if (newline) {
4608                         int tab=tablevel;
4609                         if (str.equals("}"))
4610                                 tab--;
4611                         for(int i=0; i<tab; i++)
4612                                 pw.print("\t");
4613                 }
4614                 pw.print(str);
4615                 updatetabbing(str);
4616                 newline=false;
4617         }
4618
4619
4620         /**
4621          * This function converts Java to C++ type for compilation
4622          */
4623         private String convertType(String type) {
4624
4625                 if (mapPrimitives.containsKey(type))
4626                         return mapPrimitives.get(type);
4627                 else
4628                         return type;
4629         }
4630
4631
4632         /**
4633          * A collection of methods with print-to-file functionality
4634          */
4635         private void println(String str) {
4636                 if (newline) {
4637                         int tab = tablevel;
4638                         if (str.contains("}") && !str.contains("{"))
4639                                 tab--;
4640                         for(int i=0; i<tab; i++)
4641                                 pw.print("\t");
4642                 }
4643                 pw.println(str);
4644                 updatetabbing(str);
4645                 newline = true;
4646         }
4647
4648
4649         private void updatetabbing(String str) {
4650
4651                 tablevel+=count(str,'{')-count(str,'}');
4652         }
4653
4654
4655         private int count(String str, char key) {
4656                 char[] array = str.toCharArray();
4657                 int count = 0;
4658                 for(int i=0; i<array.length; i++) {
4659                         if (array[i] == key)
4660                                 count++;
4661                 }
4662                 return count;
4663         }
4664
4665
4666         private void createDirectory(String dirName) {
4667
4668                 File file = new File(dirName);
4669                 if (!file.exists()) {
4670                         if (file.mkdir()) {
4671                                 System.out.println("IoTCompiler: Directory " + dirName + " has been created!");
4672                         } else {
4673                                 System.out.println("IoTCompiler: Failed to create directory " + dirName + "!");
4674                         }
4675                 } else {
4676                         System.out.println("IoTCompiler: Directory " + dirName + " exists...");
4677                 }
4678         }
4679
4680
4681         // Create a directory and possibly a sub directory
4682         private String createDirectories(String dir, String subdir) {
4683
4684                 String path = dir;
4685                 createDirectory(path);
4686                 if (subdir != null) {
4687                         path = path + "/" + subdir;
4688                         createDirectory(path);
4689                 }
4690                 return path;
4691         }
4692
4693
4694         // Inserting array members into a Map object
4695         // that maps arrKey to arrVal objects
4696         private void arraysToMap(Map map, Object[] arrKey, Object[] arrVal) {
4697
4698                 for(int i = 0; i < arrKey.length; i++) {
4699
4700                         map.put(arrKey[i], arrVal[i]);
4701                 }
4702         }
4703
4704
4705         // Check and find object Id for new interface in mapNewIntfaceObjId (callbacks)
4706         // Throw an error if the new interface is not found!
4707         // Basically the compiler needs to parse the policy (and requires) files for callback class first
4708         private int getNewIntfaceObjectId(String newIntface) {
4709
4710                 if (!mapNewIntfaceObjId.containsKey(newIntface)) {
4711                         throw new Error("IoTCompiler: Need to parse policy and requires files for callback class first! " +
4712                                                         "Please place the two files for callback class in front...\n");
4713                 } else {
4714                         int retObjId = mapNewIntfaceObjId.get(newIntface);
4715                         return retObjId;
4716                 }
4717         }
4718
4719
4720         // Return parameter category, i.e. PRIMITIVES, NONPRIMITIVES, USERDEFINED, ENUM, or STRUCT
4721         private ParamCategory getParamCategory(String paramType) {
4722
4723                 if (mapPrimitives.containsKey(paramType)) {
4724                         return ParamCategory.PRIMITIVES;
4725                 // We can either use mapNonPrimitivesJava or mapNonPrimitivesCplus here
4726                 } else if (mapNonPrimitivesJava.containsKey(getSimpleType(paramType))) {
4727                         return ParamCategory.NONPRIMITIVES;
4728                 } else if (isEnumClass(paramType)) {
4729                         return ParamCategory.ENUM;
4730                 } else if (isStructClass(paramType)) {
4731                         return ParamCategory.STRUCT;
4732                 } else
4733                         return ParamCategory.USERDEFINED;
4734         }
4735
4736
4737         // Return full class name for non-primitives to generate Java import statements
4738         // e.g. java.util.Set for Set
4739         private String getNonPrimitiveJavaClass(String paramNonPrimitives) {
4740
4741                 return mapNonPrimitivesJava.get(paramNonPrimitives);
4742         }
4743
4744
4745         // Return full class name for non-primitives to generate Cplus include statements
4746         // e.g. #include <set> for Set
4747         private String getNonPrimitiveCplusClass(String paramNonPrimitives) {
4748
4749                 return mapNonPrimitivesCplus.get(paramNonPrimitives);
4750         }
4751
4752
4753         // Get simple types, e.g. HashSet for HashSet<...>
4754         // Basically strip off the "<...>"
4755         private String getSimpleType(String paramType) {
4756
4757                 // Check if this is generics
4758                 if(paramType.contains("<")) {
4759                         String[] type = paramType.split("<");
4760                         return type[0];
4761                 } else
4762                         return paramType;
4763         }
4764
4765
4766         // Generate a set of standard classes for import statements
4767         private List<String> getStandardJavaIntfaceImportClasses() {
4768
4769                 List<String> importClasses = new ArrayList<String>();
4770                 // Add the standard list first
4771                 importClasses.add("java.util.List");
4772                 importClasses.add("java.util.ArrayList");
4773
4774                 return importClasses;
4775         }
4776
4777
4778         // Generate a set of standard classes for import statements
4779         private List<String> getStandardJavaImportClasses() {
4780
4781                 List<String> importClasses = new ArrayList<String>();
4782                 // Add the standard list first
4783                 importClasses.add("java.io.IOException");
4784                 importClasses.add("java.util.List");
4785                 importClasses.add("java.util.ArrayList");
4786                 importClasses.add("java.util.Arrays");
4787                 importClasses.add("iotrmi.Java.IoTRMICall");
4788                 importClasses.add("iotrmi.Java.IoTRMIObject");
4789
4790                 return importClasses;
4791         }
4792
4793
4794         // Generate a set of standard classes for import statements
4795         private List<String> getStandardCplusIncludeClasses() {
4796
4797                 List<String> importClasses = new ArrayList<String>();
4798                 // Add the standard list first
4799                 importClasses.add("<vector>");
4800                 importClasses.add("<set>");
4801                 importClasses.add("\"IoTRMICall.hpp\"");
4802                 importClasses.add("\"IoTRMIObject.hpp\"");
4803
4804                 return importClasses;
4805         }
4806
4807
4808         // Combine all classes for import statements
4809         private List<String> getAllLibClasses(Collection<String> stdLibClasses, Collection<String> libClasses) {
4810
4811                 List<String> allLibClasses = new ArrayList<String>(stdLibClasses);
4812                 // Iterate over the list of import classes
4813                 for (String str : libClasses) {
4814                         if (!allLibClasses.contains(str)) {
4815                                 allLibClasses.add(str);
4816                         }
4817                 }
4818                 return allLibClasses;
4819         }
4820
4821
4822
4823         // Generate a set of classes for import statements
4824         private Set<String> getImportClasses(Collection<String> methods, InterfaceDecl intDecl) {
4825
4826                 Set<String> importClasses = new HashSet<String>();
4827                 for (String method : methods) {
4828                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4829                         for (String paramType : methPrmTypes) {
4830
4831                                 String simpleType = getSimpleType(paramType);
4832                                 if (getParamCategory(simpleType) == ParamCategory.NONPRIMITIVES) {
4833                                         importClasses.add(getNonPrimitiveJavaClass(simpleType));
4834                                 }
4835                         }
4836                 }
4837                 return importClasses;
4838         }
4839
4840
4841         // Handle and return the correct enum declaration
4842         // In Java, if we declare enum in Camera interface, then it becomes "Camera.<enum>"
4843         private String getEnumParamDecl(String type, InterfaceDecl intDecl) {
4844
4845                 // Strips off array "[]" for return type
4846                 String pureType = getSimpleArrayType(type);
4847                 // Take the inner type of generic
4848                 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
4849                         pureType = getTypeOfGeneric(type)[0];
4850                 if (isEnumClass(pureType)) {
4851                         String enumType = intDecl.getInterface() + "." + type;
4852                         return enumType;
4853                 } else
4854                         return type;
4855         }
4856
4857
4858         // Handle and return the correct type
4859         private String getEnumParam(String type, String param, int i) {
4860
4861                 // Strips off array "[]" for return type
4862                 String pureType = getSimpleArrayType(type);
4863                 // Take the inner type of generic
4864                 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
4865                         pureType = getTypeOfGeneric(type)[0];
4866                 if (isEnumClass(pureType)) {
4867                         String enumParam = "paramEnum" + i;
4868                         return enumParam;
4869                 } else
4870                         return param;
4871         }
4872
4873
4874         // Handle and return the correct enum declaration translate into int[]
4875         private String getEnumType(String type) {
4876
4877                 // Strips off array "[]" for return type
4878                 String pureType = getSimpleArrayType(type);
4879                 // Take the inner type of generic
4880                 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
4881                         pureType = getGenericType(type);
4882                 if (isEnumClass(pureType)) {
4883                         String enumType = "int[]";
4884                         return enumType;
4885                 } else
4886                         return type;
4887         }
4888
4889         // Handle and return the correct enum declaration translate into int* for C
4890         private String getEnumCplusClsType(String type) {
4891
4892                 // Strips off array "[]" for return type
4893                 String pureType = getSimpleArrayType(type);
4894                 // Take the inner type of generic
4895                 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
4896                         pureType = getGenericType(type);
4897                 if (isEnumClass(pureType)) {
4898                         String enumType = "int*";
4899                         return enumType;
4900                 } else
4901                         return type;
4902         }
4903
4904
4905         // Handle and return the correct struct declaration
4906         private String getStructType(String type) {
4907
4908                 // Strips off array "[]" for return type
4909                 String pureType = getSimpleArrayType(type);
4910                 // Take the inner type of generic
4911                 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
4912                         pureType = getGenericType(type);
4913                 if (isStructClass(pureType)) {
4914                         String structType = "int";
4915                         return structType;
4916                 } else
4917                         return type;
4918         }
4919
4920
4921         // Check if this an enum declaration
4922         private boolean isEnumClass(String type) {
4923
4924                 // Just iterate over the set of interfaces
4925                 for (String intface : mapIntfacePTH.keySet()) {
4926                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4927                         EnumDecl enumDecl = (EnumDecl) decHandler.getEnumDecl(intface);
4928                         Set<String> setEnumDecl = enumDecl.getEnumDeclarations();
4929                         if (setEnumDecl.contains(type))
4930                                 return true;
4931                 }
4932                 return false;
4933         }
4934
4935
4936         // Check if this an struct declaration
4937         private boolean isStructClass(String type) {
4938
4939                 // Just iterate over the set of interfaces
4940                 for (String intface : mapIntfacePTH.keySet()) {
4941                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4942                         StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
4943                         List<String> listStructDecl = structDecl.getStructTypes();
4944                         if (listStructDecl.contains(type))
4945                                 return true;
4946                 }
4947                 return false;
4948         }
4949
4950
4951         // Return a struct declaration
4952         private StructDecl getStructDecl(String type) {
4953
4954                 // Just iterate over the set of interfaces
4955                 for (String intface : mapIntfacePTH.keySet()) {
4956                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4957                         StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
4958                         List<String> listStructDecl = structDecl.getStructTypes();
4959                         if (listStructDecl.contains(type))
4960                                 return structDecl;
4961                 }
4962                 return null;
4963         }
4964
4965
4966         // Return number of members (-1 if not found)
4967         private int getNumOfMembers(String type) {
4968
4969                 // Just iterate over the set of interfaces
4970                 for (String intface : mapIntfacePTH.keySet()) {
4971                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4972                         StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
4973                         List<String> listStructDecl = structDecl.getStructTypes();
4974                         if (listStructDecl.contains(type))
4975                                 return structDecl.getNumOfMembers(type);
4976                 }
4977                 return -1;
4978         }
4979
4980
4981         // Generate a set of classes for include statements
4982         private Set<String> getIncludeClasses(Collection<String> methods, InterfaceDecl intDecl, String intface, boolean needExchange) {
4983
4984                 Set<String> includeClasses = new HashSet<String>();
4985                 for (String method : methods) {
4986
4987                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4988                         List<String> methParams = intDecl.getMethodParams(method);
4989                         for (int i = 0; i < methPrmTypes.size(); i++) {
4990
4991                                 String simpleType = getSimpleType(methPrmTypes.get(i));
4992                                 String param = methParams.get(i);
4993                                 if (getParamCategory(simpleType) == ParamCategory.NONPRIMITIVES) {
4994                                         includeClasses.add("<" + getNonPrimitiveCplusClass(simpleType) + ">");
4995                                 } else if (getParamCategory(simpleType) == ParamCategory.USERDEFINED) {
4996                                         // For original interface, we need it exchanged... not for stub interfaces
4997                                         if (needExchange) {
4998                                                 includeClasses.add("\"" + exchangeParamType(simpleType) + ".hpp\"");
4999                                                 includeClasses.add("\"" + exchangeParamType(simpleType) + "_CallbackStub.hpp\"");
5000                                         } else {
5001                                                 includeClasses.add("\"" + simpleType + ".hpp\"");
5002                                                 includeClasses.add("\"" + simpleType + "_CallbackSkeleton.hpp\"");
5003                                         }
5004                                 } else if (getParamCategory(getSimpleArrayType(simpleType)) == ParamCategory.ENUM) {
5005                                         includeClasses.add("\"" + simpleType + ".hpp\"");
5006                                 } else if (getParamCategory(getSimpleArrayType(simpleType)) == ParamCategory.STRUCT) {
5007                                         includeClasses.add("\"" + simpleType + ".hpp\"");
5008                                 } else if (param.contains("[]")) {
5009                                 // Check if this is array for C++; translate into vector
5010                                         includeClasses.add("<vector>");
5011                                 }
5012                         }
5013                 }
5014                 return includeClasses;
5015         }
5016
5017
5018         // Generate a set of callback classes
5019         private Set<String> getCallbackClasses(Collection<String> methods, InterfaceDecl intDecl) {
5020
5021                 Set<String> callbackClasses = new HashSet<String>();
5022                 for (String method : methods) {
5023
5024                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
5025                         List<String> methParams = intDecl.getMethodParams(method);
5026                         for (int i = 0; i < methPrmTypes.size(); i++) {
5027
5028                                 String type = methPrmTypes.get(i);
5029                                 if (getParamCategory(type) == ParamCategory.USERDEFINED) {
5030                                         callbackClasses.add(type);
5031                                 } else if (getParamCategory(type) == ParamCategory.NONPRIMITIVES) {
5032                                 // Can be a List<...> of callback objects ...
5033                                         String genericType = getTypeOfGeneric(type)[0];
5034                                         if (getParamCategory(type) == ParamCategory.USERDEFINED) {
5035                                                 callbackClasses.add(type);
5036                                         }
5037                                 }
5038                         }
5039                 }
5040                 return callbackClasses;
5041         }
5042
5043
5044         // Print import statements into file
5045         private void printImportStatements(Collection<String> importClasses) {
5046
5047                 for(String cls : importClasses) {
5048                         println("import " + cls + ";");
5049                 }
5050         }
5051
5052
5053         // Print include statements into file
5054         private void printIncludeStatements(Collection<String> includeClasses) {
5055
5056                 for(String cls : includeClasses) {
5057                         println("#include " + cls);
5058                 }
5059         }
5060
5061
5062         // Get the C++ version of a non-primitive type
5063         // e.g. set for Set and map for Map
5064         // Input nonPrimitiveType has to be generics in format
5065         private String[] getTypeOfGeneric(String nonPrimitiveType) {
5066
5067                 // Handle <, >, and , for 2-type generic/template
5068                 String[] substr = nonPrimitiveType.split("<")[1].split(">")[0].split(",");
5069                 return substr;
5070         }
5071
5072
5073         // Gets generic type inside "<" and ">"
5074         private String getGenericType(String type) {
5075
5076                 // Handle <, >, and , for 2-type generic/template
5077                 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES) {
5078                         String[] substr = type.split("<")[1].split(">")[0].split(",");
5079                         return substr[0];
5080                 } else
5081                         return type;
5082         }
5083
5084
5085         // This helper function strips off array declaration, e.g. int[] becomes int
5086         private String getSimpleArrayType(String type) {
5087
5088                 // Handle [ for array declaration
5089                 String substr = type;
5090                 if (type.contains("[]")) {
5091                         substr = type.split("\\[\\]")[0];
5092                 }
5093                 return substr;
5094         }
5095
5096
5097         // This helper function strips off array declaration, e.g. D[] becomes D
5098         private String getSimpleIdentifier(String ident) {
5099
5100                 // Handle [ for array declaration
5101                 String substr = ident;
5102                 if (ident.contains("[]")) {
5103                         substr = ident.split("\\[\\]")[0];
5104                 }
5105                 return substr;
5106         }
5107
5108
5109         // Checks and gets type in C++
5110         private String checkAndGetCplusType(String paramType) {
5111
5112                 if (getParamCategory(paramType) == ParamCategory.PRIMITIVES) {
5113                         return convertType(paramType);
5114                 } else if (getParamCategory(paramType) == ParamCategory.NONPRIMITIVES) {
5115
5116                         // Check for generic/template format
5117                         if (paramType.contains("<") && paramType.contains(">")) {
5118
5119                                 String genericClass = getSimpleType(paramType);
5120                                 String genericType = getGenericType(paramType);
5121                                 String cplusTemplate = null;
5122                                 cplusTemplate = getNonPrimitiveCplusClass(genericClass);
5123                                 if(getParamCategory(getGenericType(paramType)) == ParamCategory.USERDEFINED) {
5124                                         cplusTemplate = cplusTemplate + "<" + genericType + "*>";
5125                                 } else {
5126                                         cplusTemplate = cplusTemplate + "<" + convertType(genericType) + ">";
5127                                 }
5128                                 return cplusTemplate;
5129                         } else
5130                                 return getNonPrimitiveCplusClass(paramType);
5131                 } else if(paramType.contains("[]")) {   // Array type (used for return type only)
5132                         String cArray = "vector<" + convertType(getSimpleArrayType(paramType)) + ">";
5133                         return cArray;
5134                 } else if(getParamCategory(paramType) == ParamCategory.USERDEFINED) {
5135                         return paramType + "*";
5136                 } else
5137                         // Just return it as is if it's not non-primitives
5138                         return paramType;
5139         }
5140
5141
5142         // Detect array declaration, e.g. int A[],
5143         //              then generate "int A[]" in C++ as "vector<int> A"
5144         private String checkAndGetCplusArray(String paramType, String param) {
5145
5146                 String paramComplete = null;
5147                 // Check for array declaration
5148                 if (param.contains("[]")) {
5149                         paramComplete = "vector<" + paramType + "> " + param.replace("[]","");
5150                 } else
5151                         // Just return it as is if it's not an array
5152                         paramComplete = paramType + " " + param;
5153
5154                 return paramComplete;
5155         }
5156         
5157
5158         // Detect array declaration, e.g. int A[],
5159         //              then generate "int A[]" in C++ as "vector<int> A"
5160         // This method just returns the type
5161         private String checkAndGetCplusArrayType(String paramType) {
5162
5163                 String paramTypeRet = null;
5164                 // Check for array declaration
5165                 if (paramType.contains("[]")) {
5166                         String type = paramType.split("\\[\\]")[0];
5167                         paramTypeRet = checkAndGetCplusType(type) + "[]";
5168                 } else if (paramType.contains("vector")) {
5169                         // Just return it as is if it's not an array
5170                         String type = paramType.split("<")[1].split(">")[0];
5171                         paramTypeRet = checkAndGetCplusType(type) + "[]";
5172                 } else
5173                         paramTypeRet = paramType;
5174
5175                 return paramTypeRet;
5176         }
5177         
5178         
5179         // Detect array declaration, e.g. int A[],
5180         //              then generate "int A[]" in C++ as "vector<int> A"
5181         // This method just returns the type
5182         private String checkAndGetCplusArrayType(String paramType, String param) {
5183
5184                 String paramTypeRet = null;
5185                 // Check for array declaration
5186                 if (param.contains("[]")) {
5187                         paramTypeRet = checkAndGetCplusType(paramType) + "[]";
5188                 } else if (paramType.contains("vector")) {
5189                         // Just return it as is if it's not an array
5190                         String type = paramType.split("<")[1].split(">")[0];
5191                         paramTypeRet = checkAndGetCplusType(type) + "[]";
5192                 } else
5193                         paramTypeRet = paramType;
5194
5195                 return paramTypeRet;
5196         }
5197
5198
5199         // Return the class type for class resolution (for return value)
5200         // - Check and return C++ array class, e.g. int A[] into int*
5201         // - Check and return C++ vector class, e.g. List<Integer> A into vector<int>
5202         private String checkAndGetCplusRetClsType(String paramType) {
5203
5204                 String paramTypeRet = null;
5205                 // Check for array declaration
5206                 if (paramType.contains("[]")) {
5207                         String type = paramType.split("\\[\\]")[0];
5208                         paramTypeRet = getSimpleArrayType(type) + "*";
5209                 } else if (paramType.contains("<") && paramType.contains(">")) {
5210                         // Just return it as is if it's not an array
5211                         String type = paramType.split("<")[1].split(">")[0];
5212                         paramTypeRet = "vector<" + getGenericType(type) + ">";
5213                 } else
5214                         paramTypeRet = paramType;
5215
5216                 return paramTypeRet;
5217         }
5218
5219
5220         // Return the class type for class resolution (for method arguments)
5221         // - Check and return C++ array class, e.g. int A[] into int*
5222         // - Check and return C++ vector class, e.g. List<Integer> A into vector<int>
5223         private String checkAndGetCplusArgClsType(String paramType, String param) {
5224
5225                 String paramTypeRet = getEnumCplusClsType(paramType);
5226                 if (!paramTypeRet.equals(paramType)) 
5227                 // Just return if it is an enum type
5228                 // Type will still be the same if it's not an enum type
5229                         return paramTypeRet;
5230
5231                 // Check for array declaration
5232                 if (param.contains("[]")) {
5233                         paramTypeRet = getSimpleArrayType(paramType) + "*";
5234                 } else if (paramType.contains("<") && paramType.contains(">")) {
5235                         // Just return it as is if it's not an array
5236                         String type = paramType.split("<")[1].split(">")[0];
5237                         paramTypeRet = "vector<" + getGenericType(type) + ">";
5238                 } else
5239                         paramTypeRet = paramType;
5240
5241                 return paramTypeRet;
5242         }
5243
5244
5245         // Detect array declaration, e.g. int A[],
5246         //              then generate type "int[]"
5247         private String checkAndGetArray(String paramType, String param) {
5248
5249                 String paramTypeRet = null;
5250                 // Check for array declaration
5251                 if (param.contains("[]")) {
5252                         paramTypeRet = paramType + "[]";
5253                 } else
5254                         // Just return it as is if it's not an array
5255                         paramTypeRet = paramType;
5256
5257                 return paramTypeRet;
5258         }
5259
5260
5261         // Is array or list?
5262         private boolean isArrayOrList(String paramType, String param) {
5263
5264                 // Check for array declaration
5265                 if (isArray(param))
5266                         return true;
5267                 else if (isList(paramType))
5268                         return true;
5269                 else
5270                         return false;
5271         }
5272
5273
5274         // Is array? 
5275         // For return type we use retType as input parameter
5276         private boolean isArray(String param) {
5277
5278                 // Check for array declaration
5279                 if (param.contains("[]"))
5280                         return true;
5281                 else
5282                         return false;
5283         }
5284
5285
5286         // Is list?
5287         private boolean isList(String paramType) {
5288
5289                 // Check for array declaration
5290                 if (paramType.contains("List"))
5291                         return true;
5292                 else
5293                         return false;
5294         }
5295
5296
5297         // Get the right type for a callback object
5298         private String checkAndGetParamClass(String paramType) {
5299
5300                 // Check if this is generics
5301                 if(getParamCategory(paramType) == ParamCategory.USERDEFINED) {
5302                         return exchangeParamType(paramType);
5303                 } else if (isList(paramType) &&
5304                                 (getParamCategory(getGenericType(paramType)) == ParamCategory.USERDEFINED)) {
5305                         return "List<" + exchangeParamType(getGenericType(paramType)) + ">";
5306                 } else
5307                         return paramType;
5308         }
5309
5310
5311         // Returns the other interface for type-checking purposes for USERDEFINED
5312         //              classes based on the information provided in multiple policy files
5313         // e.g. return CameraWithXXX instead of Camera
5314         private String exchangeParamType(String intface) {
5315
5316                 // Param type that's passed is the interface name we need to look for
5317                 //              in the map of interfaces, based on available policy files.
5318                 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
5319                 if (decHandler != null) {
5320                 // We've found the required interface policy files
5321                         RequiresDecl reqDecl = (RequiresDecl) decHandler.getRequiresDecl(intface);
5322                         Set<String> setExchInt = reqDecl.getInterfaces();
5323                         if (setExchInt.size() == 1) {
5324                                 Iterator iter = setExchInt.iterator();
5325                                 return (String) iter.next();
5326                         } else {
5327                                 throw new Error("IoTCompiler: Ambiguous stub interfaces: " + setExchInt.toString() + 
5328                                         ". Only one new interface can be declared if the object " + intface +
5329                                         " needs to be passed in as an input parameter!\n");
5330                         }
5331                 } else {
5332                 // NULL value - this means policy files missing
5333                         throw new Error("IoTCompiler: Parameter type lookup failed for " + intface +
5334                                 "... Please provide the necessary policy files for user-defined types." +
5335                                 " If this is an array please type the brackets after the variable name," +
5336                                 " e.g. \"String str[]\", not \"String[] str\"." +
5337                                 " If this is a Collections (Java) / STL (C++) type, this compiler only" +
5338                                 " supports List/ArrayList (Java) or list (C++).\n");
5339                 }
5340         }
5341
5342
5343         public static void main(String[] args) throws Exception {
5344
5345                 // If there is no argument or just "--help" or "-h", then invoke printUsage()
5346                 if ((args[0].equals("-help") ||
5347                          args[0].equals("--help")||
5348                          args[0].equals("-h"))   ||
5349                         (args.length == 0)) {
5350
5351                         IoTCompiler.printUsage();
5352
5353                 } else if (args.length > 1) {
5354
5355                         IoTCompiler comp = new IoTCompiler();
5356                         int i = 0;                              
5357                         do {
5358                                 // Parse main policy file
5359                                 ParseNode pnPol = IoTCompiler.parseFile(args[i]);
5360                                 // Parse "requires" policy file
5361                                 ParseNode pnReq = IoTCompiler.parseFile(args[i+1]);
5362                                 // Get interface name
5363                                 String intface = ParseTreeHandler.getOrigIntface(pnPol);
5364                                 comp.setDataStructures(intface, pnPol, pnReq);
5365                                 comp.getMethodsForIntface(intface);
5366                                 i = i + 2;
5367                         // 1) Check if this is the last option before "-java" or "-cplus"
5368                         // 2) Check if this is really the last option (no "-java" or "-cplus")
5369                         } while(!args[i].equals("-java") &&
5370                                         !args[i].equals("-cplus") &&
5371                                         (i < args.length));
5372
5373                         // Generate everything if we don't see "-java" or "-cplus"
5374                         if (i == args.length) {
5375                                 comp.generateEnumJava();
5376                                 comp.generateStructJava();
5377                                 comp.generateJavaLocalInterfaces();
5378                                 comp.generateJavaInterfaces();
5379                                 comp.generateJavaStubClasses();
5380                                 comp.generateJavaCallbackStubClasses();
5381                                 comp.generateJavaSkeletonClass();
5382                                 comp.generateJavaCallbackSkeletonClass();
5383                                 comp.generateEnumCplus();
5384                                 comp.generateStructCplus();
5385                                 comp.generateCplusLocalInterfaces();
5386                                 comp.generateCPlusInterfaces();
5387                                 comp.generateCPlusStubClasses();
5388                                 comp.generateCPlusCallbackStubClasses();
5389                                 comp.generateCplusSkeletonClass();
5390                                 comp.generateCplusCallbackSkeletonClass();
5391                         } else {
5392                         // Check other options
5393                                 while(i < args.length) {
5394                                         // Error checking
5395                                         if (!args[i].equals("-java") &&
5396                                                 !args[i].equals("-cplus")) {
5397                                                 throw new Error("IoTCompiler: ERROR - unrecognized command line option: " + args[i] + "\n");
5398                                         } else {
5399                                                 if (i + 1 < args.length) {
5400                                                         comp.setDirectory(args[i+1]);
5401                                                 } else
5402                                                         throw new Error("IoTCompiler: ERROR - please provide <directory> after option: " + args[i] + "\n");
5403
5404                                                 if (args[i].equals("-java")) {
5405                                                         comp.generateEnumJava();
5406                                                         comp.generateStructJava();
5407                                                         comp.generateJavaLocalInterfaces();
5408                                                         comp.generateJavaInterfaces();
5409                                                         comp.generateJavaStubClasses();
5410                                                         comp.generateJavaCallbackStubClasses();
5411                                                         comp.generateJavaSkeletonClass();
5412                                                         comp.generateJavaCallbackSkeletonClass();
5413                                                 } else {
5414                                                         comp.generateEnumCplus();
5415                                                         comp.generateStructCplus();
5416                                                         comp.generateCplusLocalInterfaces();
5417                                                         comp.generateCPlusInterfaces();
5418                                                         comp.generateCPlusStubClasses();
5419                                                         comp.generateCPlusCallbackStubClasses();
5420                                                         comp.generateCplusSkeletonClass();
5421                                                         comp.generateCplusCallbackSkeletonClass();
5422                                                 }
5423                                         }
5424                                         i = i + 2;
5425                                 }
5426                         }
5427                 } else {
5428                 // Need to at least have exactly 2 parameters, i.e. main policy file and requires file
5429                         IoTCompiler.printUsage();
5430                         throw new Error("IoTCompiler: At least two arguments (main and requires policy files) have to be provided!\n");
5431                 }
5432         }
5433 }
5434
5435