Adding struct support for Java in compiler
[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          * Class constants
64          */
65         private final static String OUTPUT_DIRECTORY = "output_files";
66
67         private enum ParamCategory {
68
69                 PRIMITIVES,             // All the primitive types, e.g. byte, short, int, long, etc.
70                 NONPRIMITIVES,  // Non-primitive types, e.g. Set, Map, List, etc.
71                 ENUM,                   // Enum type
72                 STRUCT,                 // Struct type
73                 USERDEFINED             // Assumed as driver classes
74         }
75
76         /**
77          * Class constructors
78          */
79         public IoTCompiler() {
80
81                 mapIntfacePTH = new HashMap<String,ParseTreeHandler>();
82                 mapIntDeclHand = new HashMap<String,DeclarationHandler>();
83                 mapInt2NewInts = new HashMap<String,Map<String,Set<String>>>();
84                 mapIntfaceObjId = new HashMap<String,Integer>();
85                 mapNewIntfaceObjId = new HashMap<String,Integer>();
86                 mapPrimitives = new HashMap<String,String>();
87                         arraysToMap(mapPrimitives, IoTRMITypes.primitivesJava, IoTRMITypes.primitivesCplus);
88                 mapNonPrimitivesJava = new HashMap<String,String>();
89                         arraysToMap(mapNonPrimitivesJava, IoTRMITypes.nonPrimitivesJava, IoTRMITypes.nonPrimitiveJavaLibs);
90                 mapNonPrimitivesCplus = new HashMap<String,String>();
91                         arraysToMap(mapNonPrimitivesCplus, IoTRMITypes.nonPrimitivesJava, IoTRMITypes.nonPrimitivesCplus);
92                 pw = null;
93                 dir = OUTPUT_DIRECTORY;
94                 subdir = null;
95         }
96
97
98         /**
99          * setDataStructures() sets parse tree and other data structures based on policy files.
100          * <p>
101          * It also generates parse tree (ParseTreeHandler) and
102          * copies useful information from parse tree into
103          * InterfaceDecl, CapabilityDecl, and RequiresDecl 
104          * data structures.
105          * Additionally, the data structure handles are
106          * returned from tree-parsing for further process.
107          *
108          */
109         public void setDataStructures(String origInt, ParseNode pnPol, ParseNode pnReq) {
110
111                 ParseTreeHandler ptHandler = new ParseTreeHandler(origInt, pnPol, pnReq);
112                 DeclarationHandler decHandler = new DeclarationHandler();
113                 // Process ParseNode and generate Declaration objects
114                 // Interface
115                 ptHandler.processInterfaceDecl();
116                 InterfaceDecl intDecl = ptHandler.getInterfaceDecl();
117                 decHandler.addInterfaceDecl(origInt, intDecl);
118                 // Capabilities
119                 ptHandler.processCapabilityDecl();
120                 CapabilityDecl capDecl = ptHandler.getCapabilityDecl();
121                 decHandler.addCapabilityDecl(origInt, capDecl);
122                 // Requires
123                 ptHandler.processRequiresDecl();
124                 RequiresDecl reqDecl = ptHandler.getRequiresDecl();
125                 decHandler.addRequiresDecl(origInt, reqDecl);
126                 // Enumeration
127                 ptHandler.processEnumDecl();
128                 EnumDecl enumDecl = ptHandler.getEnumDecl();
129                 decHandler.addEnumDecl(origInt, enumDecl);
130                 // Struct
131                 ptHandler.processStructDecl();
132                 StructDecl structDecl = ptHandler.getStructDecl();
133                 decHandler.addStructDecl(origInt, structDecl);
134
135                 mapIntfacePTH.put(origInt, ptHandler);
136                 mapIntDeclHand.put(origInt, decHandler);
137                 // Set object Id counter to 0 for each interface
138                 mapIntfaceObjId.put(origInt, new Integer(0));
139         }
140
141
142         /**
143          * getMethodsForIntface() reads for methods in the data structure
144          * <p>
145          * It is going to give list of methods for a certain interface
146          *              based on the declaration of capabilities.
147          */
148         public void getMethodsForIntface(String origInt) {
149
150                 ParseTreeHandler ptHandler = mapIntfacePTH.get(origInt);
151                 Map<String,Set<String>> mapNewIntMethods = new HashMap<String,Set<String>>();
152                 // Get set of new interfaces, e.g. CameraWithCaptureAndData
153                 // Generate this new interface with all the methods it needs
154                 //              from different capabilities it declares
155                 DeclarationHandler decHandler = mapIntDeclHand.get(origInt);
156                 RequiresDecl reqDecl = (RequiresDecl) decHandler.getRequiresDecl(origInt);
157                 Set<String> setIntfaces = reqDecl.getInterfaces();
158                 for (String strInt : setIntfaces) {
159
160                         // Initialize a set of methods
161                         Set<String> setMethods = new HashSet<String>();
162                         // Get list of capabilities, e.g. ImageCapture, VideoRecording, etc.
163                         List<String> listCapab = reqDecl.getCapabList(strInt);
164                         for (String strCap : listCapab) {
165
166                                 // Get list of methods for each capability
167                                 CapabilityDecl capDecl = (CapabilityDecl) decHandler.getCapabilityDecl(origInt);
168                                 List<String> listCapabMeth = capDecl.getMethods(strCap);
169                                 for (String strMeth : listCapabMeth) {
170
171                                         // Add methods into setMethods
172                                         // This is to also handle redundancies (say two capabilities
173                                         //              share the same methods)
174                                         setMethods.add(strMeth);
175                                 }
176                         }
177                         // Add interface and methods information into map
178                         mapNewIntMethods.put(strInt, setMethods);
179                 }
180                 // Map the map of interface-methods to the original interface
181                 mapInt2NewInts.put(origInt, mapNewIntMethods);
182         }
183
184
185         /**
186          * HELPER: writeMethodJavaLocalInterface() writes the method of the interface
187          */
188         private void writeMethodJavaLocalInterface(Collection<String> methods, InterfaceDecl intDecl) {
189
190                 for (String method : methods) {
191
192                         List<String> methParams = intDecl.getMethodParams(method);
193                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
194                         print("public " + intDecl.getMethodType(method) + " " +
195                                 intDecl.getMethodId(method) + "(");
196                         for (int i = 0; i < methParams.size(); i++) {
197                                 // Check for params with driver class types and exchange it 
198                                 //              with its remote interface
199                                 String paramType = checkAndGetParamClass(methPrmTypes.get(i));
200                                 print(paramType + " " + methParams.get(i));
201                                 // Check if this is the last element (don't print a comma)
202                                 if (i != methParams.size() - 1) {
203                                         print(", ");
204                                 }
205                         }
206                         println(");");
207                 }
208         }
209
210
211         /**
212          * HELPER: writeMethodJavaInterface() writes the method of the interface
213          */
214         private void writeMethodJavaInterface(Collection<String> methods, InterfaceDecl intDecl) {
215
216                 for (String method : methods) {
217
218                         List<String> methParams = intDecl.getMethodParams(method);
219                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
220                         print("public " + intDecl.getMethodType(method) + " " +
221                                 intDecl.getMethodId(method) + "(");
222                         for (int i = 0; i < methParams.size(); i++) {
223                                 // Check for params with driver class types and exchange it 
224                                 //              with its remote interface
225                                 String paramType = methPrmTypes.get(i);
226                                 print(paramType + " " + methParams.get(i));
227                                 // Check if this is the last element (don't print a comma)
228                                 if (i != methParams.size() - 1) {
229                                         print(", ");
230                                 }
231                         }
232                         println(");");
233                 }
234         }
235
236
237         /**
238          * HELPER: generateEnumJava() writes the enumeration declaration
239          */
240         private void generateEnumJava() throws IOException {
241
242                 // Create a new directory
243                 createDirectory(dir);
244                 for (String intface : mapIntfacePTH.keySet()) {
245                         // Get the right EnumDecl
246                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
247                         EnumDecl enumDecl = (EnumDecl) decHandler.getEnumDecl(intface);
248                         Set<String> enumTypes = enumDecl.getEnumDeclarations();
249                         // Iterate over enum declarations
250                         for (String enType : enumTypes) {
251                                 // Open a new file to write into
252                                 FileWriter fw = new FileWriter(dir + "/" + enType + ".java");
253                                 pw = new PrintWriter(new BufferedWriter(fw));
254                                 println("public enum " + enType + " {");
255                                 List<String> enumMembers = enumDecl.getMembers(enType);
256                                 for (int i = 0; i < enumMembers.size(); i++) {
257
258                                         String member = enumMembers.get(i);
259                                         print(member);
260                                         // Check if this is the last element (don't print a comma)
261                                         if (i != enumMembers.size() - 1)
262                                                 println(",");
263                                         else
264                                                 println("");
265                                 }
266                                 println("}\n");
267                                 pw.close();
268                                 System.out.println("IoTCompiler: Generated enum class " + enType + ".java...");
269                         }
270                 }
271         }
272
273
274         /**
275          * HELPER: generateStructJava() writes the struct declaration
276          */
277         private void generateStructJava() throws IOException {
278
279                 // Create a new directory
280                 createDirectory(dir);
281                 for (String intface : mapIntfacePTH.keySet()) {
282                         // Get the right StructDecl
283                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
284                         StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
285                         List<String> structTypes = structDecl.getStructTypes();
286                         // Iterate over enum declarations
287                         for (String stType : structTypes) {
288                                 // Open a new file to write into
289                                 FileWriter fw = new FileWriter(dir + "/" + stType + ".java");
290                                 pw = new PrintWriter(new BufferedWriter(fw));
291                                 println("public class " + stType + " {");
292                                 List<String> structMemberTypes = structDecl.getMemberTypes(stType);
293                                 List<String> structMembers = structDecl.getMembers(stType);
294                                 for (int i = 0; i < structMembers.size(); i++) {
295
296                                         String memberType = structMemberTypes.get(i);
297                                         String member = structMembers.get(i);
298                                         println("public static " + memberType + " " + member + ";");
299                                 }
300                                 println("}\n");
301                                 pw.close();
302                                 System.out.println("IoTCompiler: Generated struct class " + stType + ".java...");
303                         }
304                 }
305         }
306
307
308         /**
309          * generateJavaLocalInterface() writes the local interface and provides type-checking.
310          * <p>
311          * It needs to rewrite and exchange USERDEFINED types in input parameters of stub
312          * and original interfaces, e.g. exchange Camera and CameraWithVideoAndRecording.
313          * The local interface has to be the input parameter for the stub and the stub 
314          * interface has to be the input parameter for the local class.
315          */
316         public void generateJavaLocalInterfaces() throws IOException {
317
318                 // Create a new directory
319                 createDirectory(dir);
320                 for (String intface : mapIntfacePTH.keySet()) {
321                         // Open a new file to write into
322                         FileWriter fw = new FileWriter(dir + "/" + intface + ".java");
323                         pw = new PrintWriter(new BufferedWriter(fw));
324                         // Pass in set of methods and get import classes
325                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
326                         InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
327                         List<String> methods = intDecl.getMethods();
328                         Set<String> importClasses = getImportClasses(methods, intDecl);
329                         printImportStatements(importClasses);
330                         // Write interface header
331                         println("");
332                         println("public interface " + intface + " {");
333                         // Write enum if any...
334                         //EnumDecl enumDecl = (EnumDecl) decHandler.getEnumDecl(intface);
335                         //writeEnumJava(enumDecl);
336                         // Write struct if any...
337                         //StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
338                         //writeStructJava(structDecl);
339                         // Write methods
340                         writeMethodJavaLocalInterface(methods, intDecl);
341                         println("}");
342                         pw.close();
343                         System.out.println("IoTCompiler: Generated local interface " + intface + ".java...");
344                 }
345         }
346
347
348         /**
349          * generateJavaInterfaces() generate stub interfaces based on the methods list in Java
350          */
351         public void generateJavaInterfaces() throws IOException {
352
353                 // Create a new directory
354                 String path = createDirectories(dir, subdir);
355                 for (String intface : mapIntfacePTH.keySet()) {
356
357                         Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
358                         for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
359
360                                 // Open a new file to write into
361                                 String newIntface = intMeth.getKey();
362                                 FileWriter fw = new FileWriter(path + "/" + newIntface + ".java");
363                                 pw = new PrintWriter(new BufferedWriter(fw));
364                                 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
365                                 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
366                                 // Pass in set of methods and get import classes
367                                 Set<String> importClasses = getImportClasses(intMeth.getValue(), intDecl);
368                                 printImportStatements(importClasses);
369                                 // Write interface header
370                                 println("");
371                                 println("public interface " + newIntface + " {\n");
372                                 // Write methods
373                                 writeMethodJavaInterface(intMeth.getValue(), 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 = mapNewIntfaceObjId.get(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 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 = mapNewIntfaceObjId.get(newIntface);
450                         println("set" + newObjectId + "Allowed = 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 = mapNewIntfaceObjId.get(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: writeConstructorJavaStub() writes the constructor of the stub class
495          */
496         private void writeInitCallbackJavaStub(String intface, InterfaceDecl intDecl) {
497
498                 println("public void ___initCallBack() {");
499                 // Generate main thread for callbacks
500                 println("Thread thread = new Thread() {");
501                 println("public void run() {");
502                 println("try {");
503                 println("rmiObj = new IoTRMIObject(ports[0]);");
504                 println("while (true) {");
505                 println("byte[] method = rmiObj.getMethodBytes();");
506                 writeJavaMethodCallbackPermission(intface);
507                 println("int objId = IoTRMIObject.getObjectId(method);");
508                 println(intface + "_CallbackSkeleton skel = (" + intface + "_CallbackSkeleton) listCallbackObj.get(objId);");
509                 println("if (skel != null) {");
510                 println("skel.invokeMethod(rmiObj);");
511                 println("} else {");
512                 println("throw new Error(\"" + intface + ": Object with Id \" + objId + \" not found!\");");
513                 println("}");
514                 println("}");
515                 println("} catch (Exception ex) {");
516                 println("ex.printStackTrace();");
517                 println("throw new Error(\"Error instantiating class " + intface + "_CallbackSkeleton!\");");
518                 println("}");
519                 println("}");
520                 println("};");
521                 println("thread.start();\n");
522                 // Generate info sending part
523                 String method = "___initCallBack()";
524                 println("int methodId = " + intDecl.getHelperMethodNumId(method) + ";");
525                 println("Class<?> retType = void.class;");
526                 println("Class<?>[] paramCls = new Class<?>[] { int.class, String.class, int.class };");
527                 println("Object[] paramObj = new Object[] { ports[0], address, 0 };");
528                 println("rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
529                 println("}\n");
530         }
531
532
533         /**
534          * HELPER: checkAndWriteEnumTypeJavaStub() writes the enum type (convert from enum to int)
535          */
536         private void checkAndWriteEnumTypeJavaStub(List<String> methParams, List<String> methPrmTypes) {
537
538                 // Iterate and find enum declarations
539                 for (int i = 0; i < methParams.size(); i++) {
540                         String paramType = methPrmTypes.get(i);
541                         String param = methParams.get(i);
542                         String simpleType = getSimpleType(paramType);
543                         if (isEnumClass(simpleType)) {
544                         // Check if this is enum type
545                                 if (isArray(param)) {   // An array
546                                         println("int len" + i + " = " + param + ".length;");
547                                         println("int paramEnum" + i + "[] = new int[len];");
548                                         println("for (int i = 0; i < len" + i + "; i++) {");
549                                         println("paramEnum" + i + "[i] = " + param + "[i].ordinal();");
550                                         println("}");
551                                 } else if (isList(paramType)) { // A list
552                                         println("int len" + i + " = " + param + ".size();");
553                                         println("int paramEnum" + i + "[] = new int[len];");
554                                         println("for (int i = 0; i < len" + i + "; i++) {");
555                                         println("paramEnum" + i + "[i] = " + param + ".get(i).ordinal();");
556                                         println("}");
557                                 } else {        // Just one element
558                                         println("int paramEnum" + i + "[] = new int[1];");
559                                         println("paramEnum" + i + "[0] = " + param + ".ordinal();");
560                                 }
561                         }
562                 }
563         }
564
565
566         /**
567          * HELPER: checkAndWriteEnumRetTypeJavaStub() writes the enum return type (convert from enum to int)
568          */
569         private void checkAndWriteEnumRetTypeJavaStub(String retType) {
570
571                 // Strips off array "[]" for return type
572                 String pureType = getSimpleArrayType(getSimpleType(retType));
573                 // Take the inner type of generic
574                 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
575                         pureType = getTypeOfGeneric(retType)[0];
576                 if (isEnumClass(pureType)) {
577                 // Check if this is enum type
578                         // Enum decoder
579                         println("int[] retEnum = (int[]) retObj;");
580                         println(pureType + "[] enumVals = " + pureType + ".values();");
581                         if (isArray(retType)) {                 // An array
582                                 println("int retLen = retEnum.length;");
583                                 println(pureType + "[] enumRetVal = new " + pureType + "[retLen];");
584                                 println("for (int i = 0; i < retLen; i++) {");
585                                 println("enumRetVal[i] = enumVals[retEnum[i]];");
586                                 println("}");
587                         } else if (isList(retType)) {   // A list
588                                 println("int retLen = retEnum.length;");
589                                 println("List<" + pureType + "> enumRetVal = new ArrayList<" + pureType + ">();");
590                                 println("for (int i = 0; i < retLen; i++) {");
591                                 println("enumRetVal.add(enumVals[retEnum[i]]);");
592                                 println("}");
593                         } else {        // Just one element
594                                 println(pureType + " enumRetVal = enumVals[retEnum[0]];");
595                         }
596                         println("return enumRetVal;");
597                 }
598         }
599
600
601         /**
602          * HELPER: checkAndWriteStructSetupJavaStub() writes the struct type setup
603          */
604         private void checkAndWriteStructSetupJavaStub(List<String> methParams, List<String> methPrmTypes, 
605                         InterfaceDecl intDecl, String method) {
606                 
607                 // Iterate and find struct declarations
608                 for (int i = 0; i < methParams.size(); i++) {
609                         String paramType = methPrmTypes.get(i);
610                         String param = methParams.get(i);
611                         String simpleType = getSimpleType(paramType);
612                         if (isStructClass(simpleType)) {
613                         // Check if this is enum type
614                                 int methodNumId = intDecl.getMethodNumId(method);
615                                 String helperMethod = methodNumId + "struct" + i;
616                                 println("int methodIdStruct" + i + " = " + intDecl.getHelperMethodNumId(helperMethod) + ";");
617                                 println("Class<?> retTypeStruct" + i + " = void.class;");
618                                 println("Class<?>[] paramClsStruct" + i + " = new Class<?>[] { int.class };");
619                                 if (isArray(param)) {   // An array
620                                         println("Object[] paramObjStruct" + i + " = new Object[] { " + getSimpleArrayType(param) + ".length };");
621                                 } else if (isList(paramType)) { // A list
622                                         println("Object[] paramObjStruct" + i + " = new Object[] { " + getSimpleArrayType(param) + ".size() };");
623                                 } else {        // Just one element
624                                         println("Object[] paramObjStruct" + i + " = new Object[] { new Integer(1) };");
625                                 }
626                                 println("rmiCall.remoteCall(objectId, methodIdStruct" + i + 
627                                                 ", retTypeStruct" + i + ", null, paramClsStruct" + i + 
628                                                 ", paramObjStruct" + i + ");\n");
629                         }
630                 }
631         }
632
633
634         /**
635          * HELPER: isStructPresent() checks presence of struct
636          */
637         private boolean isStructPresent(List<String> methParams, List<String> methPrmTypes) {
638
639                 // Iterate and find enum declarations
640                 for (int i = 0; i < methParams.size(); i++) {
641                         String paramType = methPrmTypes.get(i);
642                         String param = methParams.get(i);
643                         String simpleType = getSimpleType(paramType);
644                         if (isStructClass(simpleType))
645                                 return true;
646                 }
647                 return false;
648         }
649
650
651         /**
652          * HELPER: writeLengthStructParamClassJavaStub() writes lengths of params
653          */
654         private void writeLengthStructParamClassJavaStub(List<String> methParams, List<String> methPrmTypes) {
655
656                 // Iterate and find struct declarations - count number of params
657                 for (int i = 0; i < methParams.size(); i++) {
658                         String paramType = methPrmTypes.get(i);
659                         String param = methParams.get(i);
660                         String simpleType = getGenericType(paramType);
661                         if (isStructClass(simpleType)) {
662                                 int members = getNumOfMembers(simpleType);
663                                 if (isArray(param)) {                   // An array
664                                         String structLen = param + ".length";
665                                         print(members + "*" + structLen);
666                                 } else if (isList(paramType)) { // A list
667                                         String structLen = param + ".size()";
668                                         print(members + "*" + structLen);
669                                 } else
670                                         print(Integer.toString(members));
671                         } else
672                                 print("1");
673                         if (i != methParams.size() - 1) {
674                                 print("+");
675                         }
676                 }
677         }
678
679
680         /**
681          * HELPER: writeStructMembersJavaStub() writes parameters of struct
682          */
683         private void writeStructMembersJavaStub(String simpleType, String paramType, String param) {
684
685                 // Get the struct declaration for this struct and generate initialization code
686                 StructDecl structDecl = getStructDecl(simpleType);
687                 List<String> memTypes = structDecl.getMemberTypes(simpleType);
688                 List<String> members = structDecl.getMembers(simpleType);
689                 if (isArray(param)) {                   // An array
690                         println("for(int i = 0; i < " + param + ".length; i++) {");
691                 } else if (isList(paramType)) { // A list
692                         println("for(int i = 0; i < " + param + ".size(); i++) {");
693                 }
694                 if (isArrayOrList(param, paramType)) {  // An array or list
695                         for (int i = 0; i < members.size(); i++) {
696                                 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
697                                 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
698                                 print("paramObj[pos++] = " + param + "[i].");
699                                 print(getSimpleIdentifier(members.get(i)));
700                                 println(";");
701                         }
702                         println("}");
703                 } else {        // Just one struct element
704                         for (int i = 0; i < members.size(); i++) {
705                                 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
706                                 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
707                                 print("paramObj[pos++] = " + param + ".");
708                                 print(getSimpleIdentifier(members.get(i)));
709                                 println(";");
710                         }
711                 }
712         }
713
714
715         /**
716          * HELPER: writeStructParamClassJavaStub() writes parameters if struct is present
717          */
718         private void writeStructParamClassJavaStub(List<String> methParams, List<String> methPrmTypes) {
719
720                 print("int paramLen = ");
721                 writeLengthStructParamClassJavaStub(methParams, methPrmTypes);
722                 println(";");
723                 println("Object[] paramObj = new Object[paramLen];");
724                 println("Class<?>[] paramCls = new Class<?>[paramLen];");
725                 println("int pos = 0;");
726                 // Iterate again over the parameters
727                 for (int i = 0; i < methParams.size(); i++) {
728                         String paramType = methPrmTypes.get(i);
729                         String param = methParams.get(i);
730                         String simpleType = getGenericType(paramType);
731                         if (isStructClass(simpleType)) {
732                                 writeStructMembersJavaStub(simpleType, paramType, param);
733                         } else {
734                                 String prmType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
735                                 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
736                                 print("paramObj[pos++] = ");
737                                 print(getEnumParam(methPrmTypes.get(i), getSimpleIdentifier(methParams.get(i)), i));
738                                 println(";");
739                         }
740                 }
741                 
742         }
743
744
745         /**
746          * HELPER: writeStructRetMembersJavaStub() writes parameters of struct
747          */
748         private void writeStructRetMembersJavaStub(String simpleType, String retType) {
749
750                 // Get the struct declaration for this struct and generate initialization code
751                 StructDecl structDecl = getStructDecl(simpleType);
752                 List<String> memTypes = structDecl.getMemberTypes(simpleType);
753                 List<String> members = structDecl.getMembers(simpleType);
754                 if (isArrayOrList(retType, retType)) {  // An array or list
755                         println("for(int i = 0; i < retLen.length; i++) {");
756                 }
757                 if (isArray(retType)) { // An array
758                         for (int i = 0; i < members.size(); i++) {
759                                 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
760                                 print("structRet[i]." + getSimpleIdentifier(members.get(i)));
761                                 println(" = (" + getSimpleType(getEnumType(prmType)) + ") retObj[retObjPos++];");
762                         }
763                         println("}");
764                 } else if (isList(retType)) {   // A list
765                         println(simpleType + " structRetMem = new " + simpleType + "();");
766                         for (int i = 0; i < members.size(); i++) {
767                                 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
768                                 print("structRetMem." + getSimpleIdentifier(members.get(i)));
769                                 println(" = (" + getSimpleType(getEnumType(prmType)) + ") retObj[retObjPos++];");
770                         }
771                         println("structRet.add(structRetMem);");
772                         println("}");
773                 } else {        // Just one struct element
774                         for (int i = 0; i < members.size(); i++) {
775                                 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
776                                 print("structRet." + getSimpleIdentifier(members.get(i)));
777                                 println(" = (" + getSimpleType(getEnumType(prmType)) + ") retObj[retObjPos++];");
778                         }
779                 }
780                 println("return structRet;");
781         }
782
783
784         /**
785          * HELPER: writeStructReturnJavaStub() writes parameters if struct is present
786          */
787         private void writeStructReturnJavaStub(String simpleType, String retType) {
788
789                 // Handle the returned struct!!!
790                 println("Object retLenObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
791                 // Minimum retLen is 1 if this is a single struct object
792                 println("int retLen = (int) retLenObj;");
793                 int numMem = getNumOfMembers(simpleType);
794                 println("Class<?>[] retCls = new Class<?>[" + numMem + "*retLen];");
795                 println("Class<?>[] retClsVal = new Class<?>[" + numMem + "*retLen];");
796                 println("int retPos = 0;");
797                 // Get the struct declaration for this struct and generate initialization code
798                 StructDecl structDecl = getStructDecl(simpleType);
799                 List<String> memTypes = structDecl.getMemberTypes(simpleType);
800                 List<String> members = structDecl.getMembers(simpleType);
801                 if (isArrayOrList(retType, retType)) {  // An array or list
802                         println("for(int i = 0; i < retLen; i++) {");
803                         for (int i = 0; i < members.size(); i++) {
804                                 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
805                                 println("retCls[retPos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
806                                 println("retClsVal[retPos++] = null;");
807                         }
808                         println("}");
809                 } else {        // Just one struct element
810                         for (int i = 0; i < members.size(); i++) {
811                                 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
812                                 println("retCls[retPos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
813                                 println("retClsVal[retPos++] = null;");
814                         }
815                 }
816                 println("Object[] retObj = rmiCall.getStructObjects(retCls, retClsVal);");
817                 if (isArray(retType)) {                 // An array
818                         println(simpleType + "[] structRet = new " + simpleType + "[retLen];");
819                         println("for(int i = 0; i < retLen; i++) {");
820                         println("structRet[i] = new " + simpleType + "();");
821                         println("}");
822                 } else if (isList(retType)) {   // A list
823                         println("List<" + simpleType + "> structRet = new ArrayList<" + simpleType + ">();");
824                 } else
825                         println(simpleType + " structRet = new " + simpleType + "();");
826                 println("int retObjPos = 0;");
827                 writeStructRetMembersJavaStub(simpleType, retType);
828         }
829
830
831         /**
832          * HELPER: writeStdMethodBodyJavaStub() writes the standard method body in the stub class
833          */
834         private void writeStdMethodBodyJavaStub(InterfaceDecl intDecl, List<String> methParams,
835                         List<String> methPrmTypes, String method) {
836
837                 checkAndWriteStructSetupJavaStub(methParams, methPrmTypes, intDecl, method);
838                 println("int methodId = " + intDecl.getMethodNumId(method) + ";");
839                 String retType = intDecl.getMethodType(method);
840                 println("Class<?> retType = " + getSimpleType(getStructType(getEnumType(retType))) + ".class;");
841                 checkAndWriteEnumTypeJavaStub(methParams, methPrmTypes);
842                 // Generate array of parameter types
843                 if (isStructPresent(methParams, methPrmTypes)) {
844                         writeStructParamClassJavaStub(methParams, methPrmTypes);
845                 } else {
846                         print("Class<?>[] paramCls = new Class<?>[] { ");
847                         for (int i = 0; i < methParams.size(); i++) {
848                                 String paramType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
849                                 print(getSimpleType(getEnumType(paramType)) + ".class");
850                                 // Check if this is the last element (don't print a comma)
851                                 if (i != methParams.size() - 1) {
852                                         print(", ");
853                                 }
854                         }
855                         println(" };");
856                         // Generate array of parameter objects
857                         print("Object[] paramObj = new Object[] { ");
858                         for (int i = 0; i < methParams.size(); i++) {
859                                 print(getEnumParam(methPrmTypes.get(i), getSimpleIdentifier(methParams.get(i)), i));
860                                 // Check if this is the last element (don't print a comma)
861                                 if (i != methParams.size() - 1) {
862                                         print(", ");
863                                 }
864                         }
865                         println(" };");
866                 }
867                 // Check if this is "void"
868                 if (retType.equals("void")) {
869                         println("rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
870                 } else { // We do have a return value
871                         // Generate array of parameter types
872                         if (isStructClass(getGenericType(getSimpleArrayType(retType)))) {
873                                 writeStructReturnJavaStub(getGenericType(getSimpleArrayType(retType)), retType);
874                         } else {
875                         // Check if the return value NONPRIMITIVES
876                                 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES) {
877                                         String[] retGenValType = getTypeOfGeneric(retType);
878                                         println("Class<?> retGenValType = " + retGenValType[0] + ".class;");
879                                         println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, retGenValType, paramCls, paramObj);");
880                                         println("return (" + retType + ")retObj;");
881                                 } else if (getParamCategory(retType) == ParamCategory.ENUM) {
882                                 // This is an enum type
883                                         println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
884                                         checkAndWriteEnumRetTypeJavaStub(retType);
885                                 } else {
886                                         println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
887                                         println("return (" + retType + ")retObj;");
888                                 }
889                         }
890                 }
891         }
892
893
894         /**
895          * HELPER: returnGenericCallbackType() returns the callback type
896          */
897         private String returnGenericCallbackType(String paramType) {
898
899                 if (getParamCategory(paramType) == ParamCategory.NONPRIMITIVES)
900                         return getTypeOfGeneric(paramType)[0];
901                 else
902                         return paramType;
903         }
904
905
906         /**
907          * HELPER: checkCallbackType() checks the callback type
908          */
909         private boolean checkCallbackType(String paramType, String callbackType) {
910
911                 String prmType = returnGenericCallbackType(paramType);
912                 return callbackType.equals(prmType);
913         }
914
915
916         /**
917          * HELPER: writeCallbackMethodBodyJavaStub() writes the callback method of the stub class
918          */
919         private void writeCallbackMethodBodyJavaStub(InterfaceDecl intDecl, List<String> methParams,
920                         List<String> methPrmTypes, String method, String callbackType) {
921
922                 println("try {");
923                 // Check if this is single object, array, or list of objects
924                 for (int i = 0; i < methParams.size(); i++) {
925
926                         String paramType = methPrmTypes.get(i);
927                         if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
928                                 String param = methParams.get(i);
929                                 if (isArrayOrList(paramType, param)) {  // Generate loop
930                                         println("for (" + paramType + " cb : " + getSimpleIdentifier(param) + ") {");
931                                         println(callbackType + "_CallbackSkeleton skel = new " + callbackType + "_CallbackSkeleton(cb, objIdCnt++);");
932                                 } else
933                                         println(callbackType + "_CallbackSkeleton skel = new " + callbackType + "_CallbackSkeleton(" +
934                                                 getSimpleIdentifier(param) + ", objIdCnt++);");
935                                 println("listCallbackObj.add(skel);");
936                                 if (isArrayOrList(paramType, param))
937                                         println("}");
938                         }
939                 }
940                 println("} catch (Exception ex) {");
941                 println("ex.printStackTrace();");
942                 println("throw new Error(\"Exception when generating skeleton objects!\");");
943                 println("}\n");
944                 println("int methodId = " + intDecl.getMethodNumId(method) + ";");
945                 String retType = intDecl.getMethodType(method);
946                 println("Class<?> retType = " + getSimpleType(getEnumType(retType)) + ".class;");
947                 // Generate array of parameter types
948                 print("Class<?>[] paramCls = new Class<?>[] { ");
949                 for (int i = 0; i < methParams.size(); i++) {
950                         String paramType = methPrmTypes.get(i);
951                         if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
952                                 print("int.class");
953                         } else { // Generate normal classes if it's not a callback object
954                                 String prmType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
955                                 print(getSimpleType(prmType) + ".class");
956                         }
957                         if (i != methParams.size() - 1) // Check if this is the last element
958                                 print(", ");
959                 }
960                 println(" };");
961                 // Generate array of parameter objects
962                 print("Object[] paramObj = new Object[] { ");
963                 for (int i = 0; i < methParams.size(); i++) {
964                         String paramType = methPrmTypes.get(i);
965                         if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
966                                 //if (isArray(methPrmTypes.get(i), methParams.get(i)))
967                                 if (isArray(methParams.get(i)))
968                                         print(getSimpleIdentifier(methParams.get(i)) + ".length");
969                                 else if (isList(methPrmTypes.get(i)))
970                                         print(getSimpleIdentifier(methParams.get(i)) + ".size()");
971                                 else
972                                         print("new Integer(1)");
973                         } else
974                                 print(getSimpleIdentifier(methParams.get(i)));
975                         if (i != methParams.size() - 1)
976                                 print(", ");
977                 }
978                 println(" };");
979                 // Check if this is "void"
980                 if (retType.equals("void")) {
981                         println("rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
982                 } else { // We do have a return value
983                 // Check if the return value NONPRIMITIVES
984                         if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES) {
985                                 String[] retGenValType = getTypeOfGeneric(retType);
986                                 println("Class<?> retGenValType = " + retGenValType[0] + ".class;");
987                                 println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, retGenValType, paramCls, paramObj);");
988                                 println("return (" + retType + ")retObj;");
989                         } else {
990                                 println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
991                                 println("return (" + retType + ")retObj;");
992                         }
993                 }
994         }
995
996
997         /**
998          * HELPER: writeMethodJavaStub() writes the method of the stub class
999          */
1000         private void writeMethodJavaStub(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
1001
1002                 for (String method : methods) {
1003
1004                         List<String> methParams = intDecl.getMethodParams(method);
1005                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1006                         print("public " + intDecl.getMethodType(method) + " " +
1007                                 intDecl.getMethodId(method) + "(");
1008                         boolean isCallbackMethod = false;
1009                         String callbackType = null;
1010                         for (int i = 0; i < methParams.size(); i++) {
1011
1012                                 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
1013                                 // Check if this has callback object
1014                                 if (callbackClasses.contains(paramType)) {
1015                                         isCallbackMethod = true;
1016                                         callbackType = paramType;       
1017                                         // Even if there're 2 callback arguments, we expect them to be of the same interface
1018                                 }
1019                                 print(methPrmTypes.get(i) + " " + methParams.get(i));
1020                                 // Check if this is the last element (don't print a comma)
1021                                 if (i != methParams.size() - 1) {
1022                                         print(", ");
1023                                 }
1024                         }
1025                         println(") {");
1026                         // Now, write the body of stub!
1027                         if (isCallbackMethod)
1028                                 writeCallbackMethodBodyJavaStub(intDecl, methParams, methPrmTypes, method, callbackType);
1029                         else
1030                                 writeStdMethodBodyJavaStub(intDecl, methParams, methPrmTypes, method);
1031                         println("}\n");
1032                         // Write the init callback helper method
1033                         if (isCallbackMethod)
1034                                 writeInitCallbackJavaStub(callbackType, intDecl);
1035                 }
1036         }
1037
1038
1039         /**
1040          * generateJavaStubClasses() generate stubs based on the methods list in Java
1041          */
1042         public void generateJavaStubClasses() throws IOException {
1043
1044                 // Create a new directory
1045                 String path = createDirectories(dir, subdir);
1046                 for (String intface : mapIntfacePTH.keySet()) {
1047
1048                         Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
1049                         for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
1050
1051                                 // Open a new file to write into
1052                                 String newIntface = intMeth.getKey();
1053                                 String newStubClass = newIntface + "_Stub";
1054                                 FileWriter fw = new FileWriter(path + "/" + newStubClass + ".java");
1055                                 pw = new PrintWriter(new BufferedWriter(fw));
1056                                 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
1057                                 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
1058                                 // Pass in set of methods and get import classes
1059                                 Set<String> methods = intMeth.getValue();
1060                                 Set<String> importClasses = getImportClasses(methods, intDecl);
1061                                 List<String> stdImportClasses = getStandardJavaImportClasses();
1062                                 List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
1063                                 printImportStatements(allImportClasses); println("");
1064                                 // Find out if there are callback objects
1065                                 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
1066                                 boolean callbackExist = !callbackClasses.isEmpty();
1067                                 // Write class header
1068                                 println("public class " + newStubClass + " implements " + newIntface + " {\n");
1069                                 // Write properties
1070                                 writePropertiesJavaStub(intface, newIntface, callbackExist, callbackClasses);
1071                                 // Write constructor
1072                                 writeConstructorJavaStub(intface, newStubClass, callbackExist, callbackClasses);
1073                                 // Write methods
1074                                 writeMethodJavaStub(intMeth.getValue(), intDecl, callbackClasses);
1075                                 println("}");
1076                                 pw.close();
1077                                 System.out.println("IoTCompiler: Generated stub class " + newStubClass + ".java...");
1078                         }
1079                 }
1080         }
1081
1082
1083         /**
1084          * HELPER: writePropertiesJavaCallbackStub() writes the properties of the callback stub class
1085          */
1086         private void writePropertiesJavaCallbackStub(String intface, String newIntface, boolean callbackExist, Set<String> callbackClasses) {
1087
1088                 println("private IoTRMICall rmiCall;");
1089                 println("private String address;");
1090                 println("private int[] ports;\n");
1091                 // Get the object Id
1092                 println("private static int objectId = 0;");
1093                 if (callbackExist) {
1094                 // We assume that each class only has one callback interface for now
1095                         Iterator it = callbackClasses.iterator();
1096                         String callbackType = (String) it.next();
1097                         println("// Callback properties");
1098                         println("private IoTRMIObject rmiObj;");
1099                         println("List<" + callbackType + "> listCallbackObj;");
1100                         println("private static int objIdCnt = 0;");
1101                         // Generate permission stuff for callback stubs
1102                         DeclarationHandler decHandler = mapIntDeclHand.get(callbackType);
1103                         InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(callbackType);
1104                         writePropertiesJavaPermission(callbackType, intDecl);
1105                 }
1106                 println("\n");
1107         }
1108
1109
1110         /**
1111          * HELPER: writeConstructorJavaCallbackStub() writes the constructor of the callback stub class
1112          */
1113         private void writeConstructorJavaCallbackStub(String intface, String newStubClass, boolean callbackExist, Set<String> callbackClasses) {
1114
1115                 // TODO: If we want callback in callback, then we need to add address and port initializations
1116                 println("public " + newStubClass + "(IoTRMICall _rmiCall, int _objectId) throws Exception {");
1117                 println("objectId = _objectId;");
1118                 println("rmiCall = _rmiCall;");
1119                 if (callbackExist) {
1120                         Iterator it = callbackClasses.iterator();
1121                         String callbackType = (String) it.next();
1122                         writeConstructorJavaPermission(intface);
1123                         println("listCallbackObj = new ArrayList<" + callbackType + ">();");
1124                         println("___initCallBack();");
1125                         println("// TODO: Add address and port initialization here if we want callback in callback!");
1126                 }
1127                 println("}\n");
1128         }
1129
1130
1131         /**
1132          * generateJavaCallbackStubClasses() generate callback stubs based on the methods list in Java
1133          * <p>
1134          * Callback stubs gets the IoTRMICall objects from outside of the class as contructor input
1135          * because all these stubs are populated by the class that takes in this object as a callback
1136          * object. In such a class, we only use one socket, hence one IoTRMICall, for all callback objects.
1137          */
1138         public void generateJavaCallbackStubClasses() throws IOException {
1139
1140                 // Create a new directory
1141                 String path = createDirectories(dir, subdir);
1142                 for (String intface : mapIntfacePTH.keySet()) {
1143
1144                         Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
1145                         for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
1146
1147                                 // Open a new file to write into
1148                                 String newIntface = intMeth.getKey();
1149                                 String newStubClass = newIntface + "_CallbackStub";
1150                                 FileWriter fw = new FileWriter(path + "/" + newStubClass + ".java");
1151                                 pw = new PrintWriter(new BufferedWriter(fw));
1152                                 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
1153                                 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
1154                                 // Pass in set of methods and get import classes
1155                                 Set<String> methods = intMeth.getValue();
1156                                 Set<String> importClasses = getImportClasses(methods, intDecl);
1157                                 List<String> stdImportClasses = getStandardJavaImportClasses();
1158                                 List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
1159                                 printImportStatements(allImportClasses); println("");
1160                                 // Find out if there are callback objects
1161                                 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
1162                                 boolean callbackExist = !callbackClasses.isEmpty();
1163                                 // Write class header
1164                                 println("public class " + newStubClass + " implements " + newIntface + " {\n");
1165                                 // Write properties
1166                                 writePropertiesJavaCallbackStub(intface, newIntface, callbackExist, callbackClasses);
1167                                 // Write constructor
1168                                 writeConstructorJavaCallbackStub(intface, newStubClass, callbackExist, callbackClasses);
1169                                 // Write methods
1170                                 // TODO: perhaps need to generate callback for callback
1171                                 writeMethodJavaStub(intMeth.getValue(), intDecl, callbackClasses);
1172                                 println("}");
1173                                 pw.close();
1174                                 System.out.println("IoTCompiler: Generated callback stub class " + newStubClass + ".java...");
1175                         }
1176                 }
1177         }
1178
1179
1180         /**
1181          * HELPER: writePropertiesJavaSkeleton() writes the properties of the skeleton class
1182          */
1183         private void writePropertiesJavaSkeleton(String intface, boolean callbackExist, InterfaceDecl intDecl) {
1184
1185                 println("private " + intface + " mainObj;");
1186                 //println("private int ports;");
1187                 println("private IoTRMIObject rmiObj;\n");
1188                 // Callback
1189                 if (callbackExist) {
1190                         println("private static int objIdCnt = 0;");
1191                         println("private IoTRMICall rmiCall;");
1192                 }
1193                 writePropertiesJavaPermission(intface, intDecl);
1194                 println("\n");
1195         }
1196
1197
1198         /**
1199          * HELPER: writeConstructorJavaSkeleton() writes the constructor of the skeleton class
1200          */
1201         private void writeConstructorJavaSkeleton(String newSkelClass, String intface) {
1202
1203                 println("public " + newSkelClass + "(" + intface + " _mainObj, int _port) throws Exception {");
1204                 println("mainObj = _mainObj;");
1205                 println("rmiObj = new IoTRMIObject(_port);");
1206                 // Generate permission control initialization
1207                 writeConstructorJavaPermission(intface);
1208                 println("___waitRequestInvokeMethod();");
1209                 println("}\n");
1210         }
1211
1212
1213         /**
1214          * HELPER: writeStdMethodBodyJavaSkeleton() writes the standard method body in the skeleton class
1215          */
1216         private void writeStdMethodBodyJavaSkeleton(List<String> methParams, String methodId, String methodType) {
1217
1218                 if (methodType.equals("void"))
1219                         print("mainObj." + methodId + "(");
1220                 else
1221                         print("return mainObj." + methodId + "(");
1222                 for (int i = 0; i < methParams.size(); i++) {
1223
1224                         print(getSimpleIdentifier(methParams.get(i)));
1225                         // Check if this is the last element (don't print a comma)
1226                         if (i != methParams.size() - 1) {
1227                                 print(", ");
1228                         }
1229                 }
1230                 println(");");
1231         }
1232
1233
1234         /**
1235          * HELPER: writeInitCallbackJavaSkeleton() writes the init callback method for skeleton class
1236          */
1237         private void writeInitCallbackJavaSkeleton(boolean callbackSkeleton) {
1238
1239                 // This is a callback skeleton generation
1240                 if (callbackSkeleton)
1241                         println("public void ___regCB(IoTRMIObject rmiObj) throws IOException {");
1242                 else
1243                         println("public void ___regCB() throws IOException {");
1244                 println("Object[] paramObj = rmiObj.getMethodParams(new Class<?>[] { int.class, String.class, int.class },");
1245                 println("\tnew Class<?>[] { null, null, null });");
1246                 println("rmiCall = new IoTRMICall((int) paramObj[0], (String) paramObj[1], (int) paramObj[2]);");
1247                 println("}\n");
1248         }
1249
1250
1251         /**
1252          * HELPER: writeMethodJavaSkeleton() writes the method of the skeleton class
1253          */
1254         private void writeMethodJavaSkeleton(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses, 
1255                         boolean callbackSkeleton) {
1256
1257                 for (String method : methods) {
1258
1259                         List<String> methParams = intDecl.getMethodParams(method);
1260                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1261                         String methodId = intDecl.getMethodId(method);
1262                         print("public " + intDecl.getMethodType(method) + " " + methodId + "(");
1263                         boolean isCallbackMethod = false;
1264                         String callbackType = null;
1265                         for (int i = 0; i < methParams.size(); i++) {
1266
1267                                 String origParamType = methPrmTypes.get(i);
1268                                 String paramType = checkAndGetParamClass(origParamType);
1269                                 if (callbackClasses.contains(origParamType)) { // Check if this has callback object
1270                                         isCallbackMethod = true;
1271                                         callbackType = origParamType;   
1272                                 }
1273                                 print(paramType + " " + methParams.get(i));
1274                                 // Check if this is the last element (don't print a comma)
1275                                 if (i != methParams.size() - 1) {
1276                                         print(", ");
1277                                 }
1278                         }
1279                         println(") {");
1280                         // Now, write the body of skeleton!
1281                         writeStdMethodBodyJavaSkeleton(methParams, methodId, intDecl.getMethodType(method));
1282                         println("}\n");
1283                         if (isCallbackMethod)
1284                                 writeInitCallbackJavaSkeleton(callbackSkeleton);
1285                 }
1286         }
1287
1288
1289         /**
1290          * HELPER: writeCallbackJavaStubGeneration() writes the callback stub generation part
1291          */
1292         private Map<Integer,String> writeCallbackJavaStubGeneration(List<String> methParams, List<String> methPrmTypes, String callbackType) {
1293
1294                 Map<Integer,String> mapStubParam = new HashMap<Integer,String>();
1295                 // Iterate over callback objects
1296                 for (int i = 0; i < methParams.size(); i++) {
1297                         String paramType = methPrmTypes.get(i);
1298                         String param = methParams.get(i);
1299                         //if (callbackType.equals(paramType)) {
1300                         if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
1301                                 println("try {");
1302                                 String exchParamType = checkAndGetParamClass(paramType);
1303                                 // Print array if this is array or list if this is a list of callback objects
1304                                 if (isArray(param)) {
1305                                         println("int numStubs" + i + " = (int) paramObj[" + i + "];");
1306                                         println(exchParamType + "[] stub" + i + " = new " + exchParamType + "[numStubs" + i + "];");
1307                                 } else if (isList(paramType)) {
1308                                         println("int numStubs" + i + " = (int) paramObj[" + i + "];");
1309                                         println("List<" + exchParamType + "> stub" + i + " = new ArrayList<" + exchParamType + ">();");
1310                                 } else {
1311                                         println(exchParamType + " stub" + i + " = new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt);");
1312                                         println("objIdCnt++;");
1313                                 }
1314                         }
1315                         // Generate a loop if needed
1316                         if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
1317                                 String exchParamType = checkAndGetParamClass(paramType);
1318                                 if (isArray(param)) {
1319                                         println("for (int objId = 0; objId < numStubs" + i + "; objId++) {");
1320                                         println("stub" + i + "[objId] = new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt);");
1321                                         println("objIdCnt++;");
1322                                         println("}");
1323                                 } else if (isList(paramType)) {
1324                                         println("for (int objId = 0; objId < numStubs" + i + "; objId++) {");
1325                                         println("stub" + i + ".add(new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt));");
1326                                         println("objIdCnt++;");
1327                                         println("}");
1328                                 }
1329                                 mapStubParam.put(i, "stub" + i);        // List of all stub parameters
1330                         }
1331                 }
1332                 return mapStubParam;
1333         }
1334
1335
1336         /**
1337          * HELPER: checkAndWriteEnumTypeJavaSkeleton() writes the enum type (convert from enum to int)
1338          */
1339         private void checkAndWriteEnumTypeJavaSkeleton(List<String> methParams, List<String> methPrmTypes) {
1340
1341                 // Iterate and find enum declarations
1342                 for (int i = 0; i < methParams.size(); i++) {
1343                         String paramType = methPrmTypes.get(i);
1344                         String param = methParams.get(i);
1345                         String simpleType = getSimpleType(paramType);
1346                         if (isEnumClass(simpleType)) {
1347                         // Check if this is enum type
1348                                 println("int paramInt" + i + "[] = (int[]) paramObj[" + i + "];");
1349                                 println(simpleType + "[] enumVals = " + simpleType + ".values();");
1350                                 if (isArray(param)) {   // An array
1351                                         println("int len" + i + " = paramInt" + i + ".length;");
1352                                         println(simpleType + "[] paramEnum = new " + simpleType + "[len];");
1353                                         println("for (int i = 0; i < len" + i + "; i++) {");
1354                                         println("paramEnum[i] = enumVals[paramInt" + i + "[i]];");
1355                                         println("}");
1356                                 } else if (isList(paramType)) { // A list
1357                                         println("int len" + i + " = paramInt" + i + ".length;");
1358                                         println("List<" + simpleType + "> paramEnum = new ArrayList<" + simpleType + ">();");
1359                                         println("for (int i = 0; i < len" + i + "; i++) {");
1360                                         println("paramEnum.add(enumVals[paramInt" + i + "[i]]);");
1361                                         println("}");
1362                                 } else {        // Just one element
1363                                         println(simpleType + " paramEnum" + i + " = enumVals[paramInt" + i + "[0]];");
1364                                 }
1365                         }
1366                 }
1367         }
1368
1369
1370         /**
1371          * HELPER: checkAndWriteEnumRetTypeJavaSkeleton() writes the enum return type (convert from enum to int)
1372          */
1373         private void checkAndWriteEnumRetTypeJavaSkeleton(String retType, String methodId) {
1374
1375                 // Strips off array "[]" for return type
1376                 String pureType = getSimpleArrayType(getSimpleType(retType));
1377                 // Take the inner type of generic
1378                 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
1379                         pureType = getTypeOfGeneric(retType)[0];
1380                 if (isEnumClass(pureType)) {
1381                 // Check if this is enum type
1382                         // Enum decoder
1383                         if (isArray(retType)) {                 // An array
1384                                 print(pureType + "[] retEnum = " + methodId + "(");
1385                         } else if (isList(retType)) {   // A list
1386                                 print("List<" + pureType + "> retEnum = " + methodId + "(");
1387                         } else {        // Just one element
1388                                 print(pureType + " retEnum = " + methodId + "(");
1389                         }
1390                 }
1391         }
1392
1393
1394         /**
1395          * HELPER: checkAndWriteEnumRetConvJavaSkeleton() writes the enum return type (convert from enum to int)
1396          */
1397         private void checkAndWriteEnumRetConvJavaSkeleton(String retType) {
1398
1399                 // Strips off array "[]" for return type
1400                 String pureType = getSimpleArrayType(getSimpleType(retType));
1401                 // Take the inner type of generic
1402                 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
1403                         pureType = getTypeOfGeneric(retType)[0];
1404                 if (isEnumClass(pureType)) {
1405                 // Check if this is enum type
1406                         if (isArray(retType)) { // An array
1407                                 println("int retLen = retEnum.length;");
1408                                 println("int[] retEnumVal = new int[retLen];");
1409                                 println("for (int i = 0; i < retLen; i++) {");
1410                                 println("retEnumVal[i] = retEnum[i].ordinal();");
1411                                 println("}");
1412                         } else if (isList(retType)) {   // A list
1413                                 println("int retLen = retEnum.size();");
1414                                 println("List<" + pureType + "> retEnumVal = new ArrayList<" + pureType + ">();");
1415                                 println("for (int i = 0; i < retLen; i++) {");
1416                                 println("retEnumVal.add(retEnum[i].ordinal());");
1417                                 println("}");
1418                         } else {        // Just one element
1419                                 println("int[] retEnumVal = new int[1];");
1420                                 println("retEnumVal[0] = retEnum.ordinal();");
1421                         }
1422                         println("Object retObj = retEnumVal;");
1423                 }
1424         }
1425         
1426         
1427         /**
1428          * HELPER: writeLengthStructParamClassJavaSkeleton() writes lengths of params
1429          */
1430         private void writeLengthStructParamClassJavaSkeleton(List<String> methParams, List<String> methPrmTypes, 
1431                         String method, InterfaceDecl intDecl) {
1432
1433                 // Iterate and find struct declarations - count number of params
1434                 for (int i = 0; i < methParams.size(); i++) {
1435                         String paramType = methPrmTypes.get(i);
1436                         String param = methParams.get(i);
1437                         String simpleType = getGenericType(paramType);
1438                         if (isStructClass(simpleType)) {
1439                                 int members = getNumOfMembers(simpleType);
1440                                 print(Integer.toString(members) + "*");
1441                                 int methodNumId = intDecl.getMethodNumId(method);
1442                                 print("struct" + methodNumId + "Size" + i);
1443                         } else
1444                                 print("1");
1445                         if (i != methParams.size() - 1) {
1446                                 print("+");
1447                         }
1448                 }
1449         }
1450
1451         
1452         /**
1453          * HELPER: writeStructMembersJavaSkeleton() writes parameters of struct
1454          */
1455         private void writeStructMembersJavaSkeleton(String simpleType, String paramType, 
1456                         String param, String method, InterfaceDecl intDecl, int iVar) {
1457
1458                 // Get the struct declaration for this struct and generate initialization code
1459                 StructDecl structDecl = getStructDecl(simpleType);
1460                 List<String> memTypes = structDecl.getMemberTypes(simpleType);
1461                 List<String> members = structDecl.getMembers(simpleType);
1462                 if (isArrayOrList(param, paramType)) {  // An array or list
1463                         int methodNumId = intDecl.getMethodNumId(method);
1464                         String counter = "struct" + methodNumId + "Size" + iVar;
1465                         println("for(int i = 0; i < " + counter + "; i++) {");
1466                 }
1467                 println("int pos = 0;");
1468                 if (isArrayOrList(param, paramType)) {  // An array or list
1469                         println("for(int i = 0; i < retLen; i++) {");
1470                         for (int i = 0; i < members.size(); i++) {
1471                                 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
1472                                 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
1473                                 println("paramClsGen[pos++] = null;");
1474                         }
1475                         println("}");
1476                 } else {        // Just one struct element
1477                         for (int i = 0; i < members.size(); i++) {
1478                                 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
1479                                 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
1480                                 println("paramClsGen[pos++] = null;");
1481                         }
1482                 }
1483         }
1484
1485
1486
1487         /**
1488          * HELPER: writeStructMembersInitJavaSkeleton() writes parameters of struct
1489          */
1490         private void writeStructMembersInitJavaSkeleton(InterfaceDecl intDecl, List<String> methParams,
1491                         List<String> methPrmTypes, String method) {
1492
1493                 for (int i = 0; i < methParams.size(); i++) {
1494                         String paramType = methPrmTypes.get(i);
1495                         String param = methParams.get(i);
1496                         String simpleType = getGenericType(paramType);
1497                         if (isStructClass(simpleType)) {
1498                                 int methodNumId = intDecl.getMethodNumId(method);
1499                                 String counter = "struct" + methodNumId + "Size" + i;
1500                                 // Declaration
1501                                 if (isArray(param)) {                   // An array
1502                                         println(simpleType + "[] paramStruct" + i + " = new " + simpleType + "[" + counter + "];");
1503                                         println("for(int i = 0; i < " + counter + "; i++) {");
1504                                         println("paramStruct" + i + "[i] = new " + simpleType + "();");
1505                                         println("}");
1506                                 } else if (isList(paramType)) { // A list
1507                                         println("List<" + simpleType + "> structRet = new ArrayList<" + simpleType + ">();");
1508                                 } else
1509                                         println(simpleType + " paramStruct" + i + " = new " + simpleType + "();");
1510                                 println("int objPos = 0;");
1511                                 // Initialize members
1512                                 StructDecl structDecl = getStructDecl(simpleType);
1513                                 List<String> members = structDecl.getMembers(simpleType);
1514                                 List<String> memTypes = structDecl.getMemberTypes(simpleType);
1515                                 if (isArrayOrList(param, paramType)) {  // An array or list
1516                                         println("for(int i = 0; i < " + counter + "; i++) {");
1517                                 }
1518                                 if (isArray(param)) {   // An array
1519                                         for (int j = 0; j < members.size(); j++) {
1520                                                 String prmType = checkAndGetArray(memTypes.get(j), members.get(j));
1521                                                 print("paramStruct" + i + "[i]." + getSimpleIdentifier(members.get(j)));
1522                                                 println(" = (" + getSimpleType(getEnumType(prmType)) + ") paramObj[objPos++];");
1523                                         }
1524                                         println("}");
1525                                 } else if (isList(paramType)) { // A list
1526                                         println(simpleType + " paramStructMem = new " + simpleType + "();");
1527                                         for (int j = 0; j < members.size(); j++) {
1528                                                 String prmType = checkAndGetArray(memTypes.get(j), members.get(j));
1529                                                 print("paramStructMem." + getSimpleIdentifier(members.get(j)));
1530                                                 println(" = (" + getSimpleType(getEnumType(prmType)) + ") paramObj[objPos++];");
1531                                         }
1532                                         println("paramStruct" + i + ".add(paramStructMem);");
1533                                         println("}");
1534                                 } else {        // Just one struct element
1535                                         for (int j = 0; j < members.size(); j++) {
1536                                                 String prmType = checkAndGetArray(memTypes.get(j), members.get(j));
1537                                                 print("paramStruct" + i + "." + getSimpleIdentifier(members.get(j)));
1538                                                 println(" = (" + getSimpleType(getEnumType(prmType)) + ") paramObj[objPos++];");
1539                                         }
1540                                 }
1541                         } else {
1542                                 // Take offsets of parameters
1543                                 println("int offset" + i +" = objPos;");
1544                         }
1545                 }
1546         }
1547
1548
1549         /**
1550          * HELPER: writeStructReturnJavaSkeleton() writes parameters if struct is present
1551          */
1552         private void writeStructReturnJavaSkeleton(String simpleType, String retType) {
1553
1554                 // Minimum retLen is 1 if this is a single struct object
1555                 if (isArray(retType))
1556                         println("int retLen = retStruct.length;");
1557                 else if (isList(retType))
1558                         println("int retLen = retStruct.size();");
1559                 else    // Just single struct object
1560                         println("int retLen = 1;");
1561                 println("Object retLenObj = retLen;");
1562                 println("rmiObj.sendReturnObj(retLenObj);");
1563                 int numMem = getNumOfMembers(simpleType);
1564                 println("Class<?>[] retCls = new Class<?>[" + numMem + "*retLen];");
1565                 println("Object[] retObj = new Object[" + numMem + "*retLen];");
1566                 println("int retPos = 0;");
1567                 // Get the struct declaration for this struct and generate initialization code
1568                 StructDecl structDecl = getStructDecl(simpleType);
1569                 List<String> memTypes = structDecl.getMemberTypes(simpleType);
1570                 List<String> members = structDecl.getMembers(simpleType);
1571                 if (isArrayOrList(retType, retType)) {  // An array or list
1572                         println("for(int i = 0; i < retLen; i++) {");
1573                         for (int i = 0; i < members.size(); i++) {
1574                                 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
1575                                 println("retCls[retPos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
1576                                 print("retObj[retPos++] = retStruct[i].");
1577                                 print(getEnumParam(memTypes.get(i), getSimpleIdentifier(members.get(i)), i));
1578                                 println(";");
1579                         }
1580                         println("}");
1581                 } else {        // Just one struct element
1582                         for (int i = 0; i < members.size(); i++) {
1583                                 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
1584                                 println("retCls[retPos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
1585                                 print("retObj[retPos++] = retStruct.");
1586                                 print(getEnumParam(memTypes.get(i), getSimpleIdentifier(members.get(i)), i));
1587                                 println(";");
1588                         }
1589                 }
1590
1591         }
1592
1593
1594         /**
1595          * HELPER: writeMethodHelperStructJavaSkeleton() writes the struct in skeleton
1596          */
1597         private void writeMethodHelperStructJavaSkeleton(InterfaceDecl intDecl, List<String> methParams,
1598                         List<String> methPrmTypes, String method, Set<String> callbackClasses) {
1599
1600                 // Generate array of parameter objects
1601                 boolean isCallbackMethod = false;
1602                 String callbackType = null;
1603                 print("int paramLen = ");
1604                 writeLengthStructParamClassJavaSkeleton(methParams, methPrmTypes, method, intDecl);
1605                 println(";");
1606                 println("Class<?>[] paramCls = new Class<?>[paramLen];");
1607                 println("Class<?>[] paramClsGen = new Class<?>[paramLen];");
1608                 // Iterate again over the parameters
1609                 for (int i = 0; i < methParams.size(); i++) {
1610                         String paramType = methPrmTypes.get(i);
1611                         String param = methParams.get(i);
1612                         String simpleType = getGenericType(paramType);
1613                         if (isStructClass(simpleType)) {
1614                                 writeStructMembersJavaSkeleton(simpleType, paramType, param, method, intDecl, i);
1615                         } else {
1616                                 String prmType = returnGenericCallbackType(methPrmTypes.get(i));
1617                                 if (callbackClasses.contains(prmType)) {
1618                                         isCallbackMethod = true;
1619                                         callbackType = prmType;
1620                                         print("int.class");
1621                                 } else {        // Generate normal classes if it's not a callback object
1622                                         String paramTypeOth = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
1623                                         println("paramCls[pos] = " + getSimpleType(getEnumType(paramTypeOth)) + ".class;");
1624                                         print("paramClsGen[pos++] = ");
1625                                         String prmTypeOth = methPrmTypes.get(i);
1626                                         if (getParamCategory(prmTypeOth) == ParamCategory.NONPRIMITIVES)
1627                                                 println(getTypeOfGeneric(prmType)[0] + ".class;");
1628                                         else
1629                                                 println("null;");
1630                                 }
1631                         }
1632                 }
1633                 println("Object[] paramObj = rmiObj.getMethodParams(paramCls, paramClsGen);");
1634                 writeStructMembersInitJavaSkeleton(intDecl, methParams, methPrmTypes, method);
1635                 checkAndWriteEnumTypeJavaSkeleton(methParams, methPrmTypes);
1636                 Map<Integer,String> mapStubParam = null;
1637                 if (isCallbackMethod)
1638                         mapStubParam = writeCallbackJavaStubGeneration(methParams, methPrmTypes, callbackType);
1639                 // Check if this is "void"
1640                 String retType = intDecl.getMethodType(method);
1641                 if (retType.equals("void")) {
1642                         print(intDecl.getMethodId(method) + "(");
1643                 } else if (isEnumClass(getSimpleArrayType(getSimpleType(retType)))) {   // Enum type
1644                         checkAndWriteEnumRetTypeJavaSkeleton(retType, intDecl.getMethodId(method));
1645                 } else if (isStructClass(getSimpleArrayType(getSimpleType(retType)))) { // Struct type
1646                         print(retType + " retStruct = " + intDecl.getMethodId(method) + "(");
1647                 } else { // We do have a return value
1648                         print("Object retObj = " + intDecl.getMethodId(method) + "(");
1649                 }
1650                 for (int i = 0; i < methParams.size(); i++) {
1651
1652                         if (isCallbackMethod) {
1653                                 print(mapStubParam.get(i));     // Get the callback parameter
1654                         } else if (isEnumClass(getSimpleType(methPrmTypes.get(i)))) { // Enum class
1655                                 print(getEnumParam(methPrmTypes.get(i), methParams.get(i), i));
1656                         } else if (isStructClass(getSimpleType(methPrmTypes.get(i)))) {
1657                                 print("paramStruct" + i);
1658                         } else {
1659                                 String prmType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
1660                                 print("(" + prmType + ") paramObj[offset" + i + "]");
1661                         }
1662                         if (i != methParams.size() - 1)
1663                                 print(", ");
1664                 }
1665                 println(");");
1666                 if (!retType.equals("void")) {
1667                         if (isEnumClass(getSimpleArrayType(getSimpleType(retType)))) { // Enum type
1668                                 checkAndWriteEnumRetConvJavaSkeleton(retType);
1669                                 println("rmiObj.sendReturnObj(retObj);");
1670                         } else if (isStructClass(getSimpleArrayType(getSimpleType(retType)))) { // Struct type
1671                                 writeStructReturnJavaSkeleton(getSimpleArrayType(getSimpleType(retType)), retType);
1672                                 println("rmiObj.sendReturnObj(retCls, retObj);");
1673                         } else
1674                                 println("rmiObj.sendReturnObj(retObj);");
1675                 }
1676                 if (isCallbackMethod) { // Catch exception if this is callback
1677                         println("} catch(Exception ex) {");
1678                         println("ex.printStackTrace();");
1679                         println("throw new Error(\"Exception from callback object instantiation!\");");
1680                         println("}");
1681                 }               
1682         }
1683
1684
1685         /**
1686          * HELPER: writeStdMethodHelperBodyJavaSkeleton() writes the standard method body helper in the skeleton class
1687          */
1688         private void writeStdMethodHelperBodyJavaSkeleton(InterfaceDecl intDecl, List<String> methParams,
1689                         List<String> methPrmTypes, String method, Set<String> callbackClasses) {
1690
1691                 // Generate array of parameter objects
1692                 boolean isCallbackMethod = false;
1693                 String callbackType = null;
1694                 print("Object[] paramObj = rmiObj.getMethodParams(new Class<?>[] { ");
1695                 for (int i = 0; i < methParams.size(); i++) {
1696
1697                         String paramType = returnGenericCallbackType(methPrmTypes.get(i));
1698                         if (callbackClasses.contains(paramType)) {
1699                                 isCallbackMethod = true;
1700                                 callbackType = paramType;
1701                                 print("int.class");
1702                         } else {        // Generate normal classes if it's not a callback object
1703                                 String prmType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
1704                                 print(getSimpleType(getEnumType(prmType)) + ".class");
1705                         }
1706                         if (i != methParams.size() - 1)
1707                                 print(", ");
1708                 }
1709                 println(" }, ");
1710                 // Generate generic class if it's a generic type.. null otherwise
1711                 print("new Class<?>[] { ");
1712                 for (int i = 0; i < methParams.size(); i++) {
1713                         String prmType = methPrmTypes.get(i);
1714                         if (getParamCategory(prmType) == ParamCategory.NONPRIMITIVES)
1715                                 print(getTypeOfGeneric(prmType)[0] + ".class");
1716                         else
1717                                 print("null");
1718                         if (i != methParams.size() - 1)
1719                                 print(", ");
1720                 }
1721                 println(" });");
1722                 checkAndWriteEnumTypeJavaSkeleton(methParams, methPrmTypes);
1723                 Map<Integer,String> mapStubParam = null;
1724                 if (isCallbackMethod)
1725                         mapStubParam = writeCallbackJavaStubGeneration(methParams, methPrmTypes, callbackType);
1726                 // Check if this is "void"
1727                 String retType = intDecl.getMethodType(method);
1728                 if (retType.equals("void")) {
1729                         print(intDecl.getMethodId(method) + "(");
1730                 } else if (isEnumClass(getSimpleArrayType(getSimpleType(retType)))) {   // Enum type
1731                         checkAndWriteEnumRetTypeJavaSkeleton(retType, intDecl.getMethodId(method));
1732                 } else if (isStructClass(getSimpleArrayType(getSimpleType(retType)))) { // Struct type
1733                         print(retType + " retStruct = " + intDecl.getMethodId(method) + "(");
1734                 } else { // We do have a return value
1735                         print("Object retObj = " + intDecl.getMethodId(method) + "(");
1736                 }
1737                 for (int i = 0; i < methParams.size(); i++) {
1738
1739                         if (isCallbackMethod) {
1740                                 print(mapStubParam.get(i));     // Get the callback parameter
1741                         } else if (isEnumClass(getSimpleType(methPrmTypes.get(i)))) { // Enum class
1742                                 print(getEnumParam(methPrmTypes.get(i), methParams.get(i), i));
1743                         } else {
1744                                 String prmType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
1745                                 print("(" + prmType + ") paramObj[" + i + "]");
1746                         }
1747                         if (i != methParams.size() - 1)
1748                                 print(", ");
1749                 }
1750                 println(");");
1751                 if (!retType.equals("void")) {
1752                         if (isEnumClass(getSimpleArrayType(getSimpleType(retType)))) { // Enum type
1753                                 checkAndWriteEnumRetConvJavaSkeleton(retType);
1754                                 println("rmiObj.sendReturnObj(retObj);");
1755                         } else if (isStructClass(getSimpleArrayType(getSimpleType(retType)))) { // Struct type
1756                                 writeStructReturnJavaSkeleton(getSimpleArrayType(getSimpleType(retType)), retType);
1757                                 println("rmiObj.sendReturnObj(retCls, retObj);");
1758                         } else
1759                                 println("rmiObj.sendReturnObj(retObj);");
1760                 }
1761                 if (isCallbackMethod) { // Catch exception if this is callback
1762                         println("} catch(Exception ex) {");
1763                         println("ex.printStackTrace();");
1764                         println("throw new Error(\"Exception from callback object instantiation!\");");
1765                         println("}");
1766                 }
1767         }
1768
1769
1770         /**
1771          * HELPER: writeMethodHelperJavaSkeleton() writes the method helper of the skeleton class
1772          */
1773         private void writeMethodHelperJavaSkeleton(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
1774
1775                 // Use this set to handle two same methodIds
1776                 Set<String> uniqueMethodIds = new HashSet<String>();
1777                 for (String method : methods) {
1778
1779                         List<String> methParams = intDecl.getMethodParams(method);
1780                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1781                         if (isStructPresent(methParams, methPrmTypes)) {        // Treat struct differently
1782                                 String methodId = intDecl.getMethodId(method);
1783                                 print("public void ___");
1784                                 String helperMethod = methodId;
1785                                 if (uniqueMethodIds.contains(methodId))
1786                                         helperMethod = helperMethod + intDecl.getMethodNumId(method);
1787                                 else
1788                                         uniqueMethodIds.add(methodId);
1789                                 String retType = intDecl.getMethodType(method);
1790                                 print(helperMethod + "(");
1791                                 boolean begin = true;
1792                                 for (int i = 0; i < methParams.size(); i++) { // Print size variables
1793                                         String paramType = methPrmTypes.get(i);
1794                                         String param = methParams.get(i);
1795                                         String simpleType = getSimpleType(paramType);
1796                                         if (isStructClass(simpleType)) {
1797                                                 if (!begin) {   // Generate comma for not the beginning variable
1798                                                         print(", "); begin = false;
1799                                                 }
1800                                                 int methodNumId = intDecl.getMethodNumId(method);
1801                                                 print("int struct" + methodNumId + "Size" + i);
1802                                         }
1803                                         // TODO: Need to create comma separation
1804                                 }
1805                                 // Check if this is "void"
1806                                 if (retType.equals("void"))
1807                                         println(") {");
1808                                 else
1809                                         println(") throws IOException {");
1810                                 writeMethodHelperStructJavaSkeleton(intDecl, methParams, methPrmTypes, method, callbackClasses);
1811                                 println("}\n");
1812                         } else {
1813                                 String methodId = intDecl.getMethodId(method);
1814                                 print("public void ___");
1815                                 String helperMethod = methodId;
1816                                 if (uniqueMethodIds.contains(methodId))
1817                                         helperMethod = helperMethod + intDecl.getMethodNumId(method);
1818                                 else
1819                                         uniqueMethodIds.add(methodId);
1820                                 // Check if this is "void"
1821                                 String retType = intDecl.getMethodType(method);
1822                                 if (retType.equals("void"))
1823                                         println(helperMethod + "() {");
1824                                 else
1825                                         println(helperMethod + "() throws IOException {");
1826                                 // Now, write the helper body of skeleton!
1827                                 writeStdMethodHelperBodyJavaSkeleton(intDecl, methParams, methPrmTypes, method, callbackClasses);
1828                                 println("}\n");
1829                         }
1830                 }
1831                 // Write method helper for structs
1832                 writeMethodHelperStructSetupJavaSkeleton(methods, intDecl);
1833         }
1834
1835
1836         /**
1837          * HELPER: writeMethodHelperStructSetupJavaSkeleton() writes the method helper of the struct in skeleton class
1838          */
1839         private void writeMethodHelperStructSetupJavaSkeleton(Collection<String> methods, 
1840                         InterfaceDecl intDecl) {
1841
1842                 // Use this set to handle two same methodIds
1843                 for (String method : methods) {
1844
1845                         List<String> methParams = intDecl.getMethodParams(method);
1846                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1847                         // Check for params with structs
1848                         for (int i = 0; i < methParams.size(); i++) {
1849                                 String paramType = methPrmTypes.get(i);
1850                                 String param = methParams.get(i);
1851                                 String simpleType = getSimpleType(paramType);
1852                                 if (isStructClass(simpleType)) {
1853                                         int methodNumId = intDecl.getMethodNumId(method);
1854                                         print("public int ___");
1855                                         String helperMethod = methodNumId + "struct" + i;
1856                                         println(helperMethod + "() {");
1857                                         // Now, write the helper body of skeleton!
1858                                         println("Object[] paramObj = rmiObj.getMethodParams(new Class<?>[] { int.class }, new Class<?>[] { null });");
1859                                         println("return (int) paramObj[0];");
1860                                         println("}\n");
1861                                 }
1862                         }
1863                 }
1864         }
1865
1866
1867         /**
1868          * HELPER: writeCountVarStructJavaSkeleton() writes counter variable of struct for skeleton
1869          */
1870         private void writeCountVarStructJavaSkeleton(Collection<String> methods, InterfaceDecl intDecl) {
1871
1872                 // Use this set to handle two same methodIds
1873                 for (String method : methods) {
1874
1875                         List<String> methParams = intDecl.getMethodParams(method);
1876                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1877                         // Check for params with structs
1878                         for (int i = 0; i < methParams.size(); i++) {
1879                                 String paramType = methPrmTypes.get(i);
1880                                 String param = methParams.get(i);
1881                                 String simpleType = getSimpleType(paramType);
1882                                 if (isStructClass(simpleType)) {
1883                                         int methodNumId = intDecl.getMethodNumId(method);
1884                                         println("int struct" + methodNumId + "Size" + i + " = 0;");
1885                                 }
1886                         }
1887                 }
1888         }
1889         
1890         
1891         /**
1892          * HELPER: writeInputCountVarStructJavaSkeleton() writes counter variable of struct for skeleton
1893          */
1894         private void writeInputCountVarStructJavaSkeleton(String method, InterfaceDecl intDecl) {
1895
1896                 List<String> methParams = intDecl.getMethodParams(method);
1897                 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1898                 // Check for params with structs
1899                 for (int i = 0; i < methParams.size(); i++) {
1900                         String paramType = methPrmTypes.get(i);
1901                         String param = methParams.get(i);
1902                         String simpleType = getSimpleType(paramType);
1903                         boolean begin = true;
1904                         if (isStructClass(simpleType)) {
1905                                 if (!begin) {
1906                                         print(", "); begin = false;
1907                                 }
1908                                 int methodNumId = intDecl.getMethodNumId(method);
1909                                 print("struct" + methodNumId + "Size" + i);
1910                         }
1911                 }
1912         }
1913
1914
1915         /**
1916          * HELPER: writeMethodCallStructJavaSkeleton() writes method call for wait invoke in skeleton
1917          */
1918         private void writeMethodCallStructJavaSkeleton(Collection<String> methods, InterfaceDecl intDecl) {
1919
1920                 // Use this set to handle two same methodIds
1921                 for (String method : methods) {
1922
1923                         List<String> methParams = intDecl.getMethodParams(method);
1924                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1925                         // Check for params with structs
1926                         for (int i = 0; i < methParams.size(); i++) {
1927                                 String paramType = methPrmTypes.get(i);
1928                                 String param = methParams.get(i);
1929                                 String simpleType = getSimpleType(paramType);
1930                                 if (isStructClass(simpleType)) {
1931                                         int methodNumId = intDecl.getMethodNumId(method);
1932                                         print("case ");
1933                                         String helperMethod = methodNumId + "struct" + i;
1934                                         String tempVar = "struct" + methodNumId + "Size" + i;
1935                                         print(intDecl.getHelperMethodNumId(helperMethod) + ": ");
1936                                         print(tempVar + " = ___");
1937                                         println(helperMethod + "(); break;");
1938                                 }
1939                         }
1940                 }
1941         }
1942
1943
1944         /**
1945          * HELPER: writeJavaMethodPermission() writes permission checks in skeleton
1946          */
1947         private void writeJavaMethodPermission(String intface) {
1948
1949                 // Get all the different stubs
1950                 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
1951                 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
1952                         String newIntface = intMeth.getKey();
1953                         int newObjectId = mapNewIntfaceObjId.get(newIntface);
1954                         println("if (_objectId == object" + newObjectId + "Id) {");
1955                         println("if (!set" + newObjectId + "Allowed.contains(methodId)) {");
1956                         println("throw new Error(\"Object with object Id: \" + _objectId + \"  is not allowed to access method: \" + methodId);");
1957                         println("}");
1958                         println("else {");
1959                         println("throw new Error(\"Object Id: \" + _objectId + \" not recognized!\");");
1960                         println("}");
1961                         println("}");
1962                 }
1963         }
1964
1965
1966         /**
1967          * HELPER: writeJavaWaitRequestInvokeMethod() writes the main loop of the skeleton class
1968          */
1969         private void writeJavaWaitRequestInvokeMethod(Collection<String> methods, InterfaceDecl intDecl, boolean callbackExist, String intface) {
1970
1971                 // Use this set to handle two same methodIds
1972                 Set<String> uniqueMethodIds = new HashSet<String>();
1973                 println("private void ___waitRequestInvokeMethod() throws IOException {");
1974                 // Write variables here if we have callbacks or enums or structs
1975                 writeCountVarStructJavaSkeleton(methods, intDecl);
1976                 println("while (true) {");
1977                 println("rmiObj.getMethodBytes();");
1978                 println("int _objectId = rmiObj.getObjectId();");
1979                 println("int methodId = rmiObj.getMethodId();");
1980                 // Generate permission check
1981                 writeJavaMethodPermission(intface);
1982                 println("switch (methodId) {");
1983                 // Print methods and method Ids
1984                 for (String method : methods) {
1985                         String methodId = intDecl.getMethodId(method);
1986                         int methodNumId = intDecl.getMethodNumId(method);
1987                         print("case " + methodNumId + ": ___");
1988                         String helperMethod = methodId;
1989                         if (uniqueMethodIds.contains(methodId))
1990                                 helperMethod = helperMethod + methodNumId;
1991                         else
1992                                 uniqueMethodIds.add(methodId);
1993                         print(helperMethod + "(");
1994                         writeInputCountVarStructJavaSkeleton(method, intDecl);
1995                         println("); break;");
1996                 }
1997                 String method = "___initCallBack()";
1998                 // Print case -9999 (callback handler) if callback exists
1999                 if (callbackExist) {
2000                         int methodId = intDecl.getHelperMethodNumId(method);
2001                         println("case " + methodId + ": ___regCB(); break;");
2002                 }
2003                 writeMethodCallStructJavaSkeleton(methods, intDecl);
2004                 println("default: ");
2005                 println("throw new Error(\"Method Id \" + methodId + \" not recognized!\");");
2006                 println("}");
2007                 println("}");
2008                 println("}\n");
2009         }
2010
2011
2012         /**
2013          * generateJavaSkeletonClass() generate skeletons based on the methods list in Java
2014          */
2015         public void generateJavaSkeletonClass() throws IOException {
2016
2017                 // Create a new directory
2018                 String path = createDirectories(dir, subdir);
2019                 for (String intface : mapIntfacePTH.keySet()) {
2020                         // Open a new file to write into
2021                         String newSkelClass = intface + "_Skeleton";
2022                         FileWriter fw = new FileWriter(path + "/" + newSkelClass + ".java");
2023                         pw = new PrintWriter(new BufferedWriter(fw));
2024                         // Pass in set of methods and get import classes
2025                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2026                         InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
2027                         List<String> methods = intDecl.getMethods();
2028                         Set<String> importClasses = getImportClasses(methods, intDecl);
2029                         List<String> stdImportClasses = getStandardJavaImportClasses();
2030                         List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
2031                         printImportStatements(allImportClasses);
2032                         // Find out if there are callback objects
2033                         Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
2034                         boolean callbackExist = !callbackClasses.isEmpty();
2035                         // Write class header
2036                         println("");
2037                         println("public class " + newSkelClass  + " implements " + intface + " {\n");
2038                         // Write properties
2039                         writePropertiesJavaSkeleton(intface, callbackExist, intDecl);
2040                         // Write constructor
2041                         writeConstructorJavaSkeleton(newSkelClass, intface);
2042                         // Write methods
2043                         writeMethodJavaSkeleton(methods, intDecl, callbackClasses, false);
2044                         // Write method helper
2045                         writeMethodHelperJavaSkeleton(methods, intDecl, callbackClasses);
2046                         // Write waitRequestInvokeMethod() - main loop
2047                         writeJavaWaitRequestInvokeMethod(methods, intDecl, callbackExist, intface);
2048                         println("}");
2049                         pw.close();
2050                         System.out.println("IoTCompiler: Generated skeleton class " + newSkelClass + ".java...");
2051                 }
2052         }
2053
2054
2055         /**
2056          * HELPER: writePropertiesJavaCallbackSkeleton() writes the properties of the callback skeleton class
2057          */
2058         private void writePropertiesJavaCallbackSkeleton(String intface, boolean callbackExist) {
2059
2060                 println("private " + intface + " mainObj;");
2061                 // For callback skeletons, this is its own object Id
2062                 println("private static int objectId = 0;");
2063                 // Callback
2064                 if (callbackExist) {
2065                         println("private static int objIdCnt = 0;");
2066                         println("private IoTRMICall rmiCall;");
2067                 }
2068                 println("\n");
2069         }
2070
2071
2072         /**
2073          * HELPER: writeConstructorJavaCallbackSkeleton() writes the constructor of the skeleton class
2074          */
2075         private void writeConstructorJavaCallbackSkeleton(String newSkelClass, String intface) {
2076
2077                 println("public " + newSkelClass + "(" + intface + " _mainObj, int _objectId) throws Exception {");
2078                 println("mainObj = _mainObj;");
2079                 println("objectId = _objectId;");
2080                 println("}\n");
2081         }
2082
2083
2084         /**
2085          * HELPER: writeMethodHelperJavaCallbackSkeleton() writes the method helper of the callback skeleton class
2086          */
2087         private void writeMethodHelperJavaCallbackSkeleton(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
2088
2089                 // Use this set to handle two same methodIds
2090                 Set<String> uniqueMethodIds = new HashSet<String>();
2091                 for (String method : methods) {
2092
2093                         List<String> methParams = intDecl.getMethodParams(method);
2094                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2095                         String methodId = intDecl.getMethodId(method);
2096                         print("public void ___");
2097                         String helperMethod = methodId;
2098                         if (uniqueMethodIds.contains(methodId))
2099                                 helperMethod = helperMethod + intDecl.getMethodNumId(method);
2100                         else
2101                                 uniqueMethodIds.add(methodId);
2102                         // Check if this is "void"
2103                         String retType = intDecl.getMethodType(method);
2104                         if (retType.equals("void"))
2105                                 println(helperMethod + "(IoTRMIObject rmiObj) {");
2106                         else
2107                                 println(helperMethod + "(IoTRMIObject rmiObj) throws IOException {");
2108                         // Now, write the helper body of skeleton!
2109                         writeStdMethodHelperBodyJavaSkeleton(intDecl, methParams, methPrmTypes, method, callbackClasses);
2110                         println("}\n");
2111                 }
2112         }
2113
2114
2115         /**
2116          * HELPER: writeJavaCallbackWaitRequestInvokeMethod() writes the main loop of the skeleton class
2117          */
2118         private void writeJavaCallbackWaitRequestInvokeMethod(Collection<String> methods, InterfaceDecl intDecl, boolean callbackExist) {
2119
2120                 // Use this set to handle two same methodIds
2121                 Set<String> uniqueMethodIds = new HashSet<String>();
2122                 println("public void invokeMethod(IoTRMIObject rmiObj) throws IOException {");
2123                 // Write variables here if we have callbacks or enums or structs
2124                 println("int methodId = rmiObj.getMethodId();");
2125                 // TODO: code the permission check here!
2126                 println("switch (methodId) {");
2127                 // Print methods and method Ids
2128                 for (String method : methods) {
2129                         String methodId = intDecl.getMethodId(method);
2130                         int methodNumId = intDecl.getMethodNumId(method);
2131                         print("case " + methodNumId + ": ___");
2132                         String helperMethod = methodId;
2133                         if (uniqueMethodIds.contains(methodId))
2134                                 helperMethod = helperMethod + methodNumId;
2135                         else
2136                                 uniqueMethodIds.add(methodId);
2137                         println(helperMethod + "(rmiObj); break;");
2138                 }
2139                 String method = "___initCallBack()";
2140                 // Print case -9999 (callback handler) if callback exists
2141                 if (callbackExist) {
2142                         int methodId = intDecl.getHelperMethodNumId(method);
2143                         println("case " + methodId + ": ___regCB(rmiObj); break;");
2144                 }
2145                 println("default: ");
2146                 println("throw new Error(\"Method Id \" + methodId + \" not recognized!\");");
2147                 println("}");
2148                 println("}\n");
2149         }
2150
2151
2152         /**
2153          * generateJavaCallbackSkeletonClass() generate callback skeletons based on the methods list in Java
2154          */
2155         public void generateJavaCallbackSkeletonClass() throws IOException {
2156
2157                 // Create a new directory
2158                 String path = createDirectories(dir, subdir);
2159                 for (String intface : mapIntfacePTH.keySet()) {
2160                         // Open a new file to write into
2161                         String newSkelClass = intface + "_CallbackSkeleton";
2162                         FileWriter fw = new FileWriter(path + "/" + newSkelClass + ".java");
2163                         pw = new PrintWriter(new BufferedWriter(fw));
2164                         // Pass in set of methods and get import classes
2165                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2166                         InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
2167                         List<String> methods = intDecl.getMethods();
2168                         Set<String> importClasses = getImportClasses(methods, intDecl);
2169                         List<String> stdImportClasses = getStandardJavaImportClasses();
2170                         List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
2171                         printImportStatements(allImportClasses);
2172                         // Find out if there are callback objects
2173                         Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
2174                         boolean callbackExist = !callbackClasses.isEmpty();
2175                         // Write class header
2176                         println("");
2177                         println("public class " + newSkelClass  + " implements " + intface + " {\n");
2178                         // Write properties
2179                         writePropertiesJavaCallbackSkeleton(intface, callbackExist);
2180                         // Write constructor
2181                         writeConstructorJavaCallbackSkeleton(newSkelClass, intface);
2182                         // Write methods
2183                         writeMethodJavaSkeleton(methods, intDecl, callbackClasses, true);
2184                         // Write method helper
2185                         writeMethodHelperJavaCallbackSkeleton(methods, intDecl, callbackClasses);
2186                         // Write waitRequestInvokeMethod() - main loop
2187                         writeJavaCallbackWaitRequestInvokeMethod(methods, intDecl, callbackExist);
2188                         println("}");
2189                         pw.close();
2190                         System.out.println("IoTCompiler: Generated callback skeleton class " + newSkelClass + ".java...");
2191                 }
2192         }
2193
2194
2195         /**
2196          * HELPER: writeMethodCplusLocalInterface() writes the method of the interface
2197          */
2198         private void writeMethodCplusLocalInterface(Collection<String> methods, InterfaceDecl intDecl) {
2199
2200                 for (String method : methods) {
2201
2202                         List<String> methParams = intDecl.getMethodParams(method);
2203                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2204                         print("virtual " + checkAndGetCplusType(intDecl.getMethodType(method)) + " " +
2205                                 intDecl.getMethodId(method) + "(");
2206                         for (int i = 0; i < methParams.size(); i++) {
2207                                 // Check for params with driver class types and exchange it 
2208                                 //              with its remote interface
2209                                 String paramType = checkAndGetParamClass(methPrmTypes.get(i));
2210                                 paramType = checkAndGetCplusType(paramType);
2211                                 // Check for arrays - translate into vector in C++
2212                                 String paramComplete = checkAndGetCplusArray(paramType, methParams.get(i));
2213                                 print(paramComplete);
2214                                 // Check if this is the last element (don't print a comma)
2215                                 if (i != methParams.size() - 1) {
2216                                         print(", ");
2217                                 }
2218                         }
2219                         println(") = 0;");
2220                 }
2221         }
2222
2223
2224         /**
2225          * HELPER: writeMethodCplusInterface() writes the method of the interface
2226          */
2227         private void writeMethodCplusInterface(Collection<String> methods, InterfaceDecl intDecl) {
2228
2229                 for (String method : methods) {
2230
2231                         List<String> methParams = intDecl.getMethodParams(method);
2232                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2233                         print("virtual " + checkAndGetCplusType(intDecl.getMethodType(method)) + " " +
2234                                 intDecl.getMethodId(method) + "(");
2235                         for (int i = 0; i < methParams.size(); i++) {
2236                                 // Check for params with driver class types and exchange it 
2237                                 //              with its remote interface
2238                                 String paramType = methPrmTypes.get(i);
2239                                 paramType = checkAndGetCplusType(paramType);
2240                                 // Check for arrays - translate into vector in C++
2241                                 String paramComplete = checkAndGetCplusArray(paramType, methParams.get(i));
2242                                 print(paramComplete);
2243                                 // Check if this is the last element (don't print a comma)
2244                                 if (i != methParams.size() - 1) {
2245                                         print(", ");
2246                                 }
2247                         }
2248                         println(") = 0;");
2249                 }
2250         }
2251
2252
2253         /**
2254          * HELPER: generateEnumCplus() writes the enumeration declaration
2255          */
2256         public void generateEnumCplus() throws IOException {
2257
2258                 // Create a new directory
2259                 createDirectory(dir);
2260                 for (String intface : mapIntfacePTH.keySet()) {
2261                         // Get the right StructDecl
2262                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2263                         EnumDecl enumDecl = (EnumDecl) decHandler.getEnumDecl(intface);
2264                         Set<String> enumTypes = enumDecl.getEnumDeclarations();
2265                         // Iterate over enum declarations
2266                         for (String enType : enumTypes) {
2267                                 // Open a new file to write into
2268                                 FileWriter fw = new FileWriter(dir + "/" + enType + ".hpp");
2269                                 pw = new PrintWriter(new BufferedWriter(fw));
2270                                 // Write file headers
2271                                 println("#ifndef _" + enType.toUpperCase() + "_HPP__");
2272                                 println("#define _" + enType.toUpperCase() + "_HPP__");
2273                                 println("enum " + enType + " {");
2274                                 List<String> enumMembers = enumDecl.getMembers(enType);
2275                                 for (int i = 0; i < enumMembers.size(); i++) {
2276
2277                                         String member = enumMembers.get(i);
2278                                         print(member);
2279                                         // Check if this is the last element (don't print a comma)
2280                                         if (i != enumMembers.size() - 1)
2281                                                 println(",");
2282                                         else
2283                                                 println("");
2284                                 }
2285                                 println("};\n");
2286                                 println("#endif");
2287                                 pw.close();
2288                                 System.out.println("IoTCompiler: Generated enum " + enType + ".hpp...");
2289                         }
2290                 }
2291         }
2292
2293
2294         /**
2295          * HELPER: generateStructCplus() writes the struct declaration
2296          */
2297         public void generateStructCplus() throws IOException {
2298
2299                 // Create a new directory
2300                 createDirectory(dir);
2301                 for (String intface : mapIntfacePTH.keySet()) {
2302                         // Get the right StructDecl
2303                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2304                         StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
2305                         List<String> structTypes = structDecl.getStructTypes();
2306                         // Iterate over enum declarations
2307                         for (String stType : structTypes) {
2308                                 // Open a new file to write into
2309                                 FileWriter fw = new FileWriter(dir + "/" + stType + ".hpp");
2310                                 pw = new PrintWriter(new BufferedWriter(fw));
2311                                 // Write file headers
2312                                 println("#ifndef _" + stType.toUpperCase() + "_HPP__");
2313                                 println("#define _" + stType.toUpperCase() + "_HPP__");
2314                                 println("struct " + stType + " {");
2315                                 List<String> structMemberTypes = structDecl.getMemberTypes(stType);
2316                                 List<String> structMembers = structDecl.getMembers(stType);
2317                                 for (int i = 0; i < structMembers.size(); i++) {
2318
2319                                         String memberType = structMemberTypes.get(i);
2320                                         String member = structMembers.get(i);
2321                                         String structTypeC = checkAndGetCplusType(memberType);
2322                                         String structComplete = checkAndGetCplusArray(structTypeC, member);
2323                                         println(structComplete + ";");
2324                                 }
2325                                 println("};\n");
2326                                 println("#endif");
2327                                 pw.close();
2328                                 System.out.println("IoTCompiler: Generated struct " + stType + ".hpp...");
2329                         }
2330                 }
2331         }
2332
2333
2334         /**
2335          * generateCplusLocalInterfaces() writes the local interfaces and provides type-checking.
2336          * <p>
2337          * It needs to rewrite and exchange USERDEFINED types in input parameters of stub
2338          * and original interfaces, e.g. exchange Camera and CameraWithVideoAndRecording.
2339          * The local interface has to be the input parameter for the stub and the stub 
2340          * interface has to be the input parameter for the local class.
2341          */
2342         public void generateCplusLocalInterfaces() throws IOException {
2343
2344                 // Create a new directory
2345                 createDirectory(dir);
2346                 for (String intface : mapIntfacePTH.keySet()) {
2347                         // Open a new file to write into
2348                         FileWriter fw = new FileWriter(dir + "/" + intface + ".hpp");
2349                         pw = new PrintWriter(new BufferedWriter(fw));
2350                         // Write file headers
2351                         println("#ifndef _" + intface.toUpperCase() + "_HPP__");
2352                         println("#define _" + intface.toUpperCase() + "_HPP__");
2353                         println("#include <iostream>");
2354                         // Pass in set of methods and get include classes
2355                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2356                         InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
2357                         List<String> methods = intDecl.getMethods();
2358                         Set<String> includeClasses = getIncludeClasses(methods, intDecl, intface, true);
2359                         printIncludeStatements(includeClasses); println("");
2360                         println("using namespace std;\n");
2361                         // Write enum if any...
2362                         //EnumDecl enumDecl = (EnumDecl) decHandler.getEnumDecl(intface);
2363                         //writeEnumCplus(enumDecl);
2364                         // Write struct if any...
2365                         //StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
2366                         //writeStructCplus(structDecl);
2367                         println("class " + intface); println("{");
2368                         println("public:");
2369                         // Write methods
2370                         writeMethodCplusLocalInterface(methods, intDecl);
2371                         println("};");
2372                         println("#endif");
2373                         pw.close();
2374                         System.out.println("IoTCompiler: Generated local interface " + intface + ".hpp...");
2375                 }
2376         }
2377
2378
2379         /**
2380          * generateCPlusInterfaces() generate stub interfaces based on the methods list in C++
2381          * <p>
2382          * For C++ we use virtual classe as interface
2383          */
2384         public void generateCPlusInterfaces() throws IOException {
2385
2386                 // Create a new directory
2387                 String path = createDirectories(dir, subdir);
2388                 for (String intface : mapIntfacePTH.keySet()) {
2389
2390                         Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
2391                         for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
2392
2393                                 // Open a new file to write into
2394                                 String newIntface = intMeth.getKey();
2395                                 FileWriter fw = new FileWriter(path + "/" + newIntface + ".hpp");
2396                                 pw = new PrintWriter(new BufferedWriter(fw));
2397                                 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2398                                 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
2399                                 // Write file headers
2400                                 println("#ifndef _" + newIntface.toUpperCase() + "_HPP__");
2401                                 println("#define _" + newIntface.toUpperCase() + "_HPP__");
2402                                 println("#include <iostream>");
2403                                 // Pass in set of methods and get import classes
2404                                 Set<String> includeClasses = getIncludeClasses(intMeth.getValue(), intDecl, intface, false);
2405                                 List<String> stdIncludeClasses = getStandardCplusIncludeClasses();
2406                                 List<String> allIncludeClasses = getAllLibClasses(stdIncludeClasses, includeClasses);
2407                                 printIncludeStatements(allIncludeClasses); println("");                 
2408                                 println("using namespace std;\n");
2409                                 println("class " + newIntface);
2410                                 println("{");
2411                                 println("public:");
2412                                 // Write methods
2413                                 writeMethodCplusInterface(intMeth.getValue(), intDecl);
2414                                 println("};");
2415                                 println("#endif");
2416                                 pw.close();
2417                                 System.out.println("IoTCompiler: Generated interface " + newIntface + ".hpp...");
2418                         }
2419                 }
2420         }
2421
2422
2423         /**
2424          * HELPER: writeMethodCplusStub() writes the method of the stub
2425          */
2426         private void writeMethodCplusStub(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
2427
2428                 for (String method : methods) {
2429
2430                         List<String> methParams = intDecl.getMethodParams(method);
2431                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2432                         print(checkAndGetCplusType(intDecl.getMethodType(method)) + " " +
2433                                 intDecl.getMethodId(method) + "(");
2434                         boolean isCallbackMethod = false;
2435                         String callbackType = null;
2436                         for (int i = 0; i < methParams.size(); i++) {
2437
2438                                 String paramType = methPrmTypes.get(i);
2439                                 // Check if this has callback object
2440                                 if (callbackClasses.contains(paramType)) {
2441                                         isCallbackMethod = true;
2442                                         callbackType = paramType;       
2443                                         // Even if there're 2 callback arguments, we expect them to be of the same interface
2444                                 }
2445                                 String methPrmType = checkAndGetCplusType(methPrmTypes.get(i));
2446                                 String methParamComplete = checkAndGetCplusArray(methPrmType, methParams.get(i));
2447                                 print(methParamComplete);
2448                                 // Check if this is the last element (don't print a comma)
2449                                 if (i != methParams.size() - 1) {
2450                                         print(", ");
2451                                 }
2452                         }
2453                         println(") { ");
2454                         if (isCallbackMethod)
2455                                 writeCallbackMethodBodyCplusStub(intDecl, methParams, methPrmTypes, method, callbackType);
2456                         else
2457                                 writeStdMethodBodyCplusStub(intDecl, methParams, methPrmTypes, method);
2458                         println("}\n");
2459                         // Write the init callback helper method
2460                         if (isCallbackMethod) {
2461                                 writeInitCallbackCplusStub(callbackType, intDecl);
2462                                 writeInitCallbackSendInfoCplusStub(intDecl);
2463                         }
2464                 }
2465         }
2466
2467
2468         /**
2469          * HELPER: writeCallbackMethodBodyCplusStub() writes the callback method of the stub class
2470          */
2471         private void writeCallbackMethodBodyCplusStub(InterfaceDecl intDecl, List<String> methParams,
2472                         List<String> methPrmTypes, String method, String callbackType) {
2473
2474                 // Check if this is single object, array, or list of objects
2475                 boolean isArrayOrList = false;
2476                 String callbackParam = null;
2477                 for (int i = 0; i < methParams.size(); i++) {
2478
2479                         String paramType = methPrmTypes.get(i);
2480                         if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
2481                                 String param = methParams.get(i);
2482                                 if (isArrayOrList(paramType, param)) {  // Generate loop
2483                                         println("for (" + paramType + "* cb : " + getSimpleIdentifier(param) + ") {");
2484                                         println(callbackType + "_CallbackSkeleton* skel = new " + callbackType + "_CallbackSkeleton(cb, objIdCnt++);");
2485                                         isArrayOrList = true;
2486                                         callbackParam = getSimpleIdentifier(param);
2487                                 } else
2488                                         println(callbackType + "_CallbackSkeleton* skel = new " + callbackType + "_CallbackSkeleton(" +
2489                                                 getSimpleIdentifier(param) + ", objIdCnt++);");
2490                                 println("vecCallbackObj.push_back(skel);");
2491                                 if (isArrayOrList(paramType, param))
2492                                         println("}");
2493                         }
2494                 }
2495                 println("int numParam = " + methParams.size() + ";");
2496                 println("int methodId = " + intDecl.getMethodNumId(method) + ";");
2497                 String retType = intDecl.getMethodType(method);
2498                 String retTypeC = checkAndGetCplusType(retType);
2499                 println("string retType = \"" + checkAndGetCplusArrayType(retTypeC) + "\";");
2500                 // Generate array of parameter types
2501                 print("string paramCls[] = { ");
2502                 for (int i = 0; i < methParams.size(); i++) {
2503                         String paramType = methPrmTypes.get(i);
2504                         if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
2505                                 print("\"int\"");
2506                         } else { // Generate normal classes if it's not a callback object
2507                                 String paramTypeC = checkAndGetCplusType(methPrmTypes.get(i));
2508                                 String prmType = checkAndGetCplusArrayType(paramTypeC, methParams.get(i));
2509                                 print("\"" + prmType + "\"");
2510                         }
2511                         if (i != methParams.size() - 1) // Check if this is the last element
2512                                 print(", ");
2513                 }
2514                 println(" };");
2515                 print("int ___paramCB = ");
2516                 if (isArrayOrList)
2517                         println(callbackParam + ".size();");
2518                 else
2519                         println("1;");
2520                 // Generate array of parameter objects
2521                 print("void* paramObj[] = { ");
2522                 for (int i = 0; i < methParams.size(); i++) {
2523                         String paramType = methPrmTypes.get(i);
2524                         if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
2525                                 print("&___paramCB");
2526                         } else
2527                                 print(getSimpleIdentifier(methParams.get(i)));
2528                         if (i != methParams.size() - 1)
2529                                 print(", ");
2530                 }
2531                 println(" };");
2532                 // Check if this is "void"
2533                 if (retType.equals("void")) {
2534                         println("void* retObj = NULL;");
2535                         println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
2536                 } else { // We do have a return value
2537                         if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
2538                                 println(checkAndGetCplusType(retType) + " retVal;");
2539                         else
2540                                 println(checkAndGetCplusType(retType) + " retVal = " + generateCplusInitializer(retType) + ";");
2541                         println("void* retObj = &retVal;");
2542                         println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
2543                         println("return retVal;");
2544                 }
2545         }
2546
2547
2548         /**
2549          * HELPER: checkAndWriteEnumTypeCplusStub() writes the enum type (convert from enum to int)
2550          */
2551         private void checkAndWriteEnumTypeCplusStub(List<String> methParams, List<String> methPrmTypes) {
2552
2553                 // Iterate and find enum declarations
2554                 for (int i = 0; i < methParams.size(); i++) {
2555                         String paramType = methPrmTypes.get(i);
2556                         String param = methParams.get(i);
2557                         String simpleType = getSimpleType(paramType);
2558                         if (isEnumClass(simpleType)) {
2559                         // Check if this is enum type
2560                                 if (isArrayOrList(paramType, param)) {  // An array or vector
2561                                         println("int len" + i + " = " + param + ".size();");
2562                                         println("vector<int> paramEnum" + i + "(len);");
2563                                         println("for (int i = 0; i < len" + i + "; i++) {");
2564                                         println("paramEnum" + i + "[i] = (int) " + param + "[i];");
2565                                         println("}");
2566                                 } else {        // Just one element
2567                                         println("vector<int> paramEnum" + i + "(1);");
2568                                         println("paramEnum" + i + "[0] = (int) " + param + ";");
2569                                 }
2570                         }
2571                 }
2572         }
2573
2574
2575         /**
2576          * HELPER: checkAndWriteEnumRetTypeCplusStub() writes the enum return type (convert from enum to int)
2577          */
2578         private void checkAndWriteEnumRetTypeCplusStub(String retType) {
2579
2580                 // Strips off array "[]" for return type
2581                 String pureType = getSimpleArrayType(getSimpleType(retType));
2582                 // Take the inner type of generic
2583                 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
2584                         pureType = getTypeOfGeneric(retType)[0];
2585                 if (isEnumClass(pureType)) {
2586                 // Check if this is enum type
2587                         println("vector<int> retEnumInt;");
2588                         println("void* retObj = &retEnumInt;");
2589                         println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
2590                         if (isArrayOrList(retType, retType)) {  // An array or vector
2591                                 println("int retLen = retEnumInt.size();");
2592                                 println("vector<" + pureType + "> retVal(retLen);");
2593                                 println("for (int i = 0; i < retLen; i++) {");
2594                                 println("retVal[i] = (" + pureType + ") retEnumInt[i];");
2595                                 println("}");
2596                         } else {        // Just one element
2597                                 println(pureType + " retVal = (" + pureType + ") retEnumInt[0];");
2598                         }
2599                         println("return retVal;");
2600                 }
2601         }
2602
2603
2604         /**
2605          * HELPER: writeStdMethodBodyCplusStub() writes the standard method body in the stub class
2606          */
2607         private void writeStdMethodBodyCplusStub(InterfaceDecl intDecl, List<String> methParams,
2608                         List<String> methPrmTypes, String method) {
2609
2610                 println("int numParam = " + methParams.size() + ";");
2611                 println("int methodId = " + intDecl.getMethodNumId(method) + ";");
2612                 String retType = intDecl.getMethodType(method);
2613                 String retTypeC = checkAndGetCplusType(retType);
2614                 println("string retType = \"" + checkAndGetCplusArrayType(getEnumType(retTypeC)) + "\";");
2615                 // Generate array of parameter types
2616                 print("string paramCls[] = { ");
2617                 for (int i = 0; i < methParams.size(); i++) {
2618                         String paramTypeC = checkAndGetCplusType(methPrmTypes.get(i));
2619                         String paramType = checkAndGetCplusArrayType(paramTypeC, methParams.get(i));
2620                         print("\"" + getEnumType(paramType) + "\"");
2621                         // Check if this is the last element (don't print a comma)
2622                         if (i != methParams.size() - 1) {
2623                                 print(", ");
2624                         }
2625                 }
2626                 println(" };");
2627                 checkAndWriteEnumTypeCplusStub(methParams, methPrmTypes);
2628                 // Generate array of parameter objects
2629                 print("void* paramObj[] = { ");
2630                 for (int i = 0; i < methParams.size(); i++) {
2631                         print("&" + getEnumParam(methPrmTypes.get(i), getSimpleIdentifier(methParams.get(i)), i));
2632                         // Check if this is the last element (don't print a comma)
2633                         if (i != methParams.size() - 1) {
2634                                 print(", ");
2635                         }
2636                 }
2637                 println(" };");
2638                 // Check if this is "void"
2639                 if (retType.equals("void")) {
2640                         println("void* retObj = NULL;");
2641                         println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
2642                 } else { // We do have a return value
2643                         if (getParamCategory(retType) == ParamCategory.ENUM) {
2644                                 checkAndWriteEnumRetTypeCplusStub(retType);
2645                         } else {
2646                                 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
2647                                         println(checkAndGetCplusType(retType) + " retVal;");
2648                                 else
2649                                         println(checkAndGetCplusType(retType) + " retVal = " + generateCplusInitializer(retType) + ";");
2650                                 println("void* retObj = &retVal;");
2651                                 println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
2652                                 println("return retVal;");
2653                         }
2654                 }
2655         }
2656
2657
2658         /**
2659          * HELPER: writePropertiesCplusStub() writes the properties of the stub class
2660          */
2661         private void writePropertiesCplusPermission(String intface) {
2662
2663                 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
2664                 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
2665                         String newIntface = intMeth.getKey();
2666                         int newObjectId = mapNewIntfaceObjId.get(newIntface);
2667                         println("const static int object" + newObjectId + "Id = " + newObjectId + ";");
2668                         println("const static set<int> set" + newObjectId + "Allowed;");
2669                 }
2670         }       
2671
2672         /**
2673          * HELPER: writePropertiesCplusStub() writes the properties of the stub class
2674          */
2675         private void writePropertiesCplusStub(String intface, String newIntface, boolean callbackExist, Set<String> callbackClasses) {
2676
2677                 println("IoTRMICall *rmiCall;");
2678                 //println("IoTRMIObject\t\t\t*rmiObj;");
2679                 println("string address;");
2680                 println("vector<int> ports;\n");
2681                 // Get the object Id
2682                 Integer objId = mapIntfaceObjId.get(intface);
2683                 println("const static int objectId = " + objId + ";");
2684                 mapNewIntfaceObjId.put(newIntface, objId);
2685                 mapIntfaceObjId.put(intface, objId++);
2686                 if (callbackExist) {
2687                 // We assume that each class only has one callback interface for now
2688                         Iterator it = callbackClasses.iterator();
2689                         String callbackType = (String) it.next();
2690                         println("// Callback properties");
2691                         println("IoTRMIObject *rmiObj;");
2692                         println("vector<" + callbackType + "*> vecCallbackObj;");
2693                         println("static int objIdCnt;");
2694                         // Generate permission stuff for callback stubs
2695                         writePropertiesCplusPermission(callbackType);
2696                 }
2697                 println("\n");
2698         }
2699
2700
2701         /**
2702          * HELPER: writeConstructorCplusStub() writes the constructor of the stub class
2703          */
2704         private void writeConstructorCplusStub(String newStubClass, boolean callbackExist, Set<String> callbackClasses) {
2705
2706                 println(newStubClass + 
2707                         "(int _port, const char* _address, int _rev, bool* _bResult, vector<int> _ports) {");
2708                 println("address = _address;");
2709                 println("ports = _ports;");
2710                 println("rmiCall = new IoTRMICall(_port, _address, _rev, _bResult);");
2711                 if (callbackExist) {
2712                         println("objIdCnt = 0;");
2713                         Iterator it = callbackClasses.iterator();
2714                         String callbackType = (String) it.next();
2715                         println("thread th1 (&" + newStubClass + "::___initCallBack, this);");
2716                         println("th1.detach();");
2717                         println("___regCB();");
2718                 }
2719                 println("}\n");
2720         }
2721
2722
2723         /**
2724          * HELPER: writeDeconstructorCplusStub() writes the deconstructor of the stub class
2725          */
2726         private void writeDeconstructorCplusStub(String newStubClass, boolean callbackExist, Set<String> callbackClasses) {
2727
2728                 println("~" + newStubClass + "() {");
2729                 println("if (rmiCall != NULL) {");
2730                 println("delete rmiCall;");
2731                 println("rmiCall = NULL;");
2732                 println("}");
2733                 if (callbackExist) {
2734                 // We assume that each class only has one callback interface for now
2735                         println("if (rmiObj != NULL) {");
2736                         println("delete rmiObj;");
2737                         println("rmiObj = NULL;");
2738                         println("}");
2739                         Iterator it = callbackClasses.iterator();
2740                         String callbackType = (String) it.next();
2741                         println("for(" + callbackType + "* cb : vecCallbackObj) {");
2742                         println("delete cb;");
2743                         println("cb = NULL;");
2744                         println("}");
2745                 }
2746                 println("}");
2747                 println("");
2748         }
2749
2750
2751         /**
2752          * HELPER: writeCplusMethodCallbackPermission() writes permission checks in stub for callbacks
2753          */
2754         private void writeCplusMethodCallbackPermission(String intface) {
2755
2756                 println("int methodId = IoTRMIObject::getMethodId(method);");
2757                 // Get all the different stubs
2758                 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
2759                 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
2760                         String newIntface = intMeth.getKey();
2761                         int newObjectId = mapNewIntfaceObjId.get(newIntface);
2762                         println("if (set" + newObjectId + "Allowed.find(methodId) == set" + newObjectId + "Allowed.end()) {");
2763                         println("cerr << \"Callback object for " + intface + " is not allowed to access method: \" << methodId;");
2764                         println("exit(-1);");
2765                         println("}");
2766                 }
2767         }
2768
2769
2770         /**
2771          * HELPER: writeInitCallbackCplusStub() writes the initialization of callback
2772          */
2773         private void writeInitCallbackCplusStub(String intface, InterfaceDecl intDecl) {
2774
2775                 println("void ___initCallBack() {");
2776                 println("bool bResult = false;");
2777                 println("rmiObj = new IoTRMIObject(ports[0], &bResult);");
2778                 println("while (true) {");
2779                 println("char* method = rmiObj->getMethodBytes();");
2780                 writeCplusMethodCallbackPermission(intface);
2781                 println("int objId = IoTRMIObject::getObjectId(method);");
2782                 println("if (objId < vecCallbackObj.size()) {   // Check if still within range");
2783                 println(intface + "_CallbackSkeleton* skel = dynamic_cast<" + intface + 
2784                         "_CallbackSkeleton*> (vecCallbackObj.at(objId));");
2785                 println("skel->invokeMethod(rmiObj);");
2786                 println("} else {");
2787                 println("cerr << \"Illegal object Id: \" << to_string(objId);");
2788                 // TODO: perhaps need to change this into "throw" to make it cleaner (allow stack unfolding)
2789                 println("exit(-1);");
2790                 println("}");
2791                 println("}");
2792                 println("}\n");
2793         }
2794
2795
2796         /**
2797          * HELPER: writeInitCallbackSendInfoCplusStub() writes the initialization of callback
2798          */
2799         private void writeInitCallbackSendInfoCplusStub(InterfaceDecl intDecl) {
2800
2801                 // Generate info sending part
2802                 println("void ___regCB() {");
2803                 println("int numParam = 3;");
2804                 String method = "___initCallBack()";
2805                 println("int methodId = " + intDecl.getHelperMethodNumId(method) + ";");
2806                 println("string retType = \"void\";");
2807                 println("string paramCls[] = { \"int\", \"string\", \"int\" };");
2808                 println("int rev = 0;");
2809                 println("void* paramObj[] = { &ports[0], &address, &rev };");
2810                 println("void* retObj = NULL;");
2811                 println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
2812                 println("}\n");
2813         }
2814
2815
2816         /**
2817          * generateCPlusStubClasses() generate stubs based on the methods list in C++
2818          */
2819         public void generateCPlusStubClasses() throws IOException {
2820
2821                 // Create a new directory
2822                 String path = createDirectories(dir, subdir);
2823                 for (String intface : mapIntfacePTH.keySet()) {
2824
2825                         Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
2826                         for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
2827                                 // Open a new file to write into
2828                                 String newIntface = intMeth.getKey();
2829                                 String newStubClass = newIntface + "_Stub";
2830                                 FileWriter fw = new FileWriter(path + "/" + newStubClass + ".hpp");
2831                                 pw = new PrintWriter(new BufferedWriter(fw));
2832                                 // Write file headers
2833                                 println("#ifndef _" + newStubClass.toUpperCase() + "_HPP__");
2834                                 println("#define _" + newStubClass.toUpperCase() + "_HPP__");
2835                                 println("#include <iostream>");
2836                                 // Find out if there are callback objects
2837                                 Set<String> methods = intMeth.getValue();
2838                                 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2839                                 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
2840                                 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
2841                                 boolean callbackExist = !callbackClasses.isEmpty();
2842                                 if (callbackExist)      // Need thread library if this has callback
2843                                         println("#include <thread>");
2844                                 println("#include \"" + newIntface + ".hpp\""); println("");            
2845                                 println("using namespace std;"); println("");
2846                                 println("class " + newStubClass + " : public " + newIntface); println("{");
2847                                 println("private:\n");
2848                                 writePropertiesCplusStub(intface, newIntface, callbackExist, callbackClasses);
2849                                 println("public:\n");
2850                                 // Add default constructor and destructor
2851                                 println(newStubClass + "() { }"); println("");
2852                                 writeConstructorCplusStub(newStubClass, callbackExist, callbackClasses);
2853                                 writeDeconstructorCplusStub(newStubClass, callbackExist, callbackClasses);
2854                                 // Write methods
2855                                 writeMethodCplusStub(methods, intDecl, callbackClasses);
2856                                 print("}"); println(";");
2857                                 if (callbackExist)
2858                                         writePermissionInitializationCplus(intface, newStubClass, intDecl);
2859                                 println("#endif");
2860                                 pw.close();
2861                                 System.out.println("IoTCompiler: Generated stub class " + newStubClass + ".hpp...");
2862                         }
2863                 }
2864         }
2865
2866
2867         /**
2868          * HELPER: writePropertiesCplusCallbackStub() writes the properties of the stub class
2869          */
2870         private void writePropertiesCplusCallbackStub(String intface, String newIntface, boolean callbackExist, Set<String> callbackClasses) {
2871
2872                 println("IoTRMICall *rmiCall;");
2873                 // Get the object Id
2874                 println("static int objectId;");
2875                 if (callbackExist) {
2876                 // We assume that each class only has one callback interface for now
2877                         Iterator it = callbackClasses.iterator();
2878                         String callbackType = (String) it.next();
2879                         println("// Callback properties");
2880                         println("IoTRMIObject *rmiObj;");
2881                         println("vector<" + callbackType + "*> vecCallbackObj;");
2882                         println("static int objIdCnt;");
2883                         // TODO: Need to initialize address and ports if we want to have callback-in-callback
2884                         println("string address;");
2885                         println("vector<int> ports;\n");
2886                         writePropertiesCplusPermission(callbackType);
2887                 }
2888                 println("\n");
2889         }
2890
2891
2892         /**
2893          * HELPER: writeConstructorCplusCallbackStub() writes the constructor of the stub class
2894          */
2895         private void writeConstructorCplusCallbackStub(String newStubClass, boolean callbackExist, Set<String> callbackClasses) {
2896
2897                 println(newStubClass + "(IoTRMICall* _rmiCall, int _objectId) {");
2898                 println("objectId = _objectId;");
2899                 println("rmiCall = _rmiCall;");
2900                 if (callbackExist) {
2901                         Iterator it = callbackClasses.iterator();
2902                         String callbackType = (String) it.next();
2903                         println("thread th1 (&" + newStubClass + "::___initCallBack, this);");
2904                         println("th1.detach();");
2905                         println("___regCB();");
2906                 }
2907                 println("}\n");
2908         }
2909
2910
2911         /**
2912          * generateCPlusCallbackStubClasses() generate callback stubs based on the methods list in C++
2913          */
2914         public void generateCPlusCallbackStubClasses() throws IOException {
2915
2916                 // Create a new directory
2917                 String path = createDirectories(dir, subdir);
2918                 for (String intface : mapIntfacePTH.keySet()) {
2919
2920                         Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
2921                         for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
2922                                 // Open a new file to write into
2923                                 String newIntface = intMeth.getKey();
2924                                 String newStubClass = newIntface + "_CallbackStub";
2925                                 FileWriter fw = new FileWriter(path + "/" + newStubClass + ".hpp");
2926                                 pw = new PrintWriter(new BufferedWriter(fw));
2927                                 // Find out if there are callback objects
2928                                 Set<String> methods = intMeth.getValue();
2929                                 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2930                                 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
2931                                 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
2932                                 boolean callbackExist = !callbackClasses.isEmpty();
2933                                 // Write file headers
2934                                 println("#ifndef _" + newStubClass.toUpperCase() + "_HPP__");
2935                                 println("#define _" + newStubClass.toUpperCase() + "_HPP__");
2936                                 println("#include <iostream>");
2937                                 if (callbackExist)
2938                                         println("#include <thread>");
2939                                 println("#include \"" + newIntface + ".hpp\""); println("");            
2940                                 println("using namespace std;"); println("");
2941                                 println("class " + newStubClass + " : public " + newIntface); println("{");
2942                                 println("private:\n");
2943                                 writePropertiesCplusCallbackStub(intface, newIntface, callbackExist, callbackClasses);
2944                                 println("public:\n");
2945                                 // Add default constructor and destructor
2946                                 println(newStubClass + "() { }"); println("");
2947                                 writeConstructorCplusCallbackStub(newStubClass, callbackExist, callbackClasses);
2948                                 writeDeconstructorCplusStub(newStubClass, callbackExist, callbackClasses);
2949                                 // Write methods
2950                                 writeMethodCplusStub(methods, intDecl, callbackClasses);
2951                                 println("};");
2952                                 if (callbackExist)
2953                                         writePermissionInitializationCplus(intface, newStubClass, intDecl);
2954                                 println("#endif");
2955                                 pw.close();
2956                                 System.out.println("IoTCompiler: Generated callback stub class " + newIntface + ".hpp...");
2957                         }
2958                 }
2959         }
2960
2961
2962         /**
2963          * HELPER: writePropertiesCplusSkeleton() writes the properties of the skeleton class
2964          */
2965         private void writePropertiesCplusSkeleton(String intface, boolean callbackExist, Set<String> callbackClasses) {
2966
2967                 println(intface + " *mainObj;");
2968                 // Callback
2969                 if (callbackExist) {
2970                         Iterator it = callbackClasses.iterator();
2971                         String callbackType = (String) it.next();
2972                         String exchangeType = checkAndGetParamClass(callbackType);
2973                         println("// Callback properties");
2974                         println("static int objIdCnt;");
2975                         println("vector<" + exchangeType + "*> vecCallbackObj;");
2976                         println("IoTRMICall *rmiCall;");
2977                 }
2978                 println("IoTRMIObject *rmiObj;\n");
2979                 // Keep track of object Ids of all stubs registered to this interface
2980                 writePropertiesCplusPermission(intface);
2981                 println("\n");
2982         }
2983
2984
2985         /**
2986          * HELPER: writePermissionInitializationCplus() writes the initialization of permission set
2987          */
2988         private void writePermissionInitializationCplus(String intface, String newSkelClass, InterfaceDecl intDecl) {
2989
2990                 // Keep track of object Ids of all stubs registered to this interface
2991                 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
2992                 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
2993                         String newIntface = intMeth.getKey();
2994                         int newObjectId = mapNewIntfaceObjId.get(newIntface);
2995                         print("const set<int> " + newSkelClass + "::set" + newObjectId + "Allowed {");
2996                         Set<String> methodIds = intMeth.getValue();
2997                         int i = 0;
2998                         for (String methodId : methodIds) {
2999                                 int methodNumId = intDecl.getMethodNumId(methodId);
3000                                 print(Integer.toString(methodNumId));
3001                                 // Check if this is the last element (don't print a comma)
3002                                 if (i != methodIds.size() - 1) {
3003                                         print(", ");
3004                                 }
3005                                 i++;
3006                         }
3007                         println(" };");
3008                 }       
3009         }
3010
3011
3012         /**
3013          * HELPER: writeConstructorCplusSkeleton() writes the constructor of the skeleton class
3014          */
3015         private void writeConstructorCplusSkeleton(String newSkelClass, String intface, boolean callbackExist) {
3016
3017                 println(newSkelClass + "(" + intface + " *_mainObj, int _port) {");
3018                 println("bool _bResult = false;");
3019                 println("mainObj = _mainObj;");
3020                 println("rmiObj = new IoTRMIObject(_port, &_bResult);");
3021                 // Callback
3022                 if (callbackExist) {
3023                         println("objIdCnt = 0;");
3024                 }
3025                 //println("set0Allowed = Arrays.asList(object0Permission);");
3026                 println("___waitRequestInvokeMethod();");
3027                 println("}\n");
3028         }
3029
3030
3031         /**
3032          * HELPER: writeDeconstructorCplusSkeleton() writes the deconstructor of the skeleton class
3033          */
3034         private void writeDeconstructorCplusSkeleton(String newSkelClass, boolean callbackExist, Set<String> callbackClasses) {
3035
3036                 println("~" + newSkelClass + "() {");
3037                 println("if (rmiObj != NULL) {");
3038                 println("delete rmiObj;");
3039                 println("rmiObj = NULL;");
3040                 println("}");
3041                 if (callbackExist) {
3042                 // We assume that each class only has one callback interface for now
3043                         println("if (rmiCall != NULL) {");
3044                         println("delete rmiCall;");
3045                         println("rmiCall = NULL;");
3046                         println("}");
3047                         Iterator it = callbackClasses.iterator();
3048                         String callbackType = (String) it.next();
3049                         String exchangeType = checkAndGetParamClass(callbackType);
3050                         println("for(" + exchangeType + "* cb : vecCallbackObj) {");
3051                         println("delete cb;");
3052                         println("cb = NULL;");
3053                         println("}");
3054                 }
3055                 println("}");
3056                 println("");
3057         }
3058
3059
3060         /**
3061          * HELPER: writeStdMethodBodyCplusSkeleton() writes the standard method body in the skeleton class
3062          */
3063         private void writeStdMethodBodyCplusSkeleton(List<String> methParams, String methodId, String methodType) {
3064
3065                 if (methodType.equals("void"))
3066                         print("mainObj->" + methodId + "(");
3067                 else
3068                         print("return mainObj->" + methodId + "(");
3069                 for (int i = 0; i < methParams.size(); i++) {
3070
3071                         print(getSimpleIdentifier(methParams.get(i)));
3072                         // Check if this is the last element (don't print a comma)
3073                         if (i != methParams.size() - 1) {
3074                                 print(", ");
3075                         }
3076                 }
3077                 println(");");
3078         }
3079
3080
3081         /**
3082          * HELPER: writeInitCallbackCplusSkeleton() writes the init callback method for skeleton class
3083          */
3084         private void writeInitCallbackCplusSkeleton(boolean callbackSkeleton) {
3085
3086                 // This is a callback skeleton generation
3087                 if (callbackSkeleton)
3088                         println("void ___regCB(IoTRMIObject* rmiObj) {");
3089                 else
3090                         println("void ___regCB() {");
3091                 println("int numParam = 3;");
3092                 println("int param1 = 0;");
3093                 println("string param2 = \"\";");
3094                 println("int param3 = 0;");
3095                 println("void* paramObj[] = { &param1, &param2, &param3 };");
3096                 println("bool bResult = false;");
3097                 println("rmiCall = new IoTRMICall(param1, param2.c_str(), param3, &bResult);");
3098                 println("}\n");
3099         }
3100
3101
3102         /**
3103          * HELPER: writeMethodCplusSkeleton() writes the method of the skeleton class
3104          */
3105         private void writeMethodCplusSkeleton(Collection<String> methods, InterfaceDecl intDecl, 
3106                         Set<String> callbackClasses, boolean callbackSkeleton) {
3107
3108                 for (String method : methods) {
3109
3110                         List<String> methParams = intDecl.getMethodParams(method);
3111                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
3112                         String methodId = intDecl.getMethodId(method);
3113                         String methodType = checkAndGetCplusType(intDecl.getMethodType(method));
3114                         print(methodType + " " + methodId + "(");
3115                         boolean isCallbackMethod = false;
3116                         String callbackType = null;
3117                         for (int i = 0; i < methParams.size(); i++) {
3118
3119                                 String origParamType = methPrmTypes.get(i);
3120                                 if (callbackClasses.contains(origParamType)) { // Check if this has callback object
3121                                         isCallbackMethod = true;
3122                                         callbackType = origParamType;   
3123                                 }
3124                                 String paramType = checkAndGetParamClass(methPrmTypes.get(i));
3125                                 String methPrmType = checkAndGetCplusType(paramType);
3126                                 String methParamComplete = checkAndGetCplusArray(methPrmType, methParams.get(i));
3127                                 print(methParamComplete);
3128                                 // Check if this is the last element (don't print a comma)
3129                                 if (i != methParams.size() - 1) {
3130                                         print(", ");
3131                                 }
3132                         }
3133                         println(") {");
3134                         // Now, write the body of skeleton!
3135                         writeStdMethodBodyCplusSkeleton(methParams, methodId, intDecl.getMethodType(method));
3136                         println("}\n");
3137                         if (isCallbackMethod)
3138                                 writeInitCallbackCplusSkeleton(callbackSkeleton);
3139                 }
3140         }
3141
3142
3143         /**
3144          * HELPER: writeCallbackCplusNumStubs() writes the numStubs variable
3145          */
3146         private void writeCallbackCplusNumStubs(List<String> methParams, List<String> methPrmTypes, String callbackType) {
3147
3148                 for (int i = 0; i < methParams.size(); i++) {
3149                         String paramType = methPrmTypes.get(i);
3150                         String param = methParams.get(i);
3151                         //if (callbackType.equals(paramType)) {
3152                         if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
3153                                 String exchParamType = checkAndGetParamClass(paramType);
3154                                 // Print array if this is array or list if this is a list of callback objects
3155                                 println("int numStubs" + i + " = 0;");
3156                         }
3157                 }
3158         }
3159
3160
3161         /**
3162          * HELPER: writeCallbackCplusStubGeneration() writes the callback stub generation part
3163          */
3164         private void writeCallbackCplusStubGeneration(List<String> methParams, List<String> methPrmTypes, String callbackType) {
3165
3166                 // Iterate over callback objects
3167                 for (int i = 0; i < methParams.size(); i++) {
3168                         String paramType = methPrmTypes.get(i);
3169                         String param = methParams.get(i);
3170                         // Generate a loop if needed
3171                         if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
3172                                 String exchParamType = checkAndGetParamClass(paramType);
3173                                 if (isArrayOrList(paramType, param)) {
3174                                         println("vector<" + exchParamType + "> stub;");
3175                                         println("for (int objId = 0; objId < numStubs" + i + "; objId++) {");
3176                                         println(exchParamType + "* cb" + i + " = new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt);");
3177                                         println("stub" + i + ".push_back(cb);");
3178                                         println("vecCallbackObj.push_back(cb);");
3179                                         println("objIdCnt++;");
3180                                         println("}");
3181                                 } else {
3182                                         println(exchParamType + "* stub" + i + " = new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt);");
3183                                         println("vecCallbackObj.push_back(stub" + i + ");");
3184                                         println("objIdCnt++;");
3185                                 }
3186                         }
3187                 }
3188         }
3189
3190
3191         /**
3192          * HELPER: checkAndWriteEnumTypeCplusSkeleton() writes the enum type (convert from enum to int)
3193          */
3194         private void checkAndWriteEnumTypeCplusSkeleton(List<String> methParams, List<String> methPrmTypes) {
3195
3196                 // Iterate and find enum declarations
3197                 for (int i = 0; i < methParams.size(); i++) {
3198                         String paramType = methPrmTypes.get(i);
3199                         String param = methParams.get(i);
3200                         String simpleType = getSimpleType(paramType);
3201                         if (isEnumClass(simpleType)) {
3202                         // Check if this is enum type
3203                                 if (isArrayOrList(paramType, param)) {  // An array
3204                                         println("int len" + i + " = paramEnumInt" + i + ".size();");
3205                                         println("vector<" + simpleType + "> paramEnum" + i + "(len" + i + ");");
3206                                         println("for (int i=0; i < len" + i + "; i++) {");
3207                                         println("paramEnum" + i + "[i] = (" + simpleType + ") paramEnumInt" + i + "[i];");
3208                                         println("}");
3209                                 } else {        // Just one element
3210                                         println(simpleType + " paramEnum" + i + ";");
3211                                         println("paramEnum" + i + " = (" + simpleType + ") paramEnumInt" + i + "[0];");
3212                                 }
3213                         }
3214                 }
3215         }
3216
3217
3218         /**
3219          * HELPER: checkAndWriteEnumRetTypeCplusSkeleton() writes the enum return type (convert from enum to int)
3220          */
3221         private void checkAndWriteEnumRetTypeCplusSkeleton(String retType) {
3222
3223                 // Strips off array "[]" for return type
3224                 String pureType = getSimpleArrayType(getSimpleType(retType));
3225                 // Take the inner type of generic
3226                 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
3227                         pureType = getTypeOfGeneric(retType)[0];
3228                 if (isEnumClass(pureType)) {
3229                 // Check if this is enum type
3230                         // Enum decoder
3231                         if (isArrayOrList(retType, retType)) {  // An array
3232                                 println("int retLen = retEnum.size();");
3233                                 println("vector<int> retEnumInt(retLen);");
3234                                 println("for (int i=0; i < retLen; i++) {");
3235                                 println("retEnumInt[i] = (int) retEnum[i];");
3236                                 println("}");
3237                         } else {        // Just one element
3238                                 println("vector<int> retEnumInt(1);");
3239                                 println("retEnumInt[0] = (int) retEnum;");
3240                         }
3241                 }
3242         }
3243
3244
3245         /**
3246          * HELPER: writeStdMethodHelperBodyCplusSkeleton() writes the standard method body helper in the skeleton class
3247          */
3248         private void writeStdMethodHelperBodyCplusSkeleton(InterfaceDecl intDecl, List<String> methParams,
3249                         List<String> methPrmTypes, String method, String methodId, Set<String> callbackClasses) {
3250
3251                 // Generate array of parameter types
3252                 boolean isCallbackMethod = false;
3253                 String callbackType = null;
3254                 print("string paramCls[] = { ");
3255                 for (int i = 0; i < methParams.size(); i++) {
3256                         String paramType = returnGenericCallbackType(methPrmTypes.get(i));
3257                         if (callbackClasses.contains(paramType)) {
3258                                 isCallbackMethod = true;
3259                                 callbackType = paramType;
3260                                 print("\"int\"");
3261                         } else {        // Generate normal classes if it's not a callback object
3262                                 String paramTypeC = checkAndGetCplusType(methPrmTypes.get(i));
3263                                 String prmType = checkAndGetCplusArrayType(paramTypeC, methParams.get(i));
3264                                 print("\"" + getEnumType(prmType) + "\"");
3265                         }
3266                         if (i != methParams.size() - 1) {
3267                                 print(", ");
3268                         }
3269                 }
3270                 println(" };");
3271                 println("int numParam = " + methParams.size() + ";");
3272                 if (isCallbackMethod)
3273                         writeCallbackCplusNumStubs(methParams, methPrmTypes, callbackType);
3274                 // Generate parameters
3275                 for (int i = 0; i < methParams.size(); i++) {
3276                         String paramType = returnGenericCallbackType(methPrmTypes.get(i));
3277                         if (!callbackClasses.contains(paramType)) {
3278                                 String methPrmType = checkAndGetCplusType(methPrmTypes.get(i));
3279                                 if (isEnumClass(getSimpleType(methPrmType))) {  // Check if this is enum type
3280                                         println("vector<int> paramEnumInt" + i + ";");
3281                                 } else {
3282                                         String methParamComplete = checkAndGetCplusArray(methPrmType, methParams.get(i));
3283                                         println(methParamComplete + ";");
3284                                 }
3285                         }
3286                 }
3287                 // Generate array of parameter objects
3288                 print("void* paramObj[] = { ");
3289                 for (int i = 0; i < methParams.size(); i++) {
3290                         String paramType = returnGenericCallbackType(methPrmTypes.get(i));
3291                         if (callbackClasses.contains(paramType))
3292                                 print("&numStubs" + i);
3293                         else if (isEnumClass(getSimpleType(paramType))) // Check if this is enum type
3294                                 print("&paramEnumInt" + i);
3295                         else
3296                                 print("&" + getSimpleIdentifier(methParams.get(i)));
3297                         if (i != methParams.size() - 1) {
3298                                 print(", ");
3299                         }
3300                 }
3301                 println(" };");
3302                 println("rmiObj->getMethodParams(paramCls, numParam, paramObj);");
3303                 if (isCallbackMethod)
3304                         writeCallbackCplusStubGeneration(methParams, methPrmTypes, callbackType);
3305                 checkAndWriteEnumTypeCplusSkeleton(methParams, methPrmTypes);
3306                 String retType = intDecl.getMethodType(method);
3307                 // Check if this is "void"
3308                 if (retType.equals("void")) {
3309                         print(methodId + "(");
3310                         for (int i = 0; i < methParams.size(); i++) {
3311                                 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
3312                                 if (callbackClasses.contains(paramType))
3313                                         print("stub" + i);
3314                                 else if (isEnumClass(getSimpleType(paramType))) // Check if this is enum type
3315                                         print("paramEnum" + i);
3316                                 else
3317                                         print(getSimpleIdentifier(methParams.get(i)));
3318                                 if (i != methParams.size() - 1) {
3319                                         print(", ");
3320                                 }
3321                         }
3322                         println(");");
3323                 } else { // We do have a return value
3324                         if (isEnumClass(getSimpleArrayType(getSimpleType(retType)))) // Enum type
3325                                 print(checkAndGetCplusType(retType) + " retEnum = ");
3326                         else
3327                                 print(checkAndGetCplusType(retType) + " retVal = ");
3328                         print(methodId + "(");
3329                         for (int i = 0; i < methParams.size(); i++) {
3330                                 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
3331                                 if (callbackClasses.contains(paramType))
3332                                         print("stub" + i);
3333                                 else if (isEnumClass(getSimpleType(paramType))) // Check if this is enum type
3334                                         print("paramEnum" + i);
3335                                 else
3336                                         print(getSimpleIdentifier(methParams.get(i)));
3337                                 if (i != methParams.size() - 1) {
3338                                         print(", ");
3339                                 }
3340                         }
3341                         println(");");
3342                         checkAndWriteEnumRetTypeCplusSkeleton(retType);
3343                         if (isEnumClass(getSimpleArrayType(getSimpleType(retType)))) // Enum type
3344                                 println("void* retObj = &retEnumInt;");
3345                         else
3346                                 println("void* retObj = &retVal;");
3347                         String retTypeC = checkAndGetCplusType(retType);
3348                         println("rmiObj->sendReturnObj(retObj, \"" + getEnumType(checkAndGetCplusArrayType(retTypeC)) + "\");");
3349                 }
3350         }
3351
3352
3353         /**
3354          * HELPER: writeMethodHelperCplusSkeleton() writes the method helper of the skeleton class
3355          */
3356         private void writeMethodHelperCplusSkeleton(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
3357
3358                 // Use this set to handle two same methodIds
3359                 Set<String> uniqueMethodIds = new HashSet<String>();
3360                 for (String method : methods) {
3361
3362                         List<String> methParams = intDecl.getMethodParams(method);
3363                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
3364                         String methodId = intDecl.getMethodId(method);
3365                         print("void ___");
3366                         String helperMethod = methodId;
3367                         if (uniqueMethodIds.contains(methodId))
3368                                 helperMethod = helperMethod + intDecl.getMethodNumId(method);
3369                         else
3370                                 uniqueMethodIds.add(methodId);
3371                         // Check if this is "void"
3372                         String retType = intDecl.getMethodType(method);
3373                         println(helperMethod + "() {");
3374                         // Now, write the helper body of skeleton!
3375                         writeStdMethodHelperBodyCplusSkeleton(intDecl, methParams, methPrmTypes, method, methodId, callbackClasses);
3376                         println("}\n");
3377                 }
3378         }
3379
3380
3381         /**
3382          * HELPER: writeCplusMethodPermission() writes permission checks in skeleton
3383          */
3384         private void writeCplusMethodPermission(String intface) {
3385
3386                 // Get all the different stubs
3387                 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3388                 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3389                         String newIntface = intMeth.getKey();
3390                         int newObjectId = mapNewIntfaceObjId.get(newIntface);
3391                         println("if (_objectId == object" + newObjectId + "Id) {");
3392                         println("if (set" + newObjectId + "Allowed.find(methodId) == set" + newObjectId + "Allowed.end()) {");
3393                         println("cerr << \"Object with object Id: \" << _objectId << \"  is not allowed to access method: \" << methodId << endl;");
3394                         println("exit(-1);");
3395                         println("}");
3396                         println("else {");
3397                         println("cerr << \"Object Id: \" << _objectId << \" not recognized!\" << endl;");
3398                         println("exit(-1);");
3399                         println("}");
3400                         println("}");
3401                 }
3402         }
3403
3404
3405         /**
3406          * HELPER: writeCplusWaitRequestInvokeMethod() writes the main loop of the skeleton class
3407          */
3408         private void writeCplusWaitRequestInvokeMethod(Collection<String> methods, InterfaceDecl intDecl, boolean callbackExist, String intface) {
3409
3410                 // Use this set to handle two same methodIds
3411                 Set<String> uniqueMethodIds = new HashSet<String>();
3412                 println("void ___waitRequestInvokeMethod() {");
3413                 // Write variables here if we have callbacks or enums or structs
3414                 println("while (true) {");
3415                 println("rmiObj->getMethodBytes();");
3416                 println("int _objectId = rmiObj->getObjectId();");
3417                 println("int methodId = rmiObj->getMethodId();");
3418                 // Generate permission check
3419                 writeCplusMethodPermission(intface);
3420                 println("switch (methodId) {");
3421                 // Print methods and method Ids
3422                 for (String method : methods) {
3423                         String methodId = intDecl.getMethodId(method);
3424                         int methodNumId = intDecl.getMethodNumId(method);
3425                         print("case " + methodNumId + ": ___");
3426                         String helperMethod = methodId;
3427                         if (uniqueMethodIds.contains(methodId))
3428                                 helperMethod = helperMethod + methodNumId;
3429                         else
3430                                 uniqueMethodIds.add(methodId);
3431                         println(helperMethod + "(); break;");
3432                 }
3433                 String method = "___initCallBack()";
3434                 // Print case -9999 (callback handler) if callback exists
3435                 if (callbackExist) {
3436                         int methodId = intDecl.getHelperMethodNumId(method);
3437                         println("case " + methodId + ": ___regCB(); break;");
3438                 }
3439                 println("default: ");
3440                 println("cerr << \"Method Id \" << methodId << \" not recognized!\" << endl;");
3441                 println("throw exception();");
3442                 println("}");
3443                 println("}");
3444                 println("}\n");
3445         }
3446
3447
3448         /**
3449          * generateCplusSkeletonClass() generate skeletons based on the methods list in C++
3450          */
3451         public void generateCplusSkeletonClass() throws IOException {
3452
3453                 // Create a new directory
3454                 String path = createDirectories(dir, subdir);
3455                 for (String intface : mapIntfacePTH.keySet()) {
3456                         // Open a new file to write into
3457                         String newSkelClass = intface + "_Skeleton";
3458                         FileWriter fw = new FileWriter(path + "/" + newSkelClass + ".hpp");
3459                         pw = new PrintWriter(new BufferedWriter(fw));
3460                         // Write file headers
3461                         println("#ifndef _" + newSkelClass.toUpperCase() + "_HPP__");
3462                         println("#define _" + newSkelClass.toUpperCase() + "_HPP__");
3463                         println("#include <iostream>");
3464                         println("#include \"" + intface + ".hpp\"\n");
3465                         // Pass in set of methods and get import classes
3466                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
3467                         InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
3468                         List<String> methods = intDecl.getMethods();
3469                         Set<String> includeClasses = getIncludeClasses(methods, intDecl, intface, true);
3470                         List<String> stdIncludeClasses = getStandardCplusIncludeClasses();
3471                         List<String> allIncludeClasses = getAllLibClasses(stdIncludeClasses, includeClasses);
3472                         printIncludeStatements(allIncludeClasses); println("");
3473                         println("using namespace std;\n");
3474                         // Find out if there are callback objects
3475                         Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
3476                         boolean callbackExist = !callbackClasses.isEmpty();
3477                         // Write class header
3478                         println("class " + newSkelClass + " : public " + intface); println("{");
3479                         println("private:\n");
3480                         // Write properties
3481                         writePropertiesCplusSkeleton(intface, callbackExist, callbackClasses);
3482                         println("public:\n");
3483                         // Write constructor
3484                         writeConstructorCplusSkeleton(newSkelClass, intface, callbackExist);
3485                         // Write deconstructor
3486                         writeDeconstructorCplusSkeleton(newSkelClass, callbackExist, callbackClasses);
3487                         // Write methods
3488                         writeMethodCplusSkeleton(methods, intDecl, callbackClasses, false);
3489                         // Write method helper
3490                         writeMethodHelperCplusSkeleton(methods, intDecl, callbackClasses);
3491                         // Write waitRequestInvokeMethod() - main loop
3492                         writeCplusWaitRequestInvokeMethod(methods, intDecl, callbackExist, intface);
3493                         println("};");
3494                         writePermissionInitializationCplus(intface, newSkelClass, intDecl);
3495                         println("#endif");
3496                         pw.close();
3497                         System.out.println("IoTCompiler: Generated skeleton class " + newSkelClass + ".hpp...");
3498                 }
3499         }
3500
3501
3502         /**
3503          * HELPER: writePropertiesCplusCallbackSkeleton() writes the properties of the callback skeleton class
3504          */
3505         private void writePropertiesCplusCallbackSkeleton(String intface, boolean callbackExist, Set<String> callbackClasses) {
3506
3507                 println(intface + " *mainObj;");
3508                 // Keep track of object Ids of all stubs registered to this interface
3509                 println("static int objectId;");
3510                 // Callback
3511                 if (callbackExist) {
3512                         Iterator it = callbackClasses.iterator();
3513                         String callbackType = (String) it.next();
3514                         String exchangeType = checkAndGetParamClass(callbackType);
3515                         println("// Callback properties");
3516                         println("IoTRMICall* rmiCall;");
3517                         println("vector<" + exchangeType + "*> vecCallbackObj;");
3518                         println("static int objIdCnt;");
3519                 }
3520                 println("\n");
3521         }
3522
3523
3524         /**
3525          * HELPER: writeConstructorCplusCallbackSkeleton() writes the constructor of the skeleton class
3526          */
3527         private void writeConstructorCplusCallbackSkeleton(String newSkelClass, String intface, boolean callbackExist) {
3528
3529                 println(newSkelClass + "(" + intface + " *_mainObj, int _objectId) {");
3530                 println("mainObj = _mainObj;");
3531                 println("objectId = _objectId;");
3532                 // Callback
3533                 if (callbackExist) {
3534                         println("objIdCnt = 0;");
3535                 }
3536                 println("}\n");
3537         }
3538
3539
3540         /**
3541          * HELPER: writeDeconstructorCplusStub() writes the deconstructor of the stub class
3542          */
3543         private void writeDeconstructorCplusCallbackSkeleton(String newStubClass, boolean callbackExist, 
3544                         Set<String> callbackClasses) {
3545
3546                 println("~" + newStubClass + "() {");
3547                 if (callbackExist) {
3548                 // We assume that each class only has one callback interface for now
3549                         println("if (rmiCall != NULL) {");
3550                         println("delete rmiCall;");
3551                         println("rmiCall = NULL;");
3552                         println("}");
3553                         Iterator it = callbackClasses.iterator();
3554                         String callbackType = (String) it.next();
3555                         String exchangeType = checkAndGetParamClass(callbackType);
3556                         println("for(" + exchangeType + "* cb : vecCallbackObj) {");
3557                         println("delete cb;");
3558                         println("cb = NULL;");
3559                         println("}");
3560                 }
3561                 println("}");
3562                 println("");
3563         }
3564
3565
3566         /**
3567          * HELPER: writeMethodHelperCplusCallbackSkeleton() writes the method helper of the callback skeleton class
3568          */
3569         private void writeMethodHelperCplusCallbackSkeleton(Collection<String> methods, InterfaceDecl intDecl, 
3570                         Set<String> callbackClasses) {
3571
3572                 // Use this set to handle two same methodIds
3573                 Set<String> uniqueMethodIds = new HashSet<String>();
3574                 for (String method : methods) {
3575
3576                         List<String> methParams = intDecl.getMethodParams(method);
3577                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
3578                         String methodId = intDecl.getMethodId(method);
3579                         print("void ___");
3580                         String helperMethod = methodId;
3581                         if (uniqueMethodIds.contains(methodId))
3582                                 helperMethod = helperMethod + intDecl.getMethodNumId(method);
3583                         else
3584                                 uniqueMethodIds.add(methodId);
3585                         // Check if this is "void"
3586                         String retType = intDecl.getMethodType(method);
3587                         println(helperMethod + "(IoTRMIObject* rmiObj) {");
3588                         // Now, write the helper body of skeleton!
3589                         writeStdMethodHelperBodyCplusSkeleton(intDecl, methParams, methPrmTypes, method, methodId, callbackClasses);
3590                         println("}\n");
3591                 }
3592         }
3593
3594
3595         /**
3596          * HELPER: writeCplusCallbackWaitRequestInvokeMethod() writes the main loop of the skeleton class
3597          */
3598         private void writeCplusCallbackWaitRequestInvokeMethod(Collection<String> methods, InterfaceDecl intDecl, 
3599                         boolean callbackExist) {
3600
3601                 // Use this set to handle two same methodIds
3602                 Set<String> uniqueMethodIds = new HashSet<String>();
3603                 println("void invokeMethod(IoTRMIObject* rmiObj) {");
3604                 // Write variables here if we have callbacks or enums or structs
3605                 println("int methodId = rmiObj->getMethodId();");
3606                 // TODO: code the permission check here!
3607                 println("switch (methodId) {");
3608                 // Print methods and method Ids
3609                 for (String method : methods) {
3610                         String methodId = intDecl.getMethodId(method);
3611                         int methodNumId = intDecl.getMethodNumId(method);
3612                         print("case " + methodNumId + ": ___");
3613                         String helperMethod = methodId;
3614                         if (uniqueMethodIds.contains(methodId))
3615                                 helperMethod = helperMethod + methodNumId;
3616                         else
3617                                 uniqueMethodIds.add(methodId);
3618                         println(helperMethod + "(rmiObj); break;");
3619                 }
3620                 String method = "___initCallBack()";
3621                 // Print case -9999 (callback handler) if callback exists
3622                 if (callbackExist) {
3623                         int methodId = intDecl.getHelperMethodNumId(method);
3624                         println("case " + methodId + ": ___regCB(rmiObj); break;");
3625                 }
3626                 println("default: ");
3627                 println("cerr << \"Method Id \" << methodId << \" not recognized!\" << endl;");
3628                 println("throw exception();");
3629                 println("}");
3630                 println("}\n");
3631         }
3632
3633
3634
3635         /**
3636          * generateCplusCallbackSkeletonClass() generate callback skeletons based on the methods list in C++
3637          */
3638         public void generateCplusCallbackSkeletonClass() throws IOException {
3639
3640                 // Create a new directory
3641                 String path = createDirectories(dir, subdir);
3642                 for (String intface : mapIntfacePTH.keySet()) {
3643                         // Open a new file to write into
3644                         String newSkelClass = intface + "_CallbackSkeleton";
3645                         FileWriter fw = new FileWriter(path + "/" + newSkelClass + ".hpp");
3646                         pw = new PrintWriter(new BufferedWriter(fw));
3647                         // Write file headers
3648                         println("#ifndef _" + newSkelClass.toUpperCase() + "_HPP__");
3649                         println("#define _" + newSkelClass.toUpperCase() + "_HPP__");
3650                         println("#include <iostream>");
3651                         println("#include \"" + intface + ".hpp\"\n");
3652                         // Pass in set of methods and get import classes
3653                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
3654                         InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
3655                         List<String> methods = intDecl.getMethods();
3656                         Set<String> includeClasses = getIncludeClasses(methods, intDecl, intface, true);
3657                         List<String> stdIncludeClasses = getStandardCplusIncludeClasses();
3658                         List<String> allIncludeClasses = getAllLibClasses(stdIncludeClasses, includeClasses);
3659                         printIncludeStatements(allIncludeClasses); println("");                 
3660                         // Find out if there are callback objects
3661                         Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
3662                         boolean callbackExist = !callbackClasses.isEmpty();
3663                         println("using namespace std;\n");
3664                         // Write class header
3665                         println("class " + newSkelClass + " : public " + intface); println("{");
3666                         println("private:\n");
3667                         // Write properties
3668                         writePropertiesCplusCallbackSkeleton(intface, callbackExist, callbackClasses);
3669                         println("public:\n");
3670                         // Write constructor
3671                         writeConstructorCplusCallbackSkeleton(newSkelClass, intface, callbackExist);
3672                         // Write deconstructor
3673                         writeDeconstructorCplusCallbackSkeleton(newSkelClass, callbackExist, callbackClasses);
3674                         // Write methods
3675                         writeMethodCplusSkeleton(methods, intDecl, callbackClasses, true);
3676                         // Write method helper
3677                         writeMethodHelperCplusCallbackSkeleton(methods, intDecl, callbackClasses);
3678                         // Write waitRequestInvokeMethod() - main loop
3679                         writeCplusCallbackWaitRequestInvokeMethod(methods, intDecl, callbackExist);
3680                         println("};");
3681                         println("#endif");
3682                         pw.close();
3683                         System.out.println("IoTCompiler: Generated callback skeleton class " + newSkelClass + ".hpp...");
3684                 }
3685         }
3686
3687
3688         /**
3689          * generateInitializer() generate initializer based on type
3690          */
3691         public String generateCplusInitializer(String type) {
3692
3693                 // Generate dummy returns for now
3694                 if (type.equals("short")||
3695                         type.equals("int")      ||
3696                         type.equals("long") ||
3697                         type.equals("float")||
3698                         type.equals("double")) {
3699
3700                         return "0";
3701                 } else if ( type.equals("String") ||
3702                                         type.equals("string")) {
3703   
3704                         return "\"\"";
3705                 } else if ( type.equals("char") ||
3706                                         type.equals("byte")) {
3707
3708                         return "\' \'";
3709                 } else if ( type.equals("boolean")) {
3710
3711                         return "false";
3712                 } else {
3713                         return "NULL";
3714                 }
3715         }
3716
3717
3718         /**
3719          * generateReturnStmt() generate return statement based on methType
3720          */
3721         public String generateReturnStmt(String methType) {
3722
3723                 // Generate dummy returns for now
3724                 if (methType.equals("short")||
3725                         methType.equals("int")  ||
3726                         methType.equals("long") ||
3727                         methType.equals("float")||
3728                         methType.equals("double")) {
3729
3730                         return "1";
3731                 } else if ( methType.equals("String")) {
3732   
3733                         return "\"a\"";
3734                 } else if ( methType.equals("char") ||
3735                                         methType.equals("byte")) {
3736
3737                         return "\'a\'";
3738                 } else if ( methType.equals("boolean")) {
3739
3740                         return "true";
3741                 } else {
3742                         return "null";
3743                 }
3744         }
3745
3746
3747         /**
3748          * setDirectory() sets a new directory for stub files
3749          */
3750         public void setDirectory(String _subdir) {
3751
3752                 subdir = _subdir;
3753         }
3754
3755
3756         /**
3757          * printUsage() prints the usage of this compiler
3758          */
3759         public static void printUsage() {
3760
3761                 System.out.println();
3762                 System.out.println("Sentinel interface and stub compiler version 1.0");
3763                 System.out.println("Copyright (c) 2015-2016 University of California, Irvine - Programming Language Group.");
3764                 System.out.println("All rights reserved.");
3765                 System.out.println("Usage:");
3766                 System.out.println("\tjava IoTCompiler -help / --help / -h\n");
3767                 System.out.println("\t\tDisplay this help texts\n\n");
3768                 System.out.println("\tjava IoTCompiler [<main-policy-file> <req-policy-file>]");
3769                 System.out.println("\tjava IoTCompiler [<main-policy-file> <req-policy-file>] [options]\n");
3770                 System.out.println("\t\tTake one or more pairs of main-req policy files, and generate Java and/or C++ files\n");
3771                 System.out.println("Options:");
3772                 System.out.println("\t-java\t<directory>\tGenerate Java stub files");
3773                 System.out.println("\t-cplus\t<directory>\tGenerate C++ stub files");
3774                 System.out.println();
3775         }
3776
3777
3778         /**
3779          * parseFile() prepares Lexer and Parser objects, then parses the file
3780          */
3781         public static ParseNode parseFile(String file) {
3782
3783                 ParseNode pn = null;
3784                 try {
3785                         ComplexSymbolFactory csf = new ComplexSymbolFactory();
3786                         ScannerBuffer lexer = 
3787                                 new ScannerBuffer(new Lexer(new BufferedReader(new FileReader(file)),csf));
3788                         Parser parse = new Parser(lexer,csf);
3789                         pn = (ParseNode) parse.parse().value;
3790                 } catch (Exception e) {
3791                         e.printStackTrace();
3792                         throw new Error("IoTCompiler: ERROR parsing policy file or wrong command line option: " + file);
3793                 }
3794
3795                 return pn;
3796         }
3797
3798
3799         /**================
3800          * Helper functions
3801          **================
3802          */
3803         boolean newline=true;
3804         int tablevel=0;
3805
3806         private void print(String str) {
3807                 if (newline) {
3808                         int tab=tablevel;
3809                         if (str.equals("}"))
3810                                 tab--;
3811                         for(int i=0; i<tab; i++)
3812                                 pw.print("\t");
3813                 }
3814                 pw.print(str);
3815                 updatetabbing(str);
3816                 newline=false;
3817         }
3818
3819
3820         /**
3821          * This function converts Java to C++ type for compilation
3822          */
3823         private String convertType(String jType) {
3824
3825                 return mapPrimitives.get(jType);
3826         }
3827
3828
3829         private void println(String str) {
3830                 if (newline) {
3831                         int tab = tablevel;
3832                         if (str.contains("}") && !str.contains("{"))
3833                                 tab--;
3834                         for(int i=0; i<tab; i++)
3835                                 pw.print("\t");
3836                 }
3837                 pw.println(str);
3838                 updatetabbing(str);
3839                 newline = true;
3840         }
3841
3842
3843         private void updatetabbing(String str) {
3844
3845                 tablevel+=count(str,'{')-count(str,'}');
3846         }
3847
3848
3849         private int count(String str, char key) {
3850                 char[] array = str.toCharArray();
3851                 int count = 0;
3852                 for(int i=0; i<array.length; i++) {
3853                         if (array[i] == key)
3854                                 count++;
3855                 }
3856                 return count;
3857         }
3858
3859
3860         private void createDirectory(String dirName) {
3861
3862                 File file = new File(dirName);
3863                 if (!file.exists()) {
3864                         if (file.mkdir()) {
3865                                 System.out.println("IoTCompiler: Directory " + dirName + " has been created!");
3866                         } else {
3867                                 System.out.println("IoTCompiler: Failed to create directory " + dirName + "!");
3868                         }
3869                 } else {
3870                         System.out.println("IoTCompiler: Directory " + dirName + " exists...");
3871                 }
3872         }
3873
3874
3875         // Create a directory and possibly a sub directory
3876         private String createDirectories(String dir, String subdir) {
3877
3878                 String path = dir;
3879                 createDirectory(path);
3880                 if (subdir != null) {
3881                         path = path + "/" + subdir;
3882                         createDirectory(path);
3883                 }
3884                 return path;
3885         }
3886
3887
3888         // Inserting array members into a Map object
3889         // that maps arrKey to arrVal objects
3890         private void arraysToMap(Map map, Object[] arrKey, Object[] arrVal) {
3891
3892                 for(int i = 0; i < arrKey.length; i++) {
3893
3894                         map.put(arrKey[i], arrVal[i]);
3895                 }
3896         }
3897
3898
3899         // Return parameter category, i.e. PRIMITIVES, NONPRIMITIVES, or USERDEFINED
3900         private ParamCategory getParamCategory(String paramType) {
3901
3902                 if (mapPrimitives.containsKey(paramType)) {
3903                         return ParamCategory.PRIMITIVES;
3904                 // We can either use mapNonPrimitivesJava or mapNonPrimitivesCplus here
3905                 } else if (mapNonPrimitivesJava.containsKey(getSimpleType(paramType))) {
3906                         return ParamCategory.NONPRIMITIVES;
3907                 } else if (isEnumClass(paramType)) {
3908                         return ParamCategory.ENUM;
3909                 } else if (isStructClass(paramType)) {
3910                         return ParamCategory.STRUCT;
3911                 } else
3912                         return ParamCategory.USERDEFINED;
3913         }
3914
3915
3916         // Return full class name for non-primitives to generate Java import statements
3917         // e.g. java.util.Set for Set, java.util.Map for Map
3918         private String getNonPrimitiveJavaClass(String paramNonPrimitives) {
3919
3920                 return mapNonPrimitivesJava.get(paramNonPrimitives);
3921         }
3922
3923
3924         // Return full class name for non-primitives to generate Cplus include statements
3925         // e.g. #include <set> for Set, #include <map> for Map
3926         private String getNonPrimitiveCplusClass(String paramNonPrimitives) {
3927
3928                 return mapNonPrimitivesCplus.get(paramNonPrimitives);
3929         }
3930
3931
3932         // Get simple types, e.g. HashSet for HashSet<...>
3933         // Basically strip off the "<...>"
3934         private String getSimpleType(String paramType) {
3935
3936                 // Check if this is generics
3937                 if(paramType.contains("<")) {
3938                         String[] type = paramType.split("<");
3939                         return type[0];
3940                 } else
3941                         return paramType;
3942         }
3943
3944
3945         // Generate a set of standard classes for import statements
3946         private List<String> getStandardJavaImportClasses() {
3947
3948                 List<String> importClasses = new ArrayList<String>();
3949                 // Add the standard list first
3950                 importClasses.add("java.io.IOException");
3951                 importClasses.add("java.util.List");
3952                 importClasses.add("java.util.ArrayList");
3953                 importClasses.add("java.util.Arrays");
3954                 importClasses.add("iotrmi.Java.IoTRMICall");
3955                 importClasses.add("iotrmi.Java.IoTRMIObject");
3956
3957                 return importClasses;
3958         }
3959
3960
3961         // Generate a set of standard classes for import statements
3962         private List<String> getStandardCplusIncludeClasses() {
3963
3964                 List<String> importClasses = new ArrayList<String>();
3965                 // Add the standard list first
3966                 importClasses.add("<vector>");
3967                 importClasses.add("<set>");
3968                 importClasses.add("\"IoTRMICall.hpp\"");
3969                 importClasses.add("\"IoTRMIObject.hpp\"");
3970
3971                 return importClasses;
3972         }
3973
3974
3975         // Generate a set of standard classes for import statements
3976         private List<String> getAllLibClasses(Collection<String> stdLibClasses, Collection<String> libClasses) {
3977
3978                 List<String> allLibClasses = new ArrayList<String>(stdLibClasses);
3979                 // Iterate over the list of import classes
3980                 for (String str : libClasses) {
3981                         if (!allLibClasses.contains(str)) {
3982                                 allLibClasses.add(str);
3983                         }
3984                 }
3985
3986                 return allLibClasses;
3987         }
3988
3989
3990
3991         // Generate a set of classes for import statements
3992         private Set<String> getImportClasses(Collection<String> methods, InterfaceDecl intDecl) {
3993
3994                 Set<String> importClasses = new HashSet<String>();
3995                 for (String method : methods) {
3996                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
3997                         for (String paramType : methPrmTypes) {
3998
3999                                 String simpleType = getSimpleType(paramType);
4000                                 if (getParamCategory(simpleType) == ParamCategory.NONPRIMITIVES) {
4001                                         importClasses.add(getNonPrimitiveJavaClass(simpleType));
4002                                 }
4003                         }
4004                 }
4005                 return importClasses;
4006         }
4007
4008
4009         // Handle and return the correct enum declaration
4010         // In Java, if we declare enum in Camera interface, then it becomes "Camera.<enum>"
4011         private String getEnumParamDecl(String type, InterfaceDecl intDecl) {
4012
4013                 // Strips off array "[]" for return type
4014                 String pureType = getSimpleArrayType(type);
4015                 // Take the inner type of generic
4016                 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
4017                         pureType = getTypeOfGeneric(type)[0];
4018                 if (isEnumClass(pureType)) {
4019                         String enumType = intDecl.getInterface() + "." + type;
4020                         return enumType;
4021                 } else
4022                         return type;
4023         }
4024
4025
4026         // Handle and return the correct type
4027         private String getEnumParam(String type, String param, int i) {
4028
4029                 // Strips off array "[]" for return type
4030                 String pureType = getSimpleArrayType(type);
4031                 // Take the inner type of generic
4032                 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
4033                         pureType = getTypeOfGeneric(type)[0];
4034                 if (isEnumClass(pureType)) {
4035                         String enumParam = "paramEnum" + i;
4036                         return enumParam;
4037                 } else
4038                         return param;
4039         }
4040
4041
4042         // Handle and return the correct enum declaration translate into int[]
4043         private String getEnumType(String type) {
4044
4045                 // Strips off array "[]" for return type
4046                 String pureType = getSimpleArrayType(type);
4047                 // Take the inner type of generic
4048                 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
4049                         pureType = getTypeOfGeneric(type)[0];
4050                 if (isEnumClass(pureType)) {
4051                         String enumType = "int[]";
4052                         return enumType;
4053                 } else
4054                         return type;
4055         }
4056
4057
4058         // Handle and return the correct struct declaration
4059         private String getStructType(String type) {
4060
4061                 // Strips off array "[]" for return type
4062                 String pureType = getSimpleArrayType(type);
4063                 // Take the inner type of generic
4064                 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
4065                         pureType = getTypeOfGeneric(type)[0];
4066                 if (isStructClass(pureType)) {
4067                         String structType = "int";
4068                         return structType;
4069                 } else
4070                         return type;
4071         }
4072
4073
4074         // Check if this an enum declaration
4075         private boolean isEnumClass(String type) {
4076
4077                 // Just iterate over the set of interfaces
4078                 for (String intface : mapIntfacePTH.keySet()) {
4079                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4080                         EnumDecl enumDecl = (EnumDecl) decHandler.getEnumDecl(intface);
4081                         Set<String> setEnumDecl = enumDecl.getEnumDeclarations();
4082                         if (setEnumDecl.contains(type))
4083                                 return true;
4084                 }
4085                 return false;
4086         }
4087
4088
4089         // Check if this an struct declaration
4090         private boolean isStructClass(String type) {
4091
4092                 // Just iterate over the set of interfaces
4093                 for (String intface : mapIntfacePTH.keySet()) {
4094                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4095                         StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
4096                         List<String> listStructDecl = structDecl.getStructTypes();
4097                         if (listStructDecl.contains(type))
4098                                 return true;
4099                 }
4100                 return false;
4101         }
4102
4103
4104         // Return a struct declaration
4105         private StructDecl getStructDecl(String type) {
4106
4107                 // Just iterate over the set of interfaces
4108                 for (String intface : mapIntfacePTH.keySet()) {
4109                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4110                         StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
4111                         List<String> listStructDecl = structDecl.getStructTypes();
4112                         if (listStructDecl.contains(type))
4113                                 return structDecl;
4114                 }
4115                 return null;
4116         }
4117
4118
4119         // Return number of members (-1 if not found)
4120         private int getNumOfMembers(String type) {
4121
4122                 // Just iterate over the set of interfaces
4123                 for (String intface : mapIntfacePTH.keySet()) {
4124                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4125                         StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
4126                         List<String> listStructDecl = structDecl.getStructTypes();
4127                         if (listStructDecl.contains(type))
4128                                 return structDecl.getNumOfMembers(type);
4129                 }
4130                 return -1;
4131         }
4132
4133
4134         // Generate a set of classes for include statements
4135         private Set<String> getIncludeClasses(Collection<String> methods, InterfaceDecl intDecl, String intface, boolean needExchange) {
4136
4137                 Set<String> includeClasses = new HashSet<String>();
4138                 for (String method : methods) {
4139
4140                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4141                         List<String> methParams = intDecl.getMethodParams(method);
4142                         for (int i = 0; i < methPrmTypes.size(); i++) {
4143
4144                                 String simpleType = getSimpleType(methPrmTypes.get(i));
4145                                 String param = methParams.get(i);
4146                                 if (getParamCategory(simpleType) == ParamCategory.NONPRIMITIVES) {
4147                                         includeClasses.add("<" + getNonPrimitiveCplusClass(simpleType) + ">");
4148                                 } else if (getParamCategory(simpleType) == ParamCategory.USERDEFINED) {
4149                                         // For original interface, we need it exchanged... not for stub interfaces
4150                                         if (needExchange) {
4151                                                 includeClasses.add("\"" + exchangeParamType(simpleType) + ".hpp\"");
4152                                                 includeClasses.add("\"" + exchangeParamType(simpleType) + "_CallbackStub.hpp\"");
4153                                         } else {
4154                                                 includeClasses.add("\"" + simpleType + ".hpp\"");
4155                                                 includeClasses.add("\"" + simpleType + "_CallbackSkeleton.hpp\"");
4156                                         }
4157                                 } else if (getParamCategory(getSimpleArrayType(simpleType)) == ParamCategory.ENUM) {
4158                                         includeClasses.add("\"" + simpleType + ".hpp\"");
4159                                 } else if (param.contains("[]")) {
4160                                 // Check if this is array for C++; translate into vector
4161                                         includeClasses.add("<vector>");
4162                                 }
4163                         }
4164                 }
4165                 return includeClasses;
4166         }
4167
4168
4169         // Generate a set of callback classes
4170         private Set<String> getCallbackClasses(Collection<String> methods, InterfaceDecl intDecl) {
4171
4172                 Set<String> callbackClasses = new HashSet<String>();
4173                 for (String method : methods) {
4174
4175                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4176                         List<String> methParams = intDecl.getMethodParams(method);
4177                         for (int i = 0; i < methPrmTypes.size(); i++) {
4178
4179                                 String type = methPrmTypes.get(i);
4180                                 if (getParamCategory(type) == ParamCategory.USERDEFINED) {
4181                                         callbackClasses.add(type);
4182                                 } else if (getParamCategory(type) == ParamCategory.NONPRIMITIVES) {
4183                                 // Can be a List<...> of callback objects ...
4184                                         String genericType = getTypeOfGeneric(type)[0];
4185                                         if (getParamCategory(type) == ParamCategory.USERDEFINED) {
4186                                                 callbackClasses.add(type);
4187                                         }
4188                                 }
4189                         }
4190                 }
4191                 return callbackClasses;
4192         }
4193
4194
4195         private void printImportStatements(Collection<String> importClasses) {
4196
4197                 for(String cls : importClasses) {
4198                         println("import " + cls + ";");
4199                 }
4200         }
4201
4202
4203         private void printIncludeStatements(Collection<String> includeClasses) {
4204
4205                 for(String cls : includeClasses) {
4206                         println("#include " + cls);
4207                 }
4208         }
4209
4210
4211         // Get the C++ version of a non-primitive type
4212         // e.g. set for Set and map for Map
4213         // Input nonPrimitiveType has to be generics in format
4214         private String[] getTypeOfGeneric(String nonPrimitiveType) {
4215
4216                 // Handle <, >, and , for 2-type generic/template
4217                 String[] substr = nonPrimitiveType.split("<")[1].split(">")[0].split(",");
4218                 return substr;
4219         }
4220
4221
4222         // Gets generic type inside "<" and ">"
4223         private String getGenericType(String type) {
4224
4225                 // Handle <, >, and , for 2-type generic/template
4226                 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES) {
4227                         String[] substr = type.split("<")[1].split(">")[0].split(",");
4228                         return substr[0];
4229                 } else
4230                         return type;
4231         }
4232
4233
4234         // This helper function strips off array declaration, e.g. int[] becomes int
4235         private String getSimpleArrayType(String type) {
4236
4237                 // Handle [ for array declaration
4238                 String substr = type;
4239                 if (type.contains("[]")) {
4240                         substr = type.split("\\[\\]")[0];
4241                 }
4242                 return substr;
4243         }
4244
4245
4246         // This helper function strips off array declaration, e.g. D[] becomes D
4247         private String getSimpleIdentifier(String ident) {
4248
4249                 // Handle [ for array declaration
4250                 String substr = ident;
4251                 if (ident.contains("[]")) {
4252                         substr = ident.split("\\[\\]")[0];
4253                 }
4254                 return substr;
4255         }
4256
4257
4258         private String checkAndGetCplusType(String paramType) {
4259
4260                 if (getParamCategory(paramType) == ParamCategory.PRIMITIVES) {
4261                         return convertType(paramType);
4262                 } else if (getParamCategory(paramType) == ParamCategory.NONPRIMITIVES) {
4263
4264                         // Check for generic/template format
4265                         if (paramType.contains("<") && paramType.contains(">")) {
4266
4267                                 String genericClass = getSimpleType(paramType);
4268                                 String[] genericType = getTypeOfGeneric(paramType);
4269                                 String cplusTemplate = null;
4270                                 if (genericType.length == 1) // Generic/template with one type
4271                                         cplusTemplate = getNonPrimitiveCplusClass(genericClass) + 
4272                                                 "<" + convertType(genericType[0]) + ">";
4273                                 else // Generic/template with two types
4274                                         cplusTemplate = getNonPrimitiveCplusClass(genericClass) + 
4275                                                 "<" + convertType(genericType[0]) + "," + convertType(genericType[1]) + ">";
4276                                 return cplusTemplate;
4277                         } else
4278                                 return getNonPrimitiveCplusClass(paramType);
4279                 } else if(paramType.contains("[]")) {   // Array type (used for return type only)
4280                         String cArray = "vector<" + getSimpleArrayType(paramType) + ">";
4281                         return cArray;
4282                 } else if(getParamCategory(paramType) == ParamCategory.USERDEFINED) {
4283                         return paramType + "*";
4284                 } else
4285                         // Just return it as is if it's not non-primitives
4286                         return paramType;
4287                         //return checkAndGetParamClass(paramType, true);
4288         }
4289
4290
4291         // Detect array declaration, e.g. int A[],
4292         //              then generate "int A[]" in C++ as "vector<int> A"
4293         private String checkAndGetCplusArray(String paramType, String param) {
4294
4295                 String paramComplete = null;
4296                 // Check for array declaration
4297                 if (param.contains("[]")) {
4298                         paramComplete = "vector<" + paramType + "> " + param.replace("[]","");
4299                 } else
4300                         // Just return it as is if it's not an array
4301                         paramComplete = paramType + " " + param;
4302
4303                 return paramComplete;
4304         }
4305         
4306
4307         // Detect array declaration, e.g. int A[],
4308         //              then generate "int A[]" in C++ as "vector<int> A"
4309         // This method just returns the type
4310         private String checkAndGetCplusArrayType(String paramType) {
4311
4312                 String paramTypeRet = null;
4313                 // Check for array declaration
4314                 if (paramType.contains("[]")) {
4315                         String type = paramType.split("\\[\\]")[0];
4316                         paramTypeRet = checkAndGetCplusType(type) + "[]";
4317                 } else if (paramType.contains("vector")) {
4318                         // Just return it as is if it's not an array
4319                         String type = paramType.split("<")[1].split(">")[0];
4320                         paramTypeRet = checkAndGetCplusType(type) + "[]";
4321                 } else
4322                         paramTypeRet = paramType;
4323
4324                 return paramTypeRet;
4325         }
4326         
4327         
4328         // Detect array declaration, e.g. int A[],
4329         //              then generate "int A[]" in C++ as "vector<int> A"
4330         // This method just returns the type
4331         private String checkAndGetCplusArrayType(String paramType, String param) {
4332
4333                 String paramTypeRet = null;
4334                 // Check for array declaration
4335                 if (param.contains("[]")) {
4336                         paramTypeRet = checkAndGetCplusType(paramType) + "[]";
4337                 } else if (paramType.contains("vector")) {
4338                         // Just return it as is if it's not an array
4339                         String type = paramType.split("<")[1].split(">")[0];
4340                         paramTypeRet = checkAndGetCplusType(type) + "[]";
4341                 } else
4342                         paramTypeRet = paramType;
4343
4344                 return paramTypeRet;
4345         }
4346
4347
4348         // Detect array declaration, e.g. int A[],
4349         //              then generate type "int[]"
4350         private String checkAndGetArray(String paramType, String param) {
4351
4352                 String paramTypeRet = null;
4353                 // Check for array declaration
4354                 if (param.contains("[]")) {
4355                         paramTypeRet = paramType + "[]";
4356                 } else
4357                         // Just return it as is if it's not an array
4358                         paramTypeRet = paramType;
4359
4360                 return paramTypeRet;
4361         }
4362
4363
4364         // Is array or list?
4365         private boolean isArrayOrList(String paramType, String param) {
4366
4367                 // Check for array declaration
4368                 if (isArray(param))
4369                         return true;
4370                 else if (isList(paramType))
4371                         return true;
4372                 else
4373                         return false;
4374         }
4375
4376
4377         // Is array? For return type we put the return type as input parameter
4378         private boolean isArray(String param) {
4379
4380                 // Check for array declaration
4381                 if (param.contains("[]"))
4382                         return true;
4383                 else
4384                         return false;
4385         }
4386
4387
4388         // Is list?
4389         private boolean isList(String paramType) {
4390
4391                 // Check for array declaration
4392                 if (paramType.contains("List"))
4393                         return true;
4394                 else
4395                         return false;
4396         }
4397
4398
4399         // Get the right type for a callback object
4400         private String checkAndGetParamClass(String paramType) {
4401
4402                 // Check if this is generics
4403                 if(getParamCategory(paramType) == ParamCategory.USERDEFINED) {
4404                         return exchangeParamType(paramType);
4405                 } else
4406                         return paramType;
4407         }
4408
4409
4410         // Returns the other interface for type-checking purposes for USERDEFINED
4411         //              classes based on the information provided in multiple policy files
4412         // e.g. return CameraWithXXX instead of Camera
4413         private String exchangeParamType(String intface) {
4414
4415                 // Param type that's passed is the interface name we need to look for
4416                 //              in the map of interfaces, based on available policy files.
4417                 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4418                 if (decHandler != null) {
4419                 // We've found the required interface policy files
4420                         RequiresDecl reqDecl = (RequiresDecl) decHandler.getRequiresDecl(intface);
4421                         Set<String> setExchInt = reqDecl.getInterfaces();
4422                         if (setExchInt.size() == 1) {
4423                                 Iterator iter = setExchInt.iterator();
4424                                 return (String) iter.next();
4425                         } else {
4426                                 throw new Error("IoTCompiler: Ambiguous stub interfaces: " + setExchInt.toString() + 
4427                                         ". Only one new interface can be declared if the object " + intface +
4428                                         " needs to be passed in as an input parameter!");
4429                         }
4430                 } else {
4431                 // NULL value - this means policy files missing
4432                         throw new Error("IoTCompiler: Parameter type lookup failed for " + intface +
4433                                 "... Please provide the necessary policy files for user-defined types." +
4434                                 " If this is an array please type the brackets after the variable name," +
4435                                 " e.g. \"String str[]\", not \"String[] str\"." +
4436                                 " If this is a Collections (Java) / STL (C++) type, this compiler only" +
4437                                 " supports List/ArrayList (Java) or list (C++).");
4438                 }
4439         }
4440
4441
4442         public static void main(String[] args) throws Exception {
4443
4444                 // If there is no argument or just "--help" or "-h", then invoke printUsage()
4445                 if ((args[0].equals("-help") ||
4446                          args[0].equals("--help")||
4447                          args[0].equals("-h"))   ||
4448                         (args.length == 0)) {
4449
4450                         IoTCompiler.printUsage();
4451
4452                 } else if (args.length > 1) {
4453
4454                         IoTCompiler comp = new IoTCompiler();
4455                         int i = 0;                              
4456                         do {
4457                                 // Parse main policy file
4458                                 ParseNode pnPol = IoTCompiler.parseFile(args[i]);
4459                                 // Parse "requires" policy file
4460                                 ParseNode pnReq = IoTCompiler.parseFile(args[i+1]);
4461                                 // Get interface name
4462                                 String intface = ParseTreeHandler.getOrigIntface(pnPol);
4463                                 comp.setDataStructures(intface, pnPol, pnReq);
4464                                 comp.getMethodsForIntface(intface);
4465                                 i = i + 2;
4466                         // 1) Check if this is the last option before "-java" or "-cplus"
4467                         // 2) Check if this is really the last option (no "-java" or "-cplus")
4468                         } while(!args[i].equals("-java") &&
4469                                         !args[i].equals("-cplus") &&
4470                                         (i < args.length));
4471
4472                         // Generate everything if we don't see "-java" or "-cplus"
4473                         if (i == args.length) {
4474                                 comp.generateEnumJava();
4475                                 comp.generateStructJava();
4476                                 comp.generateJavaLocalInterfaces();
4477                                 comp.generateJavaInterfaces();
4478                                 comp.generateJavaStubClasses();
4479                                 comp.generateJavaCallbackStubClasses();
4480                                 comp.generateJavaSkeletonClass();
4481                                 comp.generateJavaCallbackSkeletonClass();
4482                                 comp.generateEnumCplus();
4483                                 comp.generateStructCplus();
4484                                 comp.generateCplusLocalInterfaces();
4485                                 comp.generateCPlusInterfaces();
4486                                 comp.generateCPlusStubClasses();
4487                                 comp.generateCPlusCallbackStubClasses();
4488                                 comp.generateCplusSkeletonClass();
4489                                 comp.generateCplusCallbackSkeletonClass();
4490                         } else {
4491                         // Check other options
4492                                 while(i < args.length) {
4493                                         // Error checking
4494                                         if (!args[i].equals("-java") &&
4495                                                 !args[i].equals("-cplus")) {
4496                                                 throw new Error("IoTCompiler: ERROR - unrecognized command line option: " + args[i]);
4497                                         } else {
4498                                                 if (i + 1 < args.length) {
4499                                                         comp.setDirectory(args[i+1]);
4500                                                 } else
4501                                                         throw new Error("IoTCompiler: ERROR - please provide <directory> after option: " + args[i]);
4502
4503                                                 if (args[i].equals("-java")) {
4504                                                         comp.generateEnumJava();
4505                                                         comp.generateStructJava();
4506                                                         comp.generateJavaLocalInterfaces();
4507                                                         comp.generateJavaInterfaces();
4508                                                         comp.generateJavaStubClasses();
4509                                                         comp.generateJavaCallbackStubClasses();
4510                                                         comp.generateJavaSkeletonClass();
4511                                                         comp.generateJavaCallbackSkeletonClass();
4512                                                 } else {
4513                                                         comp.generateEnumCplus();
4514                                                         comp.generateStructCplus();
4515                                                         comp.generateCplusLocalInterfaces();
4516                                                         comp.generateCPlusInterfaces();
4517                                                         comp.generateCPlusStubClasses();
4518                                                         comp.generateCPlusCallbackStubClasses();
4519                                                         comp.generateCplusSkeletonClass();
4520                                                         comp.generateCplusCallbackSkeletonClass();
4521                                                 }
4522                                         }
4523                                         i = i + 2;
4524                                 }
4525                         }
4526                 } else {
4527                 // Need to at least have exactly 2 parameters, i.e. main policy file and requires file
4528                         IoTCompiler.printUsage();
4529                         throw new Error("IoTCompiler: At least two arguments (main and requires policy files) have to be provided!");
4530                 }
4531         }
4532 }
4533
4534
4535
4536