Fixing minor bugs for callback-in-callback placeholders
[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                 USERDEFINED             // Non-supported type by default; assumed as driver classes
72         }
73
74         /**
75          * Class constructors
76          */
77         public IoTCompiler() {
78
79                 mapIntfacePTH = new HashMap<String,ParseTreeHandler>();
80                 mapIntDeclHand = new HashMap<String,DeclarationHandler>();
81                 mapInt2NewInts = new HashMap<String,Map<String,Set<String>>>();
82                 mapIntfaceObjId = new HashMap<String,Integer>();
83                 mapNewIntfaceObjId = new HashMap<String,Integer>();
84                 mapPrimitives = new HashMap<String,String>();
85                         arraysToMap(mapPrimitives, IoTRMITypes.primitivesJava, IoTRMITypes.primitivesCplus);
86                 mapNonPrimitivesJava = new HashMap<String,String>();
87                         arraysToMap(mapNonPrimitivesJava, IoTRMITypes.nonPrimitivesJava, IoTRMITypes.nonPrimitiveJavaLibs);
88                 mapNonPrimitivesCplus = new HashMap<String,String>();
89                         arraysToMap(mapNonPrimitivesCplus, IoTRMITypes.nonPrimitivesJava, IoTRMITypes.nonPrimitivesCplus);
90                 pw = null;
91                 dir = OUTPUT_DIRECTORY;
92                 subdir = null;
93         }
94
95
96         /**
97          * setDataStructures() sets parse tree and other data structures based on policy files.
98          * <p>
99          * It also generates parse tree (ParseTreeHandler) and
100          * copies useful information from parse tree into
101          * InterfaceDecl, CapabilityDecl, and RequiresDecl 
102          * data structures.
103          * Additionally, the data structure handles are
104          * returned from tree-parsing for further process.
105          *
106          */
107         public void setDataStructures(String origInt, ParseNode pnPol, ParseNode pnReq) {
108
109                 ParseTreeHandler ptHandler = new ParseTreeHandler(origInt, pnPol, pnReq);
110                 DeclarationHandler decHandler = new DeclarationHandler();
111                 // Process ParseNode and generate Declaration objects
112                 // Interface
113                 ptHandler.processInterfaceDecl();
114                 InterfaceDecl intDecl = ptHandler.getInterfaceDecl();
115                 decHandler.addInterfaceDecl(origInt, intDecl);
116                 // Capabilities
117                 ptHandler.processCapabilityDecl();
118                 CapabilityDecl capDecl = ptHandler.getCapabilityDecl();
119                 decHandler.addCapabilityDecl(origInt, capDecl);
120                 // Requires
121                 ptHandler.processRequiresDecl();
122                 RequiresDecl reqDecl = ptHandler.getRequiresDecl();
123                 decHandler.addRequiresDecl(origInt, reqDecl);
124                 // Enumeration
125                 ptHandler.processEnumDecl();
126                 EnumDecl enumDecl = ptHandler.getEnumDecl();
127                 decHandler.addEnumDecl(origInt, enumDecl);
128                 // Struct
129                 ptHandler.processStructDecl();
130                 StructDecl structDecl = ptHandler.getStructDecl();
131                 decHandler.addStructDecl(origInt, structDecl);
132
133                 mapIntfacePTH.put(origInt, ptHandler);
134                 mapIntDeclHand.put(origInt, decHandler);
135                 // Set object Id counter to 0 for each interface
136                 mapIntfaceObjId.put(origInt, new Integer(0));
137         }
138
139
140         /**
141          * getMethodsForIntface() reads for methods in the data structure
142          * <p>
143          * It is going to give list of methods for a certain interface
144          *              based on the declaration of capabilities.
145          */
146         public void getMethodsForIntface(String origInt) {
147
148                 ParseTreeHandler ptHandler = mapIntfacePTH.get(origInt);
149                 Map<String,Set<String>> mapNewIntMethods = new HashMap<String,Set<String>>();
150                 // Get set of new interfaces, e.g. CameraWithCaptureAndData
151                 // Generate this new interface with all the methods it needs
152                 //              from different capabilities it declares
153                 DeclarationHandler decHandler = mapIntDeclHand.get(origInt);
154                 RequiresDecl reqDecl = (RequiresDecl) decHandler.getRequiresDecl(origInt);
155                 Set<String> setIntfaces = reqDecl.getInterfaces();
156                 for (String strInt : setIntfaces) {
157
158                         // Initialize a set of methods
159                         Set<String> setMethods = new HashSet<String>();
160                         // Get list of capabilities, e.g. ImageCapture, VideoRecording, etc.
161                         List<String> listCapab = reqDecl.getCapabList(strInt);
162                         for (String strCap : listCapab) {
163
164                                 // Get list of methods for each capability
165                                 CapabilityDecl capDecl = (CapabilityDecl) decHandler.getCapabilityDecl(origInt);
166                                 List<String> listCapabMeth = capDecl.getMethods(strCap);
167                                 for (String strMeth : listCapabMeth) {
168
169                                         // Add methods into setMethods
170                                         // This is to also handle redundancies (say two capabilities
171                                         //              share the same methods)
172                                         setMethods.add(strMeth);
173                                 }
174                         }
175                         // Add interface and methods information into map
176                         mapNewIntMethods.put(strInt, setMethods);
177                 }
178                 // Map the map of interface-methods to the original interface
179                 mapInt2NewInts.put(origInt, mapNewIntMethods);
180         }
181
182
183         /**
184          * HELPER: writeMethodJavaLocalInterface() writes the method of the interface
185          */
186         private void writeMethodJavaLocalInterface(Collection<String> methods, InterfaceDecl intDecl) {
187
188                 for (String method : methods) {
189
190                         List<String> methParams = intDecl.getMethodParams(method);
191                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
192                         print("public " + intDecl.getMethodType(method) + " " +
193                                 intDecl.getMethodId(method) + "(");
194                         for (int i = 0; i < methParams.size(); i++) {
195                                 // Check for params with driver class types and exchange it 
196                                 //              with its remote interface
197                                 String paramType = checkAndGetParamClass(methPrmTypes.get(i), false);
198                                 print(paramType + " " + methParams.get(i));
199                                 // Check if this is the last element (don't print a comma)
200                                 if (i != methParams.size() - 1) {
201                                         print(", ");
202                                 }
203                         }
204                         println(");");
205                 }
206         }
207
208
209         /**
210          * HELPER: writeMethodJavaInterface() writes the method of the interface
211          */
212         private void writeMethodJavaInterface(Collection<String> methods, InterfaceDecl intDecl) {
213
214                 for (String method : methods) {
215
216                         List<String> methParams = intDecl.getMethodParams(method);
217                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
218                         print("public " + intDecl.getMethodType(method) + " " +
219                                 intDecl.getMethodId(method) + "(");
220                         for (int i = 0; i < methParams.size(); i++) {
221                                 // Check for params with driver class types and exchange it 
222                                 //              with its remote interface
223                                 String paramType = methPrmTypes.get(i);
224                                 print(paramType + " " + methParams.get(i));
225                                 // Check if this is the last element (don't print a comma)
226                                 if (i != methParams.size() - 1) {
227                                         print(", ");
228                                 }
229                         }
230                         println(");");
231                 }
232         }
233
234
235         /**
236          * HELPER: writeEnumJava() writes the enumeration declaration
237          */
238         private void writeEnumJava(EnumDecl enumDecl) {
239
240                 Set<String> enumTypes = enumDecl.getEnumDeclarations();
241                 // Iterate over enum declarations
242                 for (String enType : enumTypes) {
243
244                         println("public enum " + enType + " {");
245                         List<String> enumMembers = enumDecl.getMembers(enType);
246                         for (int i = 0; i < enumMembers.size(); i++) {
247
248                                 String member = enumMembers.get(i);
249                                 print(member);
250                                 // Check if this is the last element (don't print a comma)
251                                 if (i != enumMembers.size() - 1)
252                                         println(",");
253                                 else
254                                         println("");
255                         }
256                         println("}\n");
257                 }
258         }
259
260
261         /**
262          * HELPER: writeStructJava() writes the struct declaration
263          */
264         private void writeStructJava(StructDecl structDecl) {
265
266                 List<String> structTypes = structDecl.getStructTypes();
267                 // Iterate over enum declarations
268                 for (String stType : structTypes) {
269
270                         println("public class " + stType + " {");
271                         List<String> structMemberTypes = structDecl.getMemberTypes(stType);
272                         List<String> structMembers = structDecl.getMembers(stType);
273                         for (int i = 0; i < structMembers.size(); i++) {
274
275                                 String memberType = structMemberTypes.get(i);
276                                 String member = structMembers.get(i);
277                                 println("public static " + memberType + " " + member + ";");
278                         }
279                         println("}\n");
280                 }
281         }
282
283
284         /**
285          * generateJavaLocalInterface() writes the local interface and provides type-checking.
286          * <p>
287          * It needs to rewrite and exchange USERDEFINED types in input parameters of stub
288          * and original interfaces, e.g. exchange Camera and CameraWithVideoAndRecording.
289          * The local interface has to be the input parameter for the stub and the stub 
290          * interface has to be the input parameter for the local class.
291          */
292         public void generateJavaLocalInterfaces() throws IOException {
293
294                 // Create a new directory
295                 createDirectory(dir);
296                 for (String intface : mapIntfacePTH.keySet()) {
297                         // Open a new file to write into
298                         FileWriter fw = new FileWriter(dir + "/" + intface + ".java");
299                         pw = new PrintWriter(new BufferedWriter(fw));
300                         // Pass in set of methods and get import classes
301                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
302                         InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
303                         List<String> methods = intDecl.getMethods();
304                         Set<String> importClasses = getImportClasses(methods, intDecl);
305                         printImportStatements(importClasses);
306                         // Write interface header
307                         println("");
308                         println("public interface " + intface + " {");
309                         // Write enum if any...
310                         EnumDecl enumDecl = (EnumDecl) decHandler.getEnumDecl(intface);
311                         writeEnumJava(enumDecl);
312                         // Write struct if any...
313                         StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
314                         writeStructJava(structDecl);
315                         // Write methods
316                         writeMethodJavaLocalInterface(methods, intDecl);
317                         println("}");
318                         pw.close();
319                         System.out.println("IoTCompiler: Generated local interface " + intface + ".java...");
320                 }
321         }
322
323
324         /**
325          * generateJavaInterfaces() generate stub interfaces based on the methods list in Java
326          */
327         public void generateJavaInterfaces() throws IOException {
328
329                 // Create a new directory
330                 String path = createDirectories(dir, subdir);
331                 for (String intface : mapIntfacePTH.keySet()) {
332
333                         Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
334                         for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
335
336                                 // Open a new file to write into
337                                 String newIntface = intMeth.getKey();
338                                 FileWriter fw = new FileWriter(path + "/" + newIntface + ".java");
339                                 pw = new PrintWriter(new BufferedWriter(fw));
340                                 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
341                                 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
342                                 // Pass in set of methods and get import classes
343                                 Set<String> importClasses = getImportClasses(intMeth.getValue(), intDecl);
344                                 printImportStatements(importClasses);
345                                 // Write interface header
346                                 println("");
347                                 println("public interface " + newIntface + " {\n");
348                                 // Write methods
349                                 writeMethodJavaInterface(intMeth.getValue(), intDecl);
350                                 println("}");
351                                 pw.close();
352                                 System.out.println("IoTCompiler: Generated interface " + newIntface + ".java...");
353                         }
354                 }
355         }
356
357
358         /**
359          * HELPER: writePropertiesJavaStub() writes the properties of the stub class
360          */
361         private void writePropertiesJavaStub(String intface, String newIntface, boolean callbackExist, Set<String> callbackClasses) {
362
363                 println("private IoTRMICall rmiCall;");
364                 println("private String address;");
365                 println("private int[] ports;\n");
366                 // Get the object Id
367                 Integer objId = mapIntfaceObjId.get(intface);
368                 println("private final static int objectId = " + objId + ";");
369                 mapNewIntfaceObjId.put(newIntface, objId);
370                 mapIntfaceObjId.put(intface, objId++);
371                 if (callbackExist) {
372                 // We assume that each class only has one callback interface for now
373                         Iterator it = callbackClasses.iterator();
374                         String callbackType = (String) it.next();
375                         println("// Callback properties");
376                         println("private IoTRMIObject rmiObj;");
377                         println("List<" + callbackType + "> listCallbackObj;");
378                         println("private static int objIdCnt = 0;");
379                 }
380                 println("\n");
381         }
382
383
384         /**
385          * HELPER: writeConstructorJavaStub() writes the constructor of the stub class
386          */
387         private void writeConstructorJavaStub(String intface, boolean callbackExist, Set<String> callbackClasses) {
388
389                 println("public " + intface + "(int _port, String _address, int _rev, int[] _ports) throws Exception {");
390                 println("address = _address;");
391                 println("ports = _ports;");
392                 println("rmiCall = new IoTRMICall(_port, _address, _rev);");
393                 if (callbackExist) {
394                         Iterator it = callbackClasses.iterator();
395                         String callbackType = (String) it.next();
396                         println("listCallbackObj = new ArrayList<" + callbackType + ">();");
397                         println("___initCallBack();");
398                 }
399                 println("}\n");
400         }
401
402
403         /**
404          * HELPER: writeConstructorJavaStub() writes the constructor of the stub class
405          */
406         private void writeInitCallbackJavaStub(String intface, InterfaceDecl intDecl) {
407
408                 println("public void ___initCallBack() {");
409                 // Generate main thread for callbacks
410                 println("Thread thread = new Thread() {");
411                 println("public void run() {");
412                 println("try {");
413                 println("rmiObj = new IoTRMIObject(ports[0]);");
414                 println("while (true) {");
415                 println("byte[] method = rmiObj.getMethodBytes();");
416                 println("int objId = IoTRMIObject.getObjectId(method);");
417                 println(intface + "_CallbackSkeleton skel = (" + intface + "_CallbackSkeleton) listCallbackObj.get(objId);");
418                 println("if (skel != null) {");
419                 println("skel.invokeMethod(rmiObj);");
420                 println("} else {");
421                 println("throw new Error(\"" + intface + ": Object with Id \" + objId + \" not found!\");");
422                 println("}");
423                 println("}");
424                 println("} catch (Exception ex) {");
425                 println("ex.printStackTrace();");
426                 println("throw new Error(\"Error instantiating class " + intface + "_CallbackSkeleton!\");");
427                 println("}");
428                 println("}");
429                 println("};");
430                 println("thread.start();\n");
431                 // Generate info sending part
432                 String method = "___initCallBack()";
433                 println("int methodId = " + intDecl.getHelperMethodNumId(method) + ";");
434                 println("Class<?> retType = void.class;");
435                 println("Class<?>[] paramCls = new Class<?>[] { int.class, String.class, int.class };");
436                 println("Object[] paramObj = new Object[] { ports[0], address, 0 };");
437                 println("rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
438                 println("}\n");
439         }
440
441
442         /**
443          * HELPER: writeStdMethodBodyJavaStub() writes the standard method body in the stub class
444          */
445         private void writeStdMethodBodyJavaStub(InterfaceDecl intDecl, List<String> methParams,
446                         List<String> methPrmTypes, String method) {
447
448                 println("int methodId = " + intDecl.getMethodNumId(method) + ";");
449                 String retType = intDecl.getMethodType(method);
450                 println("Class<?> retType = " + getSimpleType(retType) + ".class;");
451                 // Generate array of parameter types
452                 print("Class<?>[] paramCls = new Class<?>[] { ");
453                 for (int i = 0; i < methParams.size(); i++) {
454                         String paramType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
455                         print(getSimpleType(paramType) + ".class");
456                         // Check if this is the last element (don't print a comma)
457                         if (i != methParams.size() - 1) {
458                                 print(", ");
459                         }
460                 }
461                 println(" };");
462                 // Generate array of parameter objects
463                 print("Object[] paramObj = new Object[] { ");
464                 for (int i = 0; i < methParams.size(); i++) {
465                         print(getSimpleIdentifier(methParams.get(i)));
466                         // Check if this is the last element (don't print a comma)
467                         if (i != methParams.size() - 1) {
468                                 print(", ");
469                         }
470                 }
471                 println(" };");
472                 // Check if this is "void"
473                 if (retType.equals("void")) {
474                         println("rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
475                 } else { // We do have a return value
476                 // Check if the return value NONPRIMITIVES
477                         if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES) {
478                                 String[] retGenValType = getTypeOfGeneric(retType);
479                                 println("Class<?> retGenValType = " + retGenValType[0] + ".class;");
480                                 println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, retGenValType, paramCls, paramObj);");
481                                 println("return (" + retType + ")retObj;");
482                         } else {
483                                 println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
484                                 println("return (" + retType + ")retObj;");
485                         }
486                 }
487         }
488
489
490         /**
491          * HELPER: checkCallbackType() checks the callback type
492          */
493         private boolean checkCallbackType(String paramType, String callbackType) {
494
495                 if (getParamCategory(paramType) == ParamCategory.NONPRIMITIVES)
496                         paramType = getTypeOfGeneric(paramType)[0];
497                 return callbackType.equals(paramType);
498         }
499
500
501         /**
502          * HELPER: writeCallbackMethodBodyJavaStub() writes the callback method of the stub class
503          */
504         private void writeCallbackMethodBodyJavaStub(InterfaceDecl intDecl, List<String> methParams,
505                         List<String> methPrmTypes, String method, String callbackType) {
506
507                 println("try {");
508                 // Check if this is single object, array, or list of objects
509                 for (int i = 0; i < methParams.size(); i++) {
510
511                         String paramType = methPrmTypes.get(i);
512                         if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
513                                 String param = methParams.get(i);
514                                 if (isArrayOrList(paramType, param)) {  // Generate loop
515                                         println("for (" + paramType + " cb : " + getSimpleIdentifier(param) + ") {");
516                                         println(callbackType + "_CallbackSkeleton skel = new " + callbackType + "_CallbackSkeleton(cb, objIdCnt++);");
517                                 } else
518                                         println(callbackType + "_CallbackSkeleton skel = new " + callbackType + "_CallbackSkeleton(" +
519                                                 getSimpleIdentifier(param) + ", objIdCnt++);");
520                                 println("listCallbackObj.add(skel);");
521                                 if (isArrayOrList(paramType, param))
522                                         println("}");
523                         }
524                 }
525                 println("} catch (Exception ex) {");
526                 println("ex.printStackTrace();");
527                 println("throw new Error(\"Exception when generating skeleton objects!\");");
528                 println("}\n");
529                 println("int methodId = " + intDecl.getMethodNumId(method) + ";");
530                 String retType = intDecl.getMethodType(method);
531                 println("Class<?> retType = " + getSimpleType(retType) + ".class;");
532                 // Generate array of parameter types
533                 print("Class<?>[] paramCls = new Class<?>[] { ");
534                 for (int i = 0; i < methParams.size(); i++) {
535                         String paramType = methPrmTypes.get(i);
536                         if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
537                                 print("int.class");
538                         } else { // Generate normal classes if it's not a callback object
539                                 String prmType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
540                                 print(getSimpleType(prmType) + ".class");
541                         }
542                         if (i != methParams.size() - 1) // Check if this is the last element
543                                 print(", ");
544                 }
545                 println(" };");
546                 // Generate array of parameter objects
547                 print("Object[] paramObj = new Object[] { ");
548                 for (int i = 0; i < methParams.size(); i++) {
549                         String paramType = methPrmTypes.get(i);
550                         if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
551                                 if (isArray(methPrmTypes.get(i), methParams.get(i)))
552                                         print(getSimpleIdentifier(methParams.get(i)) + ".length");
553                                 else if (isList(methPrmTypes.get(i), methParams.get(i)))
554                                         print(getSimpleIdentifier(methParams.get(i)) + ".size()");
555                                 else
556                                         print("new Integer(1)");
557                         } else
558                                 print(getSimpleIdentifier(methParams.get(i)));
559                         if (i != methParams.size() - 1)
560                                 print(", ");
561                 }
562                 println(" };");
563                 // Check if this is "void"
564                 if (retType.equals("void")) {
565                         println("rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
566                 } else { // We do have a return value
567                 // Check if the return value NONPRIMITIVES
568                         if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES) {
569                                 String[] retGenValType = getTypeOfGeneric(retType);
570                                 println("Class<?> retGenValType = " + retGenValType[0] + ".class;");
571                                 println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, retGenValType, paramCls, paramObj);");
572                                 println("return (" + retType + ")retObj;");
573                         } else {
574                                 println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
575                                 println("return (" + retType + ")retObj;");
576                         }
577                 }
578         }
579
580
581         /**
582          * HELPER: writeMethodJavaStub() writes the method of the stub class
583          */
584         private void writeMethodJavaStub(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
585
586                 for (String method : methods) {
587
588                         List<String> methParams = intDecl.getMethodParams(method);
589                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
590                         print("public " + intDecl.getMethodType(method) + " " +
591                                 intDecl.getMethodId(method) + "(");
592                         boolean isCallbackMethod = false;
593                         String callbackType = null;
594                         for (int i = 0; i < methParams.size(); i++) {
595
596                                 String paramType = methPrmTypes.get(i);
597                                 if (getParamCategory(paramType) == ParamCategory.NONPRIMITIVES)
598                                         paramType = getTypeOfGeneric(paramType)[0];
599                                 // Check if this has callback object
600                                 if (callbackClasses != null) {
601                                         if (callbackClasses.contains(paramType)) {
602                                                 isCallbackMethod = true;
603                                                 callbackType = paramType;       
604                                                 // Even if there're 2 callback arguments, we expect them to be of the same interface
605                                         }
606                                 }
607                                 print(methPrmTypes.get(i) + " " + methParams.get(i));
608                                 // Check if this is the last element (don't print a comma)
609                                 if (i != methParams.size() - 1) {
610                                         print(", ");
611                                 }
612                         }
613                         println(") {");
614                         // Now, write the body of stub!
615                         if (isCallbackMethod)
616                                 writeCallbackMethodBodyJavaStub(intDecl, methParams, methPrmTypes, method, callbackType);
617                         else
618                                 writeStdMethodBodyJavaStub(intDecl, methParams, methPrmTypes, method);
619                         println("}\n");
620                         // Write the init callback helper method
621                         if (isCallbackMethod)
622                                 writeInitCallbackJavaStub(callbackType, intDecl);
623                 }
624         }
625
626
627         /**
628          * generateJavaStubClasses() generate stubs based on the methods list in Java
629          */
630         public void generateJavaStubClasses() throws IOException {
631
632                 // Create a new directory
633                 String path = createDirectories(dir, subdir);
634                 for (String intface : mapIntfacePTH.keySet()) {
635
636                         Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
637                         for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
638
639                                 // Open a new file to write into
640                                 String newIntface = intMeth.getKey();
641                                 String newStubClass = newIntface + "_Stub";
642                                 FileWriter fw = new FileWriter(path + "/" + newStubClass + ".java");
643                                 pw = new PrintWriter(new BufferedWriter(fw));
644                                 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
645                                 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
646                                 // Pass in set of methods and get import classes
647                                 Set<String> methods = intMeth.getValue();
648                                 Set<String> importClasses = getImportClasses(methods, intDecl);
649                                 List<String> stdImportClasses = getStandardJavaImportClasses();
650                                 List<String> allImportClasses = getAllImportClasses(stdImportClasses, importClasses);
651                                 printImportStatements(allImportClasses); println("");
652                                 // Find out if there are callback objects
653                                 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
654                                 boolean callbackExist = !callbackClasses.isEmpty();
655                                 // Write class header
656                                 println("public class " + newStubClass + " implements " + newIntface + " {\n");
657                                 // Write properties
658                                 writePropertiesJavaStub(intface, newIntface, callbackExist, callbackClasses);
659                                 // Write constructor
660                                 writeConstructorJavaStub(newStubClass, callbackExist, callbackClasses);
661                                 // Write methods
662                                 writeMethodJavaStub(intMeth.getValue(), intDecl, callbackClasses);
663                                 println("}");
664                                 pw.close();
665                                 System.out.println("IoTCompiler: Generated stub class " + newStubClass + ".java...");
666                         }
667                 }
668         }
669
670
671         /**
672          * HELPER: writePropertiesJavaCallbackStub() writes the properties of the callback stub class
673          */
674         private void writePropertiesJavaCallbackStub(String intface, String newIntface, boolean callbackExist, Set<String> callbackClasses) {
675
676                 println("private IoTRMICall rmiCall;");
677                 println("private String address;");
678                 println("private int[] ports;\n");
679                 // Get the object Id
680                 println("private static int objectId = 0;");
681                 if (callbackExist) {
682                 // We assume that each class only has one callback interface for now
683                         Iterator it = callbackClasses.iterator();
684                         String callbackType = (String) it.next();
685                         println("// Callback properties");
686                         println("private IoTRMIObject rmiObj;");
687                         println("List<" + callbackType + "> listCallbackObj;");
688                         println("private static int objIdCnt = 0;");
689                 }
690                 println("\n");
691         }
692
693
694         /**
695          * HELPER: writeConstructorJavaCallbackStub() writes the constructor of the callback stub class
696          */
697         private void writeConstructorJavaCallbackStub(String intface, boolean callbackExist, Set<String> callbackClasses) {
698
699                 // TODO: If we want callback in callback, then we need to add address and port initializations
700                 println("public " + intface + "(IoTRMICall _rmiCall, int _objectId) throws Exception {");
701                 println("objectId = _objectId;");
702                 println("rmiCall = _rmiCall;");
703                 if (callbackExist) {
704                         Iterator it = callbackClasses.iterator();
705                         String callbackType = (String) it.next();
706                         println("listCallbackObj = new ArrayList<" + callbackType + ">();");
707                         println("___initCallBack();");
708                         println("// TODO: Add address and port initialization here if we want callback in callback!");
709                 }
710                 println("}\n");
711         }
712
713
714         /**
715          * generateJavaCallbackStubClasses() generate callback stubs based on the methods list in Java
716          * <p>
717          * Callback stubs gets the IoTRMICall objects from outside of the class as contructor input
718          * because all these stubs are populated by the class that takes in this object as a callback
719          * object. In such a class, we only use one socket, hence one IoTRMICall, for all callback objects.
720          */
721         public void generateJavaCallbackStubClasses() throws IOException {
722
723                 // Create a new directory
724                 String path = createDirectories(dir, subdir);
725                 for (String intface : mapIntfacePTH.keySet()) {
726
727                         Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
728                         for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
729
730                                 // Open a new file to write into
731                                 String newIntface = intMeth.getKey();
732                                 String newStubClass = newIntface + "_CallbackStub";
733                                 FileWriter fw = new FileWriter(path + "/" + newStubClass + ".java");
734                                 pw = new PrintWriter(new BufferedWriter(fw));
735                                 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
736                                 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
737                                 // Pass in set of methods and get import classes
738                                 Set<String> methods = intMeth.getValue();
739                                 Set<String> importClasses = getImportClasses(methods, intDecl);
740                                 List<String> stdImportClasses = getStandardJavaImportClasses();
741                                 List<String> allImportClasses = getAllImportClasses(stdImportClasses, importClasses);
742                                 printImportStatements(allImportClasses); println("");
743                                 // Find out if there are callback objects
744                                 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
745                                 boolean callbackExist = !callbackClasses.isEmpty();
746                                 // Write class header
747                                 println("public class " + newStubClass + " implements " + newIntface + " {\n");
748                                 // Write properties
749                                 writePropertiesJavaCallbackStub(intface, newIntface, callbackExist, callbackClasses);
750                                 // Write constructor
751                                 writeConstructorJavaCallbackStub(newStubClass, callbackExist, callbackClasses);
752                                 // Write methods
753                                 // TODO: perhaps need to generate callback for callback
754                                 writeMethodJavaStub(intMeth.getValue(), intDecl, callbackClasses);
755                                 println("}");
756                                 pw.close();
757                                 System.out.println("IoTCompiler: Generated callback stub class " + newStubClass + ".java...");
758                         }
759                 }
760         }
761
762
763         /**
764          * HELPER: writePropertiesJavaSkeleton() writes the properties of the skeleton class
765          */
766         private void writePropertiesJavaSkeleton(String intface, boolean callbackExist) {
767
768                 println("private " + intface + " mainObj;");
769                 //println("private int ports;");
770                 println("private IoTRMIObject rmiObj;\n");
771                 // Callback
772                 if (callbackExist) {
773                         println("private static int objIdCnt = 0;");
774                         println("private IoTRMICall rmiCall;");
775                 }
776                 // Keep track of object Ids of all stubs registered to this interface
777                 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
778                 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
779                         String newIntface = intMeth.getKey();
780                         int newObjectId = mapNewIntfaceObjId.get(newIntface);
781                         println("private final static int object" + newObjectId + "Id = " + 
782                                 newObjectId + ";\t//" + newIntface);
783                 }
784                 println("\n");
785         }
786
787
788         /**
789          * HELPER: writeConstructorJavaSkeleton() writes the constructor of the skeleton class
790          */
791         private void writeConstructorJavaSkeleton(String newSkelClass, String intface) {
792
793                 println("public " + newSkelClass + "(" + intface + " _mainObj, int _port) throws Exception {");
794                 println("mainObj = _mainObj;");
795                 println("rmiObj = new IoTRMIObject(_port);");
796                 //println("set0Allowed = Arrays.asList(object0Permission);");
797                 println("___waitRequestInvokeMethod();");
798                 println("}\n");
799         }
800
801
802         /**
803          * HELPER: writeStdMethodBodyJavaSkeleton() writes the standard method body in the skeleton class
804          */
805         private void writeStdMethodBodyJavaSkeleton(List<String> methParams, String methodId, String methodType) {
806
807                 if (methodType.equals("void"))
808                         print("mainObj." + methodId + "(");
809                 else
810                         print("return mainObj." + methodId + "(");
811                 for (int i = 0; i < methParams.size(); i++) {
812
813                         print(getSimpleIdentifier(methParams.get(i)));
814                         // Check if this is the last element (don't print a comma)
815                         if (i != methParams.size() - 1) {
816                                 print(", ");
817                         }
818                 }
819                 println(");");
820         }
821
822
823         /**
824          * HELPER: writeInitCallbackJavaSkeleton() writes the init callback method for skeleton class
825          */
826         private void writeInitCallbackJavaSkeleton(boolean callbackSkeleton) {
827
828                 // This is a callback skeleton generation
829                 if (callbackSkeleton)
830                         println("public void ___regCB(IoTRMIObject rmiObj) throws IOException {");
831                 else
832                         println("public void ___regCB() throws IOException {");
833                 println("Object[] paramObj = rmiObj.getMethodParams(new Class<?>[] { int.class, String.class, int.class },");
834                 println("\tnew Class<?>[] { null, null, null });");
835                 println("rmiCall = new IoTRMICall((int) paramObj[0], (String) paramObj[1], (int) paramObj[2]);");
836                 println("}\n");
837         }
838
839
840         /**
841          * HELPER: writeMethodJavaSkeleton() writes the method of the skeleton class
842          */
843         private void writeMethodJavaSkeleton(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses, 
844                         boolean callbackSkeleton) {
845
846                 for (String method : methods) {
847
848                         List<String> methParams = intDecl.getMethodParams(method);
849                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
850                         String methodId = intDecl.getMethodId(method);
851                         print("public " + intDecl.getMethodType(method) + " " + methodId + "(");
852                         boolean isCallbackMethod = false;
853                         String callbackType = null;
854                         for (int i = 0; i < methParams.size(); i++) {
855
856                                 String origParamType = methPrmTypes.get(i);
857                                 String paramType = checkAndGetParamClass(origParamType, false);
858                                 if (callbackClasses != null) {  // Check if this has callback object
859                                         if (callbackClasses.contains(origParamType)) {
860                                                 isCallbackMethod = true;
861                                                 callbackType = origParamType;   
862                                         }
863                                 }
864                                 print(paramType + " " + methParams.get(i));
865                                 // Check if this is the last element (don't print a comma)
866                                 if (i != methParams.size() - 1) {
867                                         print(", ");
868                                 }
869                         }
870                         println(") {");
871                         // Now, write the body of skeleton!
872                         writeStdMethodBodyJavaSkeleton(methParams, methodId, intDecl.getMethodType(method));
873                         println("}\n");
874                         if (isCallbackMethod)
875                                 writeInitCallbackJavaSkeleton(callbackSkeleton);
876                 }
877         }
878
879
880         /**
881          * HELPER: writeCallbackStubGeneration() writes the callback stub generation part
882          */
883         private Map<Integer,String> writeCallbackStubGeneration(List<String> methParams, List<String> methPrmTypes, String callbackType) {
884
885                 Map<Integer,String> mapStubParam = new HashMap<Integer,String>();
886                 // Iterate over callback objects
887                 for (int i = 0; i < methParams.size(); i++) {
888                         String paramType = methPrmTypes.get(i);
889                         String param = methParams.get(i);
890                         //if (callbackType.equals(paramType)) {
891                         if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
892                                 println("try {");
893                                 String exchParamType = checkAndGetParamClass(paramType, false);
894                                 // Print array if this is array or list if this is a list of callback objects
895                                 if (isArray(paramType, param)) {
896                                         println("int numStubs" + i + " = (int) paramObj[" + i + "];");
897                                         println(exchParamType + "[] stub" + i + " = new " + exchParamType + "[numStubs" + i + "];");
898                                 } else if (isList(paramType, param)) {
899                                         println("int numStubs" + i + " = (int) paramObj[" + i + "];");
900                                         println("List<" + exchParamType + "> stub" + i + " = new ArrayList<" + exchParamType + ">();");
901                                 } else {
902                                         println(exchParamType + " stub" + i + " = new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt);");
903                                         println("objIdCnt++;");
904                                 }
905                         }
906                         // Generate a loop if needed
907                         if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
908                                 String exchParamType = checkAndGetParamClass(paramType, false);
909                                 if (isArray(paramType, param)) {
910                                         println("for (int objId = 0; objId < numStubs" + i + "; objId++) {");
911                                         println("stub" + i + "[objId] = new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt);");
912                                         println("objIdCnt++;");
913                                         println("}");
914                                 } else if (isList(paramType, param)) {
915                                         println("for (int objId = 0; objId < numStubs" + i + "; objId++) {");
916                                         println("stub" + i + ".add(new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt));");
917                                         println("objIdCnt++;");
918                                         println("}");
919                                 }
920                         }
921                         mapStubParam.put(i, "stub" + i);        // List of all stub parameters
922                 }
923                 return mapStubParam;
924         }
925
926
927         /**
928          * HELPER: writeStdMethodHelperBodyJavaSkeleton() writes the standard method body helper in the skeleton class
929          */
930         private void writeStdMethodHelperBodyJavaSkeleton(InterfaceDecl intDecl, List<String> methParams,
931                         List<String> methPrmTypes, String method, Set<String> callbackClasses) {
932                 // Generate array of parameter objects
933                 boolean isCallbackMethod = false;
934                 String callbackType = null;
935                 print("Object[] paramObj = rmiObj.getMethodParams(new Class<?>[] { ");
936                 for (int i = 0; i < methParams.size(); i++) {
937                         String paramType = methPrmTypes.get(i);
938                         if (getParamCategory(paramType) == ParamCategory.NONPRIMITIVES)
939                                 paramType = getTypeOfGeneric(paramType)[0];
940                         if (callbackClasses != null) {
941                                 if (callbackClasses.contains(paramType)) {
942                                         isCallbackMethod = true;
943                                         callbackType = paramType;
944                                         print("int.class");
945                                 } else {
946                                         String prmType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
947                                         print(getSimpleType(prmType) + ".class");
948                                 }
949                         } else { // Generate normal classes if it's not a callback object
950                                 String prmType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
951                                 print(getSimpleType(prmType) + ".class");
952                         }
953                         if (i != methParams.size() - 1)
954                                 print(", ");
955                 }
956                 println(" }, ");
957                 // Generate generic class if it's a generic type.. null otherwise
958                 print("new Class<?>[] { ");
959                 for (int i = 0; i < methParams.size(); i++) {
960                         String prmType = methPrmTypes.get(i);
961                         if (getParamCategory(prmType) == ParamCategory.NONPRIMITIVES)
962                                 print(getTypeOfGeneric(prmType)[0] + ".class");
963                         else
964                                 print("null");
965                         if (i != methParams.size() - 1)
966                                 print(", ");
967                 }
968                 println(" });");
969                 Map<Integer,String> mapStubParam = null;
970                 if (isCallbackMethod)
971                         mapStubParam = writeCallbackStubGeneration(methParams, methPrmTypes, callbackType);
972                 // Check if this is "void"
973                 String retType = intDecl.getMethodType(method);
974                 if (retType.equals("void")) {
975                         print(intDecl.getMethodId(method) + "(");
976                 } else { // We do have a return value
977                         print("Object retObj = " + intDecl.getMethodId(method) + "(");
978                 }
979                 for (int i = 0; i < methParams.size(); i++) {
980
981                         if (isCallbackMethod) {
982                                 print(mapStubParam.get(i));     // Get the callback parameter
983                         } else {
984                                 String prmType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
985                                 print("(" + prmType + ") paramObj[" + i + "]");
986                         }
987                         if (i != methParams.size() - 1)
988                                 print(", ");
989                 }
990                 println(");");
991                 if (!retType.equals("void"))
992                         println("rmiObj.sendReturnObj(retObj);");
993                 if (isCallbackMethod) { // Catch exception if this is callback
994                         println("} catch(Exception ex) {");
995                         println("ex.printStackTrace();");
996                         println("throw new Error(\"Exception from callback object instantiation!\");");
997                         println("}");
998                 }
999         }
1000
1001
1002         /**
1003          * HELPER: writeMethodHelperJavaSkeleton() writes the method helper of the skeleton class
1004          */
1005         private void writeMethodHelperJavaSkeleton(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
1006
1007                 // Use this set to handle two same methodIds
1008                 Set<String> uniqueMethodIds = new HashSet<String>();
1009                 for (String method : methods) {
1010
1011                         List<String> methParams = intDecl.getMethodParams(method);
1012                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1013                         String methodId = intDecl.getMethodId(method);
1014                         print("public void ___");
1015                         String helperMethod = methodId;
1016                         if (uniqueMethodIds.contains(methodId))
1017                                 helperMethod = helperMethod + intDecl.getMethodNumId(method);
1018                         else
1019                                 uniqueMethodIds.add(methodId);
1020                         // Check if this is "void"
1021                         String retType = intDecl.getMethodType(method);
1022                         if (retType.equals("void"))
1023                                 println(helperMethod + "() {");
1024                         else
1025                                 println(helperMethod + "() throws IOException {");
1026                         // Now, write the helper body of skeleton!
1027                         writeStdMethodHelperBodyJavaSkeleton(intDecl, methParams, methPrmTypes, method, callbackClasses);
1028                         println("}\n");
1029                 }
1030         }
1031
1032
1033         /**
1034          * HELPER: writeJavaWaitRequestInvokeMethod() writes the main loop of the skeleton class
1035          */
1036         private void writeJavaWaitRequestInvokeMethod(Collection<String> methods, InterfaceDecl intDecl, boolean callbackExist) {
1037
1038                 // Use this set to handle two same methodIds
1039                 Set<String> uniqueMethodIds = new HashSet<String>();
1040                 println("private void ___waitRequestInvokeMethod() throws IOException {");
1041                 // Write variables here if we have callbacks or enums or structs
1042                 println("while (true) {");
1043                 println("rmiObj.getMethodBytes();");
1044                 println("int _objectId = rmiObj.getObjectId();");
1045                 println("int methodId = rmiObj.getMethodId();");
1046                 // TODO: code the permission check here!
1047                 println("switch (methodId) {");
1048                 // Print methods and method Ids
1049                 for (String method : methods) {
1050                         String methodId = intDecl.getMethodId(method);
1051                         int methodNumId = intDecl.getMethodNumId(method);
1052                         print("case " + methodNumId + ": ___");
1053                         String helperMethod = methodId;
1054                         if (uniqueMethodIds.contains(methodId))
1055                                 helperMethod = helperMethod + methodNumId;
1056                         else
1057                                 uniqueMethodIds.add(methodId);
1058                         println(helperMethod + "(); break;");
1059                 }
1060                 String method = "___initCallBack()";
1061                 // Print case -9999 (callback handler) if callback exists
1062                 if (callbackExist) {
1063                         int methodId = intDecl.getHelperMethodNumId(method);
1064                         println("case " + methodId + ": ___regCB(); break;");
1065                 }
1066                 println("default: ");
1067                 println("throw new Error(\"Method Id \" + methodId + \" not recognized!\");");
1068                 println("}");
1069                 println("}");
1070                 println("}\n");
1071         }
1072
1073
1074         /**
1075          * generateJavaSkeletonClass() generate skeletons based on the methods list in Java
1076          */
1077         public void generateJavaSkeletonClass() throws IOException {
1078
1079                 // Create a new directory
1080                 String path = createDirectories(dir, subdir);
1081                 for (String intface : mapIntfacePTH.keySet()) {
1082                         // Open a new file to write into
1083                         String newSkelClass = intface + "_Skeleton";
1084                         FileWriter fw = new FileWriter(path + "/" + newSkelClass + ".java");
1085                         pw = new PrintWriter(new BufferedWriter(fw));
1086                         // Pass in set of methods and get import classes
1087                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
1088                         InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
1089                         List<String> methods = intDecl.getMethods();
1090                         Set<String> importClasses = getImportClasses(methods, intDecl);
1091                         List<String> stdImportClasses = getStandardJavaImportClasses();
1092                         List<String> allImportClasses = getAllImportClasses(stdImportClasses, importClasses);
1093                         printImportStatements(allImportClasses);
1094                         // Find out if there are callback objects
1095                         Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
1096                         boolean callbackExist = !callbackClasses.isEmpty();
1097                         // Write class header
1098                         println("");
1099                         println("public class " + newSkelClass  + " implements " + intface + " {\n");
1100                         // Write properties
1101                         writePropertiesJavaSkeleton(intface, callbackExist);
1102                         // Write constructor
1103                         writeConstructorJavaSkeleton(newSkelClass, intface);
1104                         // Write methods
1105                         writeMethodJavaSkeleton(methods, intDecl, callbackClasses, false);
1106                         // Write method helper
1107                         writeMethodHelperJavaSkeleton(methods, intDecl, callbackClasses);
1108                         // Write waitRequestInvokeMethod() - main loop
1109                         writeJavaWaitRequestInvokeMethod(methods, intDecl, callbackExist);
1110                         println("}");
1111                         pw.close();
1112                         System.out.println("IoTCompiler: Generated skeleton class " + newSkelClass + ".java...");
1113                 }
1114         }
1115
1116
1117         /**
1118          * HELPER: writePropertiesJavaCallbackSkeleton() writes the properties of the callback skeleton class
1119          */
1120         private void writePropertiesJavaCallbackSkeleton(String intface, boolean callbackExist) {
1121
1122                 println("private " + intface + " mainObj;");
1123                 // For callback skeletons, this is its own object Id
1124                 println("private static int objectId = 0;");
1125                 // Callback
1126                 if (callbackExist) {
1127                         println("private static int objIdCnt = 0;");
1128                         println("private IoTRMICall rmiCall;");
1129                 }
1130                 println("\n");
1131         }
1132
1133
1134         /**
1135          * HELPER: writeConstructorJavaCallbackSkeleton() writes the constructor of the skeleton class
1136          */
1137         private void writeConstructorJavaCallbackSkeleton(String newSkelClass, String intface) {
1138
1139                 println("public " + newSkelClass + "(" + intface + " _mainObj, int _objectId) throws Exception {");
1140                 println("mainObj = _mainObj;");
1141                 println("objectId = _objectId;");
1142                 println("}\n");
1143         }
1144
1145
1146         /**
1147          * HELPER: writeMethodHelperJavaCallbackSkeleton() writes the method helper of the callback skeleton class
1148          */
1149         private void writeMethodHelperJavaCallbackSkeleton(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
1150
1151                 // Use this set to handle two same methodIds
1152                 Set<String> uniqueMethodIds = new HashSet<String>();
1153                 for (String method : methods) {
1154
1155                         List<String> methParams = intDecl.getMethodParams(method);
1156                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1157                         String methodId = intDecl.getMethodId(method);
1158                         print("public void ___");
1159                         String helperMethod = methodId;
1160                         if (uniqueMethodIds.contains(methodId))
1161                                 helperMethod = helperMethod + intDecl.getMethodNumId(method);
1162                         else
1163                                 uniqueMethodIds.add(methodId);
1164                         // Check if this is "void"
1165                         String retType = intDecl.getMethodType(method);
1166                         if (retType.equals("void"))
1167                                 println(helperMethod + "(IoTRMIObject rmiObj) {");
1168                         else
1169                                 println(helperMethod + "(IoTRMIObject rmiObj) throws IOException {");
1170                         // Now, write the helper body of skeleton!
1171                         writeStdMethodHelperBodyJavaSkeleton(intDecl, methParams, methPrmTypes, method, callbackClasses);
1172                         println("}\n");
1173                 }
1174         }
1175
1176
1177         /**
1178          * HELPER: writeJavaCallbackWaitRequestInvokeMethod() writes the main loop of the skeleton class
1179          */
1180         private void writeJavaCallbackWaitRequestInvokeMethod(Collection<String> methods, InterfaceDecl intDecl, boolean callbackExist) {
1181
1182                 // Use this set to handle two same methodIds
1183                 Set<String> uniqueMethodIds = new HashSet<String>();
1184                 println("public void invokeMethod(IoTRMIObject rmiObj) throws IOException {");
1185                 // Write variables here if we have callbacks or enums or structs
1186                 println("int methodId = rmiObj.getMethodId();");
1187                 // TODO: code the permission check here!
1188                 println("switch (methodId) {");
1189                 // Print methods and method Ids
1190                 for (String method : methods) {
1191                         String methodId = intDecl.getMethodId(method);
1192                         int methodNumId = intDecl.getMethodNumId(method);
1193                         print("case " + methodNumId + ": ___");
1194                         String helperMethod = methodId;
1195                         if (uniqueMethodIds.contains(methodId))
1196                                 helperMethod = helperMethod + methodNumId;
1197                         else
1198                                 uniqueMethodIds.add(methodId);
1199                         println(helperMethod + "(rmiObj); break;");
1200                 }
1201                 String method = "___initCallBack()";
1202                 // Print case -9999 (callback handler) if callback exists
1203                 if (callbackExist) {
1204                         int methodId = intDecl.getHelperMethodNumId(method);
1205                         println("case " + methodId + ": ___regCB(rmiObj); break;");
1206                 }
1207                 println("default: ");
1208                 println("throw new Error(\"Method Id \" + methodId + \" not recognized!\");");
1209                 println("}");
1210                 println("}\n");
1211         }
1212
1213
1214         /**
1215          * generateJavaCallbackSkeletonClass() generate callback skeletons based on the methods list in Java
1216          */
1217         public void generateJavaCallbackSkeletonClass() throws IOException {
1218
1219                 // Create a new directory
1220                 String path = createDirectories(dir, subdir);
1221                 for (String intface : mapIntfacePTH.keySet()) {
1222                         // Open a new file to write into
1223                         String newSkelClass = intface + "_CallbackSkeleton";
1224                         FileWriter fw = new FileWriter(path + "/" + newSkelClass + ".java");
1225                         pw = new PrintWriter(new BufferedWriter(fw));
1226                         // Pass in set of methods and get import classes
1227                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
1228                         InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
1229                         List<String> methods = intDecl.getMethods();
1230                         Set<String> importClasses = getImportClasses(methods, intDecl);
1231                         List<String> stdImportClasses = getStandardJavaImportClasses();
1232                         List<String> allImportClasses = getAllImportClasses(stdImportClasses, importClasses);
1233                         printImportStatements(allImportClasses);
1234                         // Find out if there are callback objects
1235                         Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
1236                         boolean callbackExist = !callbackClasses.isEmpty();
1237                         // Write class header
1238                         println("");
1239                         println("public class " + newSkelClass  + " implements " + intface + " {\n");
1240                         // Write properties
1241                         writePropertiesJavaCallbackSkeleton(intface, callbackExist);
1242                         // Write constructor
1243                         writeConstructorJavaCallbackSkeleton(newSkelClass, intface);
1244                         // Write methods
1245                         writeMethodJavaSkeleton(methods, intDecl, callbackClasses, true);
1246                         // Write method helper
1247                         writeMethodHelperJavaCallbackSkeleton(methods, intDecl, callbackClasses);
1248                         // Write waitRequestInvokeMethod() - main loop
1249                         writeJavaCallbackWaitRequestInvokeMethod(methods, intDecl, callbackExist);
1250                         println("}");
1251                         pw.close();
1252                         System.out.println("IoTCompiler: Generated callback skeleton class " + newSkelClass + ".java...");
1253                 }
1254         }
1255
1256
1257         /**
1258          * HELPER: writeMethodCplusInterface() writes the method of the interface
1259          */
1260         private void writeMethodCplusInterface(Collection<String> methods, InterfaceDecl intDecl) {
1261
1262                 for (String method : methods) {
1263
1264                         List<String> methParams = intDecl.getMethodParams(method);
1265                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1266                         print("virtual " + checkAndGetCplusType(intDecl.getMethodType(method)) + " " +
1267                                 intDecl.getMethodId(method) + "(");
1268                         for (int i = 0; i < methParams.size(); i++) {
1269                                 // Check for params with driver class types and exchange it 
1270                                 //              with its remote interface
1271                                 //String paramType = checkAndGetParamClass(methPrmTypes.get(i), true);
1272                                 String paramType = methPrmTypes.get(i);
1273                                 paramType = checkAndGetCplusType(paramType);
1274                                 // Check for arrays - translate into vector in C++
1275                                 String paramComplete = checkAndGetCplusArray(paramType, methParams.get(i));
1276                                 print(paramComplete);
1277                                 // Check if this is the last element (don't print a comma)
1278                                 if (i != methParams.size() - 1) {
1279                                         print(", ");
1280                                 }
1281                         }
1282                         println(") = 0;");
1283                 }
1284         }
1285
1286
1287         /**
1288          * HELPER: writeEnumCplus() writes the enumeration declaration
1289          */
1290         private void writeEnumCplus(EnumDecl enumDecl) {
1291
1292                 Set<String> enumTypes = enumDecl.getEnumDeclarations();
1293                 // Iterate over enum declarations
1294                 for (String enType : enumTypes) {
1295
1296                         println("enum " + enType + " {");
1297                         List<String> enumMembers = enumDecl.getMembers(enType);
1298                         for (int i = 0; i < enumMembers.size(); i++) {
1299
1300                                 String member = enumMembers.get(i);
1301                                 print(member);
1302                                 // Check if this is the last element (don't print a comma)
1303                                 if (i != enumMembers.size() - 1)
1304                                         println(",");
1305                                 else
1306                                         println("");
1307                         }
1308                         println("};\n");
1309                 }
1310         }
1311
1312
1313         /**
1314          * HELPER: writeStructCplus() writes the struct declaration
1315          */
1316         private void writeStructCplus(StructDecl structDecl) {
1317
1318                 List<String> structTypes = structDecl.getStructTypes();
1319                 // Iterate over enum declarations
1320                 for (String stType : structTypes) {
1321
1322                         println("struct " + stType + " {");
1323                         List<String> structMemberTypes = structDecl.getMemberTypes(stType);
1324                         List<String> structMembers = structDecl.getMembers(stType);
1325                         for (int i = 0; i < structMembers.size(); i++) {
1326
1327                                 String memberType = structMemberTypes.get(i);
1328                                 String member = structMembers.get(i);
1329                                 String structTypeC = checkAndGetCplusType(memberType);
1330                                 String structComplete = checkAndGetCplusArray(structTypeC, member);
1331                                 println(structComplete + ";");
1332                         }
1333                         println("};\n");
1334                 }
1335         }
1336
1337
1338         /**
1339          * generateCplusLocalInterfaces() writes the local interfaces and provides type-checking.
1340          * <p>
1341          * It needs to rewrite and exchange USERDEFINED types in input parameters of stub
1342          * and original interfaces, e.g. exchange Camera and CameraWithVideoAndRecording.
1343          * The local interface has to be the input parameter for the stub and the stub 
1344          * interface has to be the input parameter for the local class.
1345          */
1346         public void generateCplusLocalInterfaces() throws IOException {
1347
1348                 // Create a new directory
1349                 createDirectory(dir);
1350                 for (String intface : mapIntfacePTH.keySet()) {
1351                         // Open a new file to write into
1352                         FileWriter fw = new FileWriter(dir + "/" + intface + ".hpp");
1353                         pw = new PrintWriter(new BufferedWriter(fw));
1354                         // Write file headers
1355                         println("#ifndef _" + intface.toUpperCase() + "_HPP__");
1356                         println("#define _" + intface.toUpperCase() + "_HPP__");
1357                         println("#include <iostream>");
1358                         // Pass in set of methods and get include classes
1359                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
1360                         InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
1361                         List<String> methods = intDecl.getMethods();
1362                         Set<String> includeClasses = getIncludeClasses(methods, intDecl);
1363                         printIncludeStatements(includeClasses); println("");
1364                         println("using namespace std;\n");
1365                         // Write enum if any...
1366                         EnumDecl enumDecl = (EnumDecl) decHandler.getEnumDecl(intface);
1367                         writeEnumCplus(enumDecl);
1368                         // Write struct if any...
1369                         StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
1370                         writeStructCplus(structDecl);
1371                         println("class " + intface); println("{");
1372                         println("public:");
1373                         // Write methods
1374                         writeMethodCplusInterface(methods, intDecl);
1375                         println("};");
1376                         println("#endif");
1377                         pw.close();
1378                         System.out.println("IoTCompiler: Generated local interface " + intface + ".hpp...");
1379                 }
1380         }
1381
1382
1383         /**
1384          * generateCPlusInterfaces() generate stub interfaces based on the methods list in C++
1385          * <p>
1386          * For C++ we use virtual classe as interface
1387          */
1388         public void generateCPlusInterfaces() throws IOException {
1389
1390                 // Create a new directory
1391                 String path = createDirectories(dir, subdir);
1392                 for (String intface : mapIntfacePTH.keySet()) {
1393
1394                         Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
1395                         for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
1396
1397                                 // Open a new file to write into
1398                                 String newIntface = intMeth.getKey();
1399                                 FileWriter fw = new FileWriter(path + "/" + newIntface + ".hpp");
1400                                 pw = new PrintWriter(new BufferedWriter(fw));
1401                                 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
1402                                 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
1403                                 // Write file headers
1404                                 println("#ifndef _" + newIntface.toUpperCase() + "_HPP__");
1405                                 println("#define _" + newIntface.toUpperCase() + "_HPP__");
1406                                 println("#include <iostream>");
1407                                 // Pass in set of methods and get import classes
1408                                 Set<String> includeClasses = getIncludeClasses(intMeth.getValue(), intDecl);
1409                                 List<String> stdIncludeClasses = getStandardCplusIncludeClasses();
1410                                 List<String> allIncludeClasses = getAllImportClasses(stdIncludeClasses, includeClasses);
1411                                 printIncludeStatements(allIncludeClasses); println("");                 
1412                                 println("using namespace std;\n");
1413                                 println("class " + newIntface);
1414                                 println("{");
1415                                 println("public:");
1416                                 // Write methods
1417                                 writeMethodCplusInterface(intMeth.getValue(), intDecl);
1418                                 println("};");
1419                                 println("#endif");
1420                                 pw.close();
1421                                 System.out.println("IoTCompiler: Generated interface " + newIntface + ".hpp...");
1422                         }
1423                 }
1424         }
1425
1426
1427         /**
1428          * HELPER: writeMethodCplusStub() writes the method of the stub
1429          */
1430         private void writeMethodCplusStub(Collection<String> methods, InterfaceDecl intDecl) {
1431
1432                 for (String method : methods) {
1433
1434                         List<String> methParams = intDecl.getMethodParams(method);
1435                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1436                         print(checkAndGetCplusType(intDecl.getMethodType(method)) + " " +
1437                                 intDecl.getMethodId(method) + "(");
1438                         for (int i = 0; i < methParams.size(); i++) {
1439
1440                                 //String paramType = checkAndGetParamClass(methPrmTypes.get(i), true);
1441                                 String paramType = methPrmTypes.get(i);
1442                                 String methPrmType = checkAndGetCplusType(paramType);
1443                                 String methParamComplete = checkAndGetCplusArray(methPrmType, methParams.get(i));
1444                                 print(methParamComplete);
1445                                 // Check if this is the last element (don't print a comma)
1446                                 if (i != methParams.size() - 1) {
1447                                         print(", ");
1448                                 }
1449                         }
1450                         println(") { ");
1451                         writeStdMethodBodyCplusStub(intDecl, methParams, methPrmTypes, method);
1452                         println("}\n");
1453                 }
1454         }
1455
1456
1457         /**
1458          * HELPER: writeStdMethodBodyCplusStub() writes the standard method body in the stub class
1459          */
1460         private void writeStdMethodBodyCplusStub(InterfaceDecl intDecl, List<String> methParams,
1461                         List<String> methPrmTypes, String method) {
1462
1463                 println("int numParam = " + methParams.size() + ";");
1464                 println("int methodId = " + intDecl.getMethodNumId(method) + ";");
1465                 String retType = intDecl.getMethodType(method);
1466                 String retTypeC = checkAndGetCplusType(retType);
1467                 println("string retType = \"" + checkAndGetCplusArrayType(retTypeC) + "\";");
1468                 // Generate array of parameter types
1469                 print("string paramCls[] = { ");
1470                 for (int i = 0; i < methParams.size(); i++) {
1471                         String paramTypeC = checkAndGetCplusType(methPrmTypes.get(i));
1472                         String paramType = checkAndGetCplusArrayType(paramTypeC, methParams.get(i));
1473                         print("\"" + paramType + "\"");
1474                         // Check if this is the last element (don't print a comma)
1475                         if (i != methParams.size() - 1) {
1476                                 print(", ");
1477                         }
1478                 }
1479                 println(" };");
1480                 // Generate array of parameter objects
1481                 print("void* paramObj[] = { ");
1482                 for (int i = 0; i < methParams.size(); i++) {
1483                         print("&" + checkAndGetCplusType(getSimpleIdentifier(methParams.get(i))));
1484                         // Check if this is the last element (don't print a comma)
1485                         if (i != methParams.size() - 1) {
1486                                 print(", ");
1487                         }
1488                 }
1489                 println(" };");
1490                 // Check if this is "void"
1491                 if (retType.equals("void")) {
1492                         println("void* retObj = NULL;");
1493                         println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
1494                 } else { // We do have a return value
1495                         if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
1496                                 println(checkAndGetCplusType(retType) + " retVal;");
1497                         else
1498                                 println(checkAndGetCplusType(retType) + " retVal = " + generateCplusInitializer(retType) + ";");
1499                         println("void* retObj = &retVal;");
1500                         println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
1501                         println("return retVal;");
1502                 }
1503         }
1504
1505
1506         /**
1507          * HELPER: writePropertiesCplusStub() writes the properties of the stub class
1508          */
1509         private void writePropertiesCplusStub(String intface, String newIntface) {
1510
1511                 println("IoTRMICall *rmiCall;");
1512                 //println("IoTRMIObject\t\t\t*rmiObj;");
1513                 println("string address;");
1514                 println("vector<int> ports;\n");
1515                 // Get the object Id
1516                 Integer objId = mapIntfaceObjId.get(intface);
1517                 println("const static int objectId = " + objId + ";");
1518                 mapNewIntfaceObjId.put(newIntface, objId);
1519                 mapIntfaceObjId.put(intface, objId++);
1520                 println("\n");
1521         }
1522
1523
1524         /**
1525          * HELPER: writeConstructorCplusStub() writes the constructor of the stub class
1526          */
1527         private void writeConstructorCplusStub(String newStubClass) {
1528
1529                 println(newStubClass + 
1530                         "(int _port, const char* _address, int _rev, bool* _bResult, vector<int> _ports) {");
1531                 println("address = _address;");
1532                 println("ports = _ports;");
1533                 println("rmiCall = new IoTRMICall(_port, _address, _rev, _bResult);");
1534                 println("}\n");
1535         }
1536
1537
1538         /**
1539          * HELPER: writeDeconstructorCplusStub() writes the deconstructor of the stub class
1540          */
1541         private void writeDeconstructorCplusStub(String newStubClass) {
1542
1543                 println("~" + newStubClass + "() {");
1544                 println("if (rmiCall != NULL) {");
1545                 println("delete rmiCall;");
1546                 println("rmiCall = NULL;");
1547                 println("}");
1548                 println("}");
1549                 println("");
1550                 // Check if this is callback!!! and print "delete rmiObj and vecCBObj"
1551         }
1552
1553
1554         /**
1555          * generateCPlusStubClasses() generate stubs based on the methods list in C++
1556          */
1557         public void generateCPlusStubClasses() throws IOException {
1558
1559                 // Create a new directory
1560                 String path = createDirectories(dir, subdir);
1561                 for (String intface : mapIntfacePTH.keySet()) {
1562
1563                         Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
1564                         for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
1565                                 // Open a new file to write into
1566                                 String newIntface = intMeth.getKey();
1567                                 String newStubClass = newIntface + "_Stub";
1568                                 FileWriter fw = new FileWriter(path + "/" + newStubClass + ".hpp");
1569                                 pw = new PrintWriter(new BufferedWriter(fw));
1570                                 // Write file headers
1571                                 println("#ifndef _" + newStubClass.toUpperCase() + "_HPP__");
1572                                 println("#define _" + newStubClass.toUpperCase() + "_HPP__");
1573                                 println("#include <iostream>");
1574                                 println("#include \"" + newIntface + ".hpp\""); println("");            
1575                                 println("using namespace std;"); println("");
1576                                 println("class " + newStubClass + " : public " + newIntface); println("{");
1577                                 println("private:\n");
1578                                 writePropertiesCplusStub(intface, newIntface);
1579                                 println("public:\n");
1580                                 // Add default constructor and destructor
1581                                 println(newStubClass + "() { }"); println("");
1582                                 writeConstructorCplusStub(newStubClass);
1583                                 writeDeconstructorCplusStub(newStubClass);
1584                                 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
1585                                 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
1586                                 // Write methods
1587                                 writeMethodCplusStub(intMeth.getValue(), intDecl);
1588                                 print("}"); println(";");
1589                                 println("#endif");
1590                                 pw.close();
1591                                 System.out.println("IoTCompiler: Generated stub class " + newIntface + ".hpp...");
1592                         }
1593                 }
1594         }
1595
1596
1597         /**
1598          * HELPER: writePropertiesCplusCallbackStub() writes the properties of the stub class
1599          */
1600         private void writePropertiesCplusCallbackStub(String intface, String newIntface) {
1601
1602                 println("IoTRMICall *rmiCall;");
1603                 // Get the object Id
1604                 println("static int objectId;");
1605                 println("\n");
1606         }
1607
1608
1609         /**
1610          * HELPER: writeConstructorCplusCallbackStub() writes the constructor of the stub class
1611          */
1612         private void writeConstructorCplusCallbackStub(String newStubClass) {
1613
1614                 println(newStubClass + "(IoTRMICall* _rmiCall, int _objectId) {");
1615                 println("objectId = _objectId;");
1616                 println("rmiCall = _rmiCall;");
1617                 println("}\n");
1618         }
1619
1620
1621         /**
1622          * generateCPlusCallbackStubClasses() generate callback stubs based on the methods list in C++
1623          */
1624         public void generateCPlusCallbackStubClasses() throws IOException {
1625
1626                 // Create a new directory
1627                 String path = createDirectories(dir, subdir);
1628                 for (String intface : mapIntfacePTH.keySet()) {
1629
1630                         Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
1631                         for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
1632                                 // Open a new file to write into
1633                                 String newIntface = intMeth.getKey();
1634                                 String newStubClass = newIntface + "_CallbackStub";
1635                                 FileWriter fw = new FileWriter(path + "/" + newStubClass + ".hpp");
1636                                 pw = new PrintWriter(new BufferedWriter(fw));
1637                                 // Write file headers
1638                                 println("#ifndef _" + newStubClass.toUpperCase() + "_HPP__");
1639                                 println("#define _" + newStubClass.toUpperCase() + "_HPP__");
1640                                 println("#include <iostream>");
1641                                 println("#include \"" + newIntface + ".hpp\""); println("");            
1642                                 println("using namespace std;"); println("");
1643                                 println("class " + newStubClass + " : public " + newIntface); println("{");
1644                                 println("private:\n");
1645                                 writePropertiesCplusCallbackStub(intface, newIntface);
1646                                 println("public:\n");
1647                                 // Add default constructor and destructor
1648                                 println(newStubClass + "() { }"); println("");
1649                                 writeConstructorCplusCallbackStub(newStubClass);
1650                                 writeDeconstructorCplusStub(newStubClass);
1651                                 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
1652                                 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
1653                                 // Write methods
1654                                 writeMethodCplusStub(intMeth.getValue(), intDecl);
1655                                 print("}"); println(";");
1656                                 println("#endif");
1657                                 pw.close();
1658                                 System.out.println("IoTCompiler: Generated callback stub class " + newIntface + ".hpp...");
1659                         }
1660                 }
1661         }
1662
1663
1664         /**
1665          * HELPER: writePropertiesCplusSkeleton() writes the properties of the skeleton class
1666          */
1667         private void writePropertiesCplusSkeleton(String intface) {
1668
1669                 println(intface + " *mainObj;");
1670                 //println("private int ports;");
1671                 //println("private IoTRMICall rmiCall;");
1672                 println("IoTRMIObject *rmiObj;\n");
1673                 // Keep track of object Ids of all stubs registered to this interface
1674                 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
1675                 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
1676                         String newIntface = intMeth.getKey();
1677                         int newObjectId = mapNewIntfaceObjId.get(newIntface);
1678 //                      println("const static int object" + newObjectId + "Id = " + 
1679 //                              newObjectId + ";\t//" + newIntface);
1680                 }
1681                 // TODO: CALLBACKS!
1682                 // TODO: code the set of allowed functions here
1683                 println("\n");
1684         }
1685
1686
1687         /**
1688          * HELPER: writeConstructorCplusSkeleton() writes the constructor of the skeleton class
1689          */
1690         private void writeConstructorCplusSkeleton(String newSkelClass, String intface) {
1691
1692                 println(newSkelClass + "(" + intface + " *_mainObj, int _port) {");
1693                 println("bool _bResult = false;");
1694                 println("mainObj = _mainObj;");
1695                 println("rmiObj = new IoTRMIObject(_port, &_bResult);");
1696                 //println("set0Allowed = Arrays.asList(object0Permission);");
1697                 //println("___waitRequestInvokeMethod();");
1698                 println("}\n");
1699         }
1700
1701
1702         /**
1703          * HELPER: writeDeconstructorCplusSkeleton() writes the deconstructor of the skeleton class
1704          */
1705         private void writeDeconstructorCplusSkeleton(String newSkelClass) {
1706
1707                 println("~" + newSkelClass + "() {");
1708                 println("if (rmiObj != NULL) {");
1709                 println("delete rmiObj;");
1710                 println("rmiObj = NULL;");
1711                 println("}");
1712                 println("}");
1713                 println("");
1714                 // Check if this is callback!!! and print "delete rmiObj and vecCBObj"
1715         }
1716
1717
1718         /**
1719          * HELPER: writeStdMethodBodyCplusSkeleton() writes the standard method body in the skeleton class
1720          */
1721         private void writeStdMethodBodyCplusSkeleton(List<String> methParams, String methodId, String methodType) {
1722
1723                 if (methodType.equals("void"))
1724                         print("mainObj->" + methodId + "(");
1725                 else
1726                         print("return mainObj->" + methodId + "(");
1727                 for (int i = 0; i < methParams.size(); i++) {
1728
1729                         print(getSimpleIdentifier(methParams.get(i)));
1730                         // Check if this is the last element (don't print a comma)
1731                         if (i != methParams.size() - 1) {
1732                                 print(", ");
1733                         }
1734                 }
1735                 println(");");
1736         }
1737
1738
1739         /**
1740          * HELPER: writeMethodCplusSkeleton() writes the method of the skeleton class
1741          */
1742         private void writeMethodCplusSkeleton(Collection<String> methods, InterfaceDecl intDecl) {
1743
1744                 for (String method : methods) {
1745
1746                         List<String> methParams = intDecl.getMethodParams(method);
1747                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1748                         String methodId = intDecl.getMethodId(method);
1749                         String methodType = checkAndGetCplusType(intDecl.getMethodType(method));
1750                         print(methodType + " " + methodId + "(");
1751                         for (int i = 0; i < methParams.size(); i++) {
1752
1753                                 String paramType = checkAndGetParamClass(methPrmTypes.get(i), true);
1754                                 String methPrmType = checkAndGetCplusType(paramType);
1755                                 String methParamComplete = checkAndGetCplusArray(methPrmType, methParams.get(i));
1756                                 print(methParamComplete);
1757                                 // Check if this is the last element (don't print a comma)
1758                                 if (i != methParams.size() - 1) {
1759                                         print(", ");
1760                                 }
1761                         }
1762                         println(") {");
1763                         // Now, write the body of skeleton!
1764                         writeStdMethodBodyCplusSkeleton(methParams, methodId, intDecl.getMethodType(method));
1765                         println("}\n");
1766                 }
1767         }
1768
1769
1770         /**
1771          * HELPER: writeStdMethodHelperBodyCplusSkeleton() writes the standard method body helper in the skeleton class
1772          */
1773         private void writeStdMethodHelperBodyCplusSkeleton(InterfaceDecl intDecl, List<String> methParams,
1774                         List<String> methPrmTypes, String method, String methodId) {
1775
1776                 // Generate array of parameter types
1777                 print("string paramCls[] = { ");
1778                 for (int i = 0; i < methParams.size(); i++) {
1779                         String paramTypeC = checkAndGetCplusType(methPrmTypes.get(i));
1780                         String paramType = checkAndGetCplusArrayType(paramTypeC, methParams.get(i));
1781                         print("\"" + paramType + "\"");
1782                         if (i != methParams.size() - 1) {
1783                                 print(", ");
1784                         }
1785                 }
1786                 println(" };");
1787                 println("int numParam = " + methParams.size() + ";");
1788                 // Generate parameters
1789                 for (int i = 0; i < methParams.size(); i++) {
1790                         String methPrmType = checkAndGetCplusType(methPrmTypes.get(i));
1791                         String methParamComplete = checkAndGetCplusArray(methPrmType, methParams.get(i));
1792                         println(methParamComplete + ";");
1793                 }
1794                 // Generate array of parameter objects
1795                 print("void* paramObj[] = { ");
1796                 for (int i = 0; i < methParams.size(); i++) {
1797                         print("&" + getSimpleIdentifier(methParams.get(i)));
1798                         if (i != methParams.size() - 1) {
1799                                 print(", ");
1800                         }
1801                 }
1802                 println(" };");
1803                 println("rmiObj->getMethodParams(paramCls, numParam, paramObj);");
1804                 String retType = intDecl.getMethodType(method);
1805                 // Check if this is "void"
1806                 if (retType.equals("void")) {
1807                         print(methodId + "(");
1808                         for (int i = 0; i < methParams.size(); i++) {
1809                                 print(getSimpleIdentifier(methParams.get(i)));
1810                                 if (i != methParams.size() - 1) {
1811                                         print(", ");
1812                                 }
1813                         }
1814                         println(");");
1815                 } else { // We do have a return value
1816                         print(checkAndGetCplusType(retType) + " retVal = " + methodId + "(");
1817                         for (int i = 0; i < methParams.size(); i++) {
1818                                 print(getSimpleIdentifier(methParams.get(i)));
1819                                 if (i != methParams.size() - 1) {
1820                                         print(", ");
1821                                 }
1822                         }
1823                         println(");");
1824                         println("void* retObj = &retVal;");
1825                         String retTypeC = checkAndGetCplusType(retType);
1826                         println("rmiObj->sendReturnObj(retObj, \"" + checkAndGetCplusArrayType(retTypeC) + "\");");
1827                 }
1828         }
1829
1830
1831         /**
1832          * HELPER: writeMethodHelperCplusSkeleton() writes the method helper of the skeleton class
1833          */
1834         private void writeMethodHelperCplusSkeleton(Collection<String> methods, InterfaceDecl intDecl) {
1835
1836                 // Use this set to handle two same methodIds
1837                 Set<String> uniqueMethodIds = new HashSet<String>();
1838                 for (String method : methods) {
1839
1840                         List<String> methParams = intDecl.getMethodParams(method);
1841                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1842                         String methodId = intDecl.getMethodId(method);
1843                         print("void ___");
1844                         String helperMethod = methodId;
1845                         if (uniqueMethodIds.contains(methodId))
1846                                 helperMethod = helperMethod + intDecl.getMethodNumId(method);
1847                         else
1848                                 uniqueMethodIds.add(methodId);
1849                         // Check if this is "void"
1850                         String retType = intDecl.getMethodType(method);
1851                         println(helperMethod + "() {");
1852                         // Now, write the helper body of skeleton!
1853                         writeStdMethodHelperBodyCplusSkeleton(intDecl, methParams, methPrmTypes, method, methodId);
1854                         println("}\n");
1855                 }
1856         }
1857
1858
1859         /**
1860          * HELPER: writeCplusWaitRequestInvokeMethod() writes the main loop of the skeleton class
1861          */
1862         private void writeCplusWaitRequestInvokeMethod(Collection<String> methods, InterfaceDecl intDecl) {
1863
1864                 // Use this set to handle two same methodIds
1865                 Set<String> uniqueMethodIds = new HashSet<String>();
1866                 println("void ___waitRequestInvokeMethod() {");
1867                 // Write variables here if we have callbacks or enums or structs
1868                 println("while (true) {");
1869                 println("rmiObj->getMethodBytes();");
1870                 println("int _objectId = rmiObj->getObjectId();");
1871                 println("int methodId = rmiObj->getMethodId();");
1872                 // TODO: code the permission check here!
1873                 println("switch (methodId) {");
1874                 // Print methods and method Ids
1875                 for (String method : methods) {
1876                         String methodId = intDecl.getMethodId(method);
1877                         int methodNumId = intDecl.getMethodNumId(method);
1878                         print("case " + methodNumId + ": ___");
1879                         String helperMethod = methodId;
1880                         if (uniqueMethodIds.contains(methodId))
1881                                 helperMethod = helperMethod + methodNumId;
1882                         else
1883                                 uniqueMethodIds.add(methodId);
1884                         println(helperMethod + "(); break;");
1885                 }
1886                 println("default: ");
1887                 println("cerr << \"Method Id \" << methodId << \" not recognized!\" << endl;");
1888                 println("throw exception();");
1889                 println("}");
1890                 println("}");
1891                 println("}\n");
1892         }
1893
1894
1895         /**
1896          * generateCplusSkeletonClass() generate skeletons based on the methods list in C++
1897          */
1898         public void generateCplusSkeletonClass() throws IOException {
1899
1900                 // Create a new directory
1901                 String path = createDirectories(dir, subdir);
1902                 for (String intface : mapIntfacePTH.keySet()) {
1903                         // Open a new file to write into
1904                         String newSkelClass = intface + "_Skeleton";
1905                         FileWriter fw = new FileWriter(path + "/" + newSkelClass + ".hpp");
1906                         pw = new PrintWriter(new BufferedWriter(fw));
1907                         // Write file headers
1908                         println("#ifndef _" + newSkelClass.toUpperCase() + "_HPP__");
1909                         println("#define _" + newSkelClass.toUpperCase() + "_HPP__");
1910                         println("#include <iostream>");
1911                         println("#include \"" + intface + ".hpp\"\n");
1912                         // Pass in set of methods and get import classes
1913                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
1914                         InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
1915                         List<String> methods = intDecl.getMethods();
1916                         Set<String> includeClasses = getIncludeClasses(methods, intDecl);
1917                         List<String> stdIncludeClasses = getStandardCplusIncludeClasses();
1918                         List<String> allIncludeClasses = getAllImportClasses(stdIncludeClasses, includeClasses);
1919                         printIncludeStatements(allIncludeClasses); println("");                 
1920                         println("using namespace std;\n");
1921                         // Write class header
1922                         println("class " + newSkelClass + " : public " + intface); println("{");
1923                         println("private:\n");
1924                         // Write properties
1925                         writePropertiesCplusSkeleton(intface);
1926                         println("public:\n");
1927                         // Write constructor
1928                         writeConstructorCplusSkeleton(newSkelClass, intface);
1929                         // Write deconstructor
1930                         writeDeconstructorCplusSkeleton(newSkelClass);
1931                         // Write methods
1932                         writeMethodCplusSkeleton(methods, intDecl);
1933                         // Write method helper
1934                         writeMethodHelperCplusSkeleton(methods, intDecl);
1935                         // Write waitRequestInvokeMethod() - main loop
1936                         writeCplusWaitRequestInvokeMethod(methods, intDecl);
1937                         println("};");
1938                         println("#endif");
1939                         pw.close();
1940                         System.out.println("IoTCompiler: Generated skeleton class " + newSkelClass + ".hpp...");
1941                 }
1942         }
1943
1944
1945         /**
1946          * HELPER: writePropertiesCplusCallbackSkeleton() writes the properties of the callback skeleton class
1947          */
1948         private void writePropertiesCplusCallbackSkeleton(String intface) {
1949
1950                 println(intface + " *mainObj;");
1951                 //println("IoTRMIObject *rmiObj;\n");
1952                 // Keep track of object Ids of all stubs registered to this interface
1953                 println("static int objectId;");
1954                 println("\n");
1955         }
1956
1957
1958         /**
1959          * HELPER: writeConstructorCplusCallbackSkeleton() writes the constructor of the skeleton class
1960          */
1961         private void writeConstructorCplusCallbackSkeleton(String newSkelClass, String intface) {
1962
1963                 println(newSkelClass + "(" + intface + " *_mainObj, int _objectId) {");
1964                 println("mainObj = _mainObj;");
1965                 println("objectId = _objectId;");
1966                 println("}\n");
1967         }
1968
1969
1970         /**
1971          * HELPER: writeMethodHelperCplusCallbackSkeleton() writes the method helper of the callback skeleton class
1972          */
1973         private void writeMethodHelperCplusCallbackSkeleton(Collection<String> methods, InterfaceDecl intDecl) {
1974
1975                 // Use this set to handle two same methodIds
1976                 Set<String> uniqueMethodIds = new HashSet<String>();
1977                 for (String method : methods) {
1978
1979                         List<String> methParams = intDecl.getMethodParams(method);
1980                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1981                         String methodId = intDecl.getMethodId(method);
1982                         print("void ___");
1983                         String helperMethod = methodId;
1984                         if (uniqueMethodIds.contains(methodId))
1985                                 helperMethod = helperMethod + intDecl.getMethodNumId(method);
1986                         else
1987                                 uniqueMethodIds.add(methodId);
1988                         // Check if this is "void"
1989                         String retType = intDecl.getMethodType(method);
1990                         println(helperMethod + "(IoTRMIObject* rmiObj) {");
1991                         // Now, write the helper body of skeleton!
1992                         writeStdMethodHelperBodyCplusSkeleton(intDecl, methParams, methPrmTypes, method, methodId);
1993                         println("}\n");
1994                 }
1995         }
1996
1997
1998         /**
1999          * HELPER: writeCplusCallbackWaitRequestInvokeMethod() writes the main loop of the skeleton class
2000          */
2001         private void writeCplusCallbackWaitRequestInvokeMethod(Collection<String> methods, InterfaceDecl intDecl) {
2002
2003                 // Use this set to handle two same methodIds
2004                 Set<String> uniqueMethodIds = new HashSet<String>();
2005                 println("void invokeMethod(IoTRMIObject* rmiObj) {");
2006                 // Write variables here if we have callbacks or enums or structs
2007                 println("int methodId = rmiObj->getMethodId();");
2008                 // TODO: code the permission check here!
2009                 println("switch (methodId) {");
2010                 // Print methods and method Ids
2011                 for (String method : methods) {
2012                         String methodId = intDecl.getMethodId(method);
2013                         int methodNumId = intDecl.getMethodNumId(method);
2014                         print("case " + methodNumId + ": ___");
2015                         String helperMethod = methodId;
2016                         if (uniqueMethodIds.contains(methodId))
2017                                 helperMethod = helperMethod + methodNumId;
2018                         else
2019                                 uniqueMethodIds.add(methodId);
2020                         println(helperMethod + "(rmiObj); break;");
2021                 }
2022                 println("default: ");
2023                 println("cerr << \"Method Id \" << methodId << \" not recognized!\" << endl;");
2024                 println("throw exception();");
2025                 println("}");
2026                 println("}\n");
2027         }
2028
2029
2030
2031         /**
2032          * generateCplusCallbackSkeletonClass() generate callback skeletons based on the methods list in C++
2033          */
2034         public void generateCplusCallbackSkeletonClass() throws IOException {
2035
2036                 // Create a new directory
2037                 String path = createDirectories(dir, subdir);
2038                 for (String intface : mapIntfacePTH.keySet()) {
2039                         // Open a new file to write into
2040                         String newSkelClass = intface + "_CallbackSkeleton";
2041                         FileWriter fw = new FileWriter(path + "/" + newSkelClass + ".hpp");
2042                         pw = new PrintWriter(new BufferedWriter(fw));
2043                         // Write file headers
2044                         println("#ifndef _" + newSkelClass.toUpperCase() + "_HPP__");
2045                         println("#define _" + newSkelClass.toUpperCase() + "_HPP__");
2046                         println("#include <iostream>");
2047                         println("#include \"" + intface + ".hpp\"\n");
2048                         // Pass in set of methods and get import classes
2049                         DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2050                         InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
2051                         List<String> methods = intDecl.getMethods();
2052                         Set<String> includeClasses = getIncludeClasses(methods, intDecl);
2053                         List<String> stdIncludeClasses = getStandardCplusIncludeClasses();
2054                         List<String> allIncludeClasses = getAllImportClasses(stdIncludeClasses, includeClasses);
2055                         printIncludeStatements(allIncludeClasses); println("");                 
2056                         println("using namespace std;\n");
2057                         // Write class header
2058                         println("class " + newSkelClass + " : public " + intface); println("{");
2059                         println("private:\n");
2060                         // Write properties
2061                         writePropertiesCplusCallbackSkeleton(intface);
2062                         println("public:\n");
2063                         // Write constructor
2064                         writeConstructorCplusCallbackSkeleton(newSkelClass, intface);
2065                         // Write deconstructor
2066                         //writeDeconstructorCplusSkeleton(newSkelClass);
2067                         // Write methods
2068                         writeMethodCplusSkeleton(methods, intDecl);
2069                         // Write method helper
2070                         writeMethodHelperCplusCallbackSkeleton(methods, intDecl);
2071                         // Write waitRequestInvokeMethod() - main loop
2072                         writeCplusCallbackWaitRequestInvokeMethod(methods, intDecl);
2073                         println("};");
2074                         println("#endif");
2075                         pw.close();
2076                         System.out.println("IoTCompiler: Generated callback skeleton class " + newSkelClass + ".hpp...");
2077                 }
2078         }
2079
2080
2081         /**
2082          * generateInitializer() generate initializer based on type
2083          */
2084         public String generateCplusInitializer(String type) {
2085
2086                 // Generate dummy returns for now
2087                 if (type.equals("short")||
2088                         type.equals("int")      ||
2089                         type.equals("long") ||
2090                         type.equals("float")||
2091                         type.equals("double")) {
2092
2093                         return "0";
2094                 } else if ( type.equals("String") ||
2095                                         type.equals("string")) {
2096   
2097                         return "\"\"";
2098                 } else if ( type.equals("char") ||
2099                                         type.equals("byte")) {
2100
2101                         return "\' \'";
2102                 } else if ( type.equals("boolean")) {
2103
2104                         return "false";
2105                 } else {
2106                         return "NULL";
2107                 }
2108         }
2109
2110
2111         /**
2112          * generateReturnStmt() generate return statement based on methType
2113          */
2114         public String generateReturnStmt(String methType) {
2115
2116                 // Generate dummy returns for now
2117                 if (methType.equals("short")||
2118                         methType.equals("int")  ||
2119                         methType.equals("long") ||
2120                         methType.equals("float")||
2121                         methType.equals("double")) {
2122
2123                         return "1";
2124                 } else if ( methType.equals("String")) {
2125   
2126                         return "\"a\"";
2127                 } else if ( methType.equals("char") ||
2128                                         methType.equals("byte")) {
2129
2130                         return "\'a\'";
2131                 } else if ( methType.equals("boolean")) {
2132
2133                         return "true";
2134                 } else {
2135                         return "null";
2136                 }
2137         }
2138
2139
2140         /**
2141          * setDirectory() sets a new directory for stub files
2142          */
2143         public void setDirectory(String _subdir) {
2144
2145                 subdir = _subdir;
2146         }
2147
2148
2149         /**
2150          * printUsage() prints the usage of this compiler
2151          */
2152         public static void printUsage() {
2153
2154                 System.out.println();
2155                 System.out.println("Sentinel interface and stub compiler version 1.0");
2156                 System.out.println("Copyright (c) 2015-2016 University of California, Irvine - Programming Language Group.");
2157                 System.out.println("All rights reserved.");
2158                 System.out.println("Usage:");
2159                 System.out.println("\tjava IoTCompiler -help / --help / -h\n");
2160                 System.out.println("\t\tDisplay this help texts\n\n");
2161                 System.out.println("\tjava IoTCompiler [<main-policy-file> <req-policy-file>]");
2162                 System.out.println("\tjava IoTCompiler [<main-policy-file> <req-policy-file>] [options]\n");
2163                 System.out.println("\t\tTake one or more pairs of main-req policy files, and generate Java and/or C++ files\n");
2164                 System.out.println("Options:");
2165                 System.out.println("\t-java\t<directory>\tGenerate Java stub files");
2166                 System.out.println("\t-cplus\t<directory>\tGenerate C++ stub files");
2167                 System.out.println();
2168         }
2169
2170
2171         /**
2172          * parseFile() prepares Lexer and Parser objects, then parses the file
2173          */
2174         public static ParseNode parseFile(String file) {
2175
2176                 ParseNode pn = null;
2177                 try {
2178                         ComplexSymbolFactory csf = new ComplexSymbolFactory();
2179                         ScannerBuffer lexer = 
2180                                 new ScannerBuffer(new Lexer(new BufferedReader(new FileReader(file)),csf));
2181                         Parser parse = new Parser(lexer,csf);
2182                         pn = (ParseNode) parse.parse().value;
2183                 } catch (Exception e) {
2184                         e.printStackTrace();
2185                         throw new Error("IoTCompiler: ERROR parsing policy file or wrong command line option: " + file);
2186                 }
2187
2188                 return pn;
2189         }
2190
2191
2192         /**================
2193          * Helper functions
2194          **================
2195          */
2196         boolean newline=true;
2197         int tablevel=0;
2198
2199         private void print(String str) {
2200                 if (newline) {
2201                         int tab=tablevel;
2202                         if (str.equals("}"))
2203                                 tab--;
2204                         for(int i=0; i<tab; i++)
2205                                 pw.print("\t");
2206                 }
2207                 pw.print(str);
2208                 updatetabbing(str);
2209                 newline=false;
2210         }
2211
2212
2213         /**
2214          * This function converts Java to C++ type for compilation
2215          */
2216         private String convertType(String jType) {
2217
2218                 return mapPrimitives.get(jType);
2219         }
2220
2221
2222         private void println(String str) {
2223                 if (newline) {
2224                         int tab = tablevel;
2225                         if (str.equals("}"))
2226                                 tab--;
2227                         for(int i=0; i<tab; i++)
2228                                 pw.print("\t");
2229                 }
2230                 pw.println(str);
2231                 updatetabbing(str);
2232                 newline = true;
2233         }
2234
2235
2236         private void updatetabbing(String str) {
2237                 tablevel+=count(str,'{')-count(str,'}');
2238         }
2239
2240
2241         private int count(String str, char key) {
2242                 char[] array = str.toCharArray();
2243                 int count = 0;
2244                 for(int i=0; i<array.length; i++) {
2245                         if (array[i] == key)
2246                                 count++;
2247                 }
2248                 return count;
2249         }
2250
2251
2252         private void createDirectory(String dirName) {
2253
2254                 File file = new File(dirName);
2255                 if (!file.exists()) {
2256                         if (file.mkdir()) {
2257                                 System.out.println("IoTCompiler: Directory " + dirName + " has been created!");
2258                         } else {
2259                                 System.out.println("IoTCompiler: Failed to create directory " + dirName + "!");
2260                         }
2261                 } else {
2262                         System.out.println("IoTCompiler: Directory " + dirName + " exists...");
2263                 }
2264         }
2265
2266
2267         // Create a directory and possibly a sub directory
2268         private String createDirectories(String dir, String subdir) {
2269
2270                 String path = dir;
2271                 createDirectory(path);
2272                 if (subdir != null) {
2273                         path = path + "/" + subdir;
2274                         createDirectory(path);
2275                 }
2276                 return path;
2277         }
2278
2279
2280         // Inserting array members into a Map object
2281         // that maps arrKey to arrVal objects
2282         private void arraysToMap(Map map, Object[] arrKey, Object[] arrVal) {
2283
2284                 for(int i = 0; i < arrKey.length; i++) {
2285
2286                         map.put(arrKey[i], arrVal[i]);
2287                 }
2288         }
2289
2290
2291         // Return parameter category, i.e. PRIMITIVES, NONPRIMITIVES, or USERDEFINED
2292         private ParamCategory getParamCategory(String paramType) {
2293
2294                 if (mapPrimitives.containsKey(paramType)) {
2295                         return ParamCategory.PRIMITIVES;
2296                 // We can either use mapNonPrimitivesJava or mapNonPrimitivesCplus here
2297                 } else if (mapNonPrimitivesJava.containsKey(getSimpleType(paramType))) {
2298                         return ParamCategory.NONPRIMITIVES;
2299                 } else
2300                         return ParamCategory.USERDEFINED;
2301         }
2302
2303
2304         // Return full class name for non-primitives to generate Java import statements
2305         // e.g. java.util.Set for Set, java.util.Map for Map
2306         private String getNonPrimitiveJavaClass(String paramNonPrimitives) {
2307
2308                 return mapNonPrimitivesJava.get(paramNonPrimitives);
2309         }
2310
2311
2312         // Return full class name for non-primitives to generate Cplus include statements
2313         // e.g. #include <set> for Set, #include <map> for Map
2314         private String getNonPrimitiveCplusClass(String paramNonPrimitives) {
2315
2316                 return mapNonPrimitivesCplus.get(paramNonPrimitives);
2317         }
2318
2319
2320         // Get simple types, e.g. HashSet for HashSet<...>
2321         // Basically strip off the "<...>"
2322         private String getSimpleType(String paramType) {
2323
2324                 // Check if this is generics
2325                 if(paramType.contains("<")) {
2326                         String[] type = paramType.split("<");
2327                         return type[0];
2328                 } else
2329                         return paramType;
2330         }
2331
2332
2333         // Generate a set of standard classes for import statements
2334         private List<String> getStandardJavaImportClasses() {
2335
2336                 List<String> importClasses = new ArrayList<String>();
2337                 // Add the standard list first
2338                 importClasses.add("java.io.IOException");
2339                 importClasses.add("java.util.List");
2340                 importClasses.add("java.util.ArrayList");
2341                 importClasses.add("iotrmi.Java.IoTRMICall");
2342                 importClasses.add("iotrmi.Java.IoTRMIObject");
2343
2344                 return importClasses;
2345         }
2346
2347
2348         // Generate a set of standard classes for import statements
2349         private List<String> getStandardCplusIncludeClasses() {
2350
2351                 List<String> importClasses = new ArrayList<String>();
2352                 // Add the standard list first
2353                 importClasses.add("<vector>");
2354                 importClasses.add("\"IoTRMICall.hpp\"");
2355                 importClasses.add("\"IoTRMIObject.hpp\"");
2356
2357                 return importClasses;
2358         }
2359
2360
2361         // Generate a set of standard classes for import statements
2362         private List<String> getAllImportClasses(Collection<String> stdImportClasses, Collection<String> importClasses) {
2363
2364                 List<String> allImportClasses = new ArrayList<String>(stdImportClasses);
2365                 // Iterate over the list of import classes
2366                 for (String str : importClasses) {
2367                         if (!stdImportClasses.contains(str)) {
2368                                 stdImportClasses.add(str);
2369                         }
2370                 }
2371
2372                 return allImportClasses;
2373         }
2374
2375
2376
2377         // Generate a set of classes for import statements
2378         private Set<String> getImportClasses(Collection<String> methods, InterfaceDecl intDecl) {
2379
2380                 Set<String> importClasses = new HashSet<String>();
2381                 for (String method : methods) {
2382                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2383                         for (String paramType : methPrmTypes) {
2384
2385                                 String simpleType = getSimpleType(paramType);
2386                                 if (getParamCategory(simpleType) == ParamCategory.NONPRIMITIVES) {
2387                                         importClasses.add(getNonPrimitiveJavaClass(simpleType));
2388                                 }
2389                         }
2390                 }
2391                 return importClasses;
2392         }
2393
2394
2395         // Generate a set of classes for include statements
2396         private Set<String> getIncludeClasses(Collection<String> methods, InterfaceDecl intDecl) {
2397
2398                 Set<String> includeClasses = new HashSet<String>();
2399                 for (String method : methods) {
2400
2401                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2402                         List<String> methParams = intDecl.getMethodParams(method);
2403                         for (int i = 0; i < methPrmTypes.size(); i++) {
2404
2405                                 String simpleType = getSimpleType(methPrmTypes.get(i));
2406                                 String param = methParams.get(i);
2407                                 if (getParamCategory(simpleType) == ParamCategory.NONPRIMITIVES) {
2408                                         includeClasses.add("<" + getNonPrimitiveCplusClass(simpleType) + ">");
2409                                 } else if (getParamCategory(simpleType) == ParamCategory.USERDEFINED) {
2410                                         includeClasses.add("\"" + exchangeParamType(simpleType) + ".hpp\"");
2411                                 } else if (param.contains("[]")) {
2412                                 // Check if this is array for C++; translate into vector
2413                                         includeClasses.add("<vector>");
2414                                 }
2415                         }
2416                 }
2417                 return includeClasses;
2418         }
2419
2420
2421         // Generate a set of callback classes
2422         private Set<String> getCallbackClasses(Collection<String> methods, InterfaceDecl intDecl) {
2423
2424                 Set<String> callbackClasses = new HashSet<String>();
2425                 for (String method : methods) {
2426
2427                         List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2428                         List<String> methParams = intDecl.getMethodParams(method);
2429                         for (int i = 0; i < methPrmTypes.size(); i++) {
2430
2431                                 String type = methPrmTypes.get(i);
2432                                 if (getParamCategory(type) == ParamCategory.USERDEFINED) {
2433                                         callbackClasses.add(type);
2434                                 } else if (getParamCategory(type) == ParamCategory.NONPRIMITIVES) {
2435                                 // Can be a List<...> of callback objects ...
2436                                         String genericType = getTypeOfGeneric(type)[0];
2437                                         if (getParamCategory(type) == ParamCategory.USERDEFINED) {
2438                                                 callbackClasses.add(type);
2439                                         }
2440                                 }
2441                         }
2442                 }
2443                 return callbackClasses;
2444         }
2445
2446
2447         private void printImportStatements(Collection<String> importClasses) {
2448
2449                 for(String cls : importClasses) {
2450                         println("import " + cls + ";");
2451                 }
2452         }
2453
2454
2455         private void printIncludeStatements(Collection<String> includeClasses) {
2456
2457                 for(String cls : includeClasses) {
2458                         println("#include " + cls);
2459                 }
2460         }
2461
2462
2463         // Get the C++ version of a non-primitive type
2464         // e.g. set for Set and map for Map
2465         // Input nonPrimitiveType has to be generics in format
2466         private String[] getTypeOfGeneric(String nonPrimitiveType) {
2467
2468                 // Handle <, >, and , for 2-type generic/template
2469                 String[] substr = nonPrimitiveType.split("<")[1].split(">")[0].split(",");
2470                 return substr;
2471         }
2472
2473
2474         // This helper function strips off array declaration, e.g. D[] becomes D
2475         private String getSimpleIdentifier(String ident) {
2476
2477                 // Handle [ for array declaration
2478                 String substr = ident;
2479                 if (ident.contains("[]")) {
2480                         substr = ident.split("\\[\\]")[0];
2481                 }
2482                 return substr;
2483         }
2484
2485
2486         private String checkAndGetCplusType(String paramType) {
2487
2488                 if (getParamCategory(paramType) == ParamCategory.PRIMITIVES) {
2489                         return convertType(paramType);
2490                 } else if (getParamCategory(paramType) == ParamCategory.NONPRIMITIVES) {
2491
2492                         // Check for generic/template format
2493                         if (paramType.contains("<") && paramType.contains(">")) {
2494
2495                                 String genericClass = getSimpleType(paramType);
2496                                 String[] genericType = getTypeOfGeneric(paramType);
2497                                 String cplusTemplate = null;
2498                                 if (genericType.length == 1) // Generic/template with one type
2499                                         cplusTemplate = getNonPrimitiveCplusClass(genericClass) + 
2500                                                 "<" + convertType(genericType[0]) + ">";
2501                                 else // Generic/template with two types
2502                                         cplusTemplate = getNonPrimitiveCplusClass(genericClass) + 
2503                                                 "<" + convertType(genericType[0]) + "," + convertType(genericType[1]) + ">";
2504                                 return cplusTemplate;
2505                         } else
2506                                 return getNonPrimitiveCplusClass(paramType);
2507                 } else
2508                         // Just return it as is if it's not non-primitives
2509                         return paramType;
2510         }
2511
2512
2513         // Detect array declaration, e.g. int A[],
2514         //              then generate "int A[]" in C++ as "vector<int> A"
2515         private String checkAndGetCplusArray(String paramType, String param) {
2516
2517                 String paramComplete = null;
2518                 // Check for array declaration
2519                 if (param.contains("[]")) {
2520                         paramComplete = "vector<" + paramType + "> " + param.replace("[]","");
2521                 } else
2522                         // Just return it as is if it's not an array
2523                         paramComplete = paramType + " " + param;
2524
2525                 return paramComplete;
2526         }
2527         
2528
2529         // Detect array declaration, e.g. int A[],
2530         //              then generate "int A[]" in C++ as "vector<int> A"
2531         // This method just returns the type
2532         private String checkAndGetCplusArrayType(String paramType) {
2533
2534                 String paramTypeRet = null;
2535                 // Check for array declaration
2536                 if (paramType.contains("[]")) {
2537                         String type = paramType.split("\\[\\]")[0];
2538                         paramTypeRet = checkAndGetCplusType(type) + "[]";
2539                 } else if (paramType.contains("vector")) {
2540                         // Just return it as is if it's not an array
2541                         String type = paramType.split("<")[1].split(">")[0];
2542                         paramTypeRet = checkAndGetCplusType(type) + "[]";
2543                 } else
2544                         paramTypeRet = paramType;
2545
2546                 return paramTypeRet;
2547         }
2548         
2549         
2550         // Detect array declaration, e.g. int A[],
2551         //              then generate "int A[]" in C++ as "vector<int> A"
2552         // This method just returns the type
2553         private String checkAndGetCplusArrayType(String paramType, String param) {
2554
2555                 String paramTypeRet = null;
2556                 // Check for array declaration
2557                 if (param.contains("[]")) {
2558                         paramTypeRet = checkAndGetCplusType(paramType) + "[]";
2559                 } else if (paramType.contains("vector")) {
2560                         // Just return it as is if it's not an array
2561                         String type = paramType.split("<")[1].split(">")[0];
2562                         paramTypeRet = checkAndGetCplusType(type) + "[]";
2563                 } else
2564                         paramTypeRet = paramType;
2565
2566                 return paramTypeRet;
2567         }
2568
2569
2570         // Detect array declaration, e.g. int A[],
2571         //              then generate type "int[]"
2572         private String checkAndGetArray(String paramType, String param) {
2573
2574                 String paramTypeRet = null;
2575                 // Check for array declaration
2576                 if (param.contains("[]")) {
2577                         paramTypeRet = paramType + "[]";
2578                 } else
2579                         // Just return it as is if it's not an array
2580                         paramTypeRet = paramType;
2581
2582                 return paramTypeRet;
2583         }
2584
2585
2586         // Is array or list?
2587         private boolean isArrayOrList(String paramType, String param) {
2588
2589                 // Check for array declaration
2590                 if (isArray(paramType, param))
2591                         return true;
2592                 else if (isList(paramType, param))
2593                         return true;
2594                 else
2595                         return false;
2596         }
2597
2598
2599         // Is array or list?
2600         private boolean isArray(String paramType, String param) {
2601
2602                 // Check for array declaration
2603                 if (param.contains("[]"))
2604                         return true;
2605                 else
2606                         return false;
2607         }
2608
2609
2610         // Is array or list?
2611         private boolean isList(String paramType, String param) {
2612
2613                 // Check for array declaration
2614                 if (paramType.contains("List"))
2615                         return true;
2616                 else
2617                         return false;
2618         }
2619
2620
2621         // Get the right type for a callback object
2622         private String checkAndGetParamClass(String paramType, boolean needPtr) {
2623
2624                 // Check if this is generics
2625                 if(getParamCategory(paramType) == ParamCategory.USERDEFINED) {
2626                         // If true then return with pointer (C++)
2627                         if (needPtr)
2628                                 return exchangeParamType(paramType) + "*";
2629                         else    // Java, so no pointer needed
2630                                 return exchangeParamType(paramType);
2631                 } else
2632                         return paramType;
2633         }
2634
2635
2636         // Returns the other interface for type-checking purposes for USERDEFINED
2637         //              classes based on the information provided in multiple policy files
2638         // e.g. return CameraWithXXX instead of Camera
2639         private String exchangeParamType(String intface) {
2640
2641                 // Param type that's passed is the interface name we need to look for
2642                 //              in the map of interfaces, based on available policy files.
2643                 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2644                 if (decHandler != null) {
2645                 // We've found the required interface policy files
2646                         RequiresDecl reqDecl = (RequiresDecl) decHandler.getRequiresDecl(intface);
2647                         Set<String> setExchInt = reqDecl.getInterfaces();
2648                         if (setExchInt.size() == 1) {
2649                                 Iterator iter = setExchInt.iterator();
2650                                 return (String) iter.next();
2651                         } else {
2652                                 throw new Error("IoTCompiler: Ambiguous stub interfaces: " + setExchInt.toString() + 
2653                                         ". Only one new interface can be declared if the object " + intface +
2654                                         " needs to be passed in as an input parameter!");
2655                         }
2656                 } else {
2657                 // NULL value - this means policy files missing
2658                         throw new Error("IoTCompiler: Parameter type lookup failed for " + intface +
2659                                 "... Please provide the necessary policy files for user-defined types." +
2660                                 " If this is an array please type the brackets after the variable name," +
2661                                 " e.g. \"String str[]\", not \"String[] str\"." +
2662                                 " If this is a Collections (Java) / STL (C++) type, this compiler only" +
2663                                 " supports List/ArrayList (Java) or list (C++).");
2664                 }
2665         }
2666
2667
2668         public static void main(String[] args) throws Exception {
2669
2670                 // If there is no argument or just "--help" or "-h", then invoke printUsage()
2671                 if ((args[0].equals("-help") ||
2672                          args[0].equals("--help")||
2673                          args[0].equals("-h"))   ||
2674                         (args.length == 0)) {
2675
2676                         IoTCompiler.printUsage();
2677
2678                 } else if (args.length > 1) {
2679
2680                         IoTCompiler comp = new IoTCompiler();
2681                         int i = 0;                              
2682                         do {
2683                                 // Parse main policy file
2684                                 ParseNode pnPol = IoTCompiler.parseFile(args[i]);
2685                                 // Parse "requires" policy file
2686                                 ParseNode pnReq = IoTCompiler.parseFile(args[i+1]);
2687                                 // Get interface name
2688                                 String intface = ParseTreeHandler.getOrigIntface(pnPol);
2689                                 comp.setDataStructures(intface, pnPol, pnReq);
2690                                 comp.getMethodsForIntface(intface);
2691                                 i = i + 2;
2692                         // 1) Check if this is the last option before "-java" or "-cplus"
2693                         // 2) Check if this is really the last option (no "-java" or "-cplus")
2694                         } while(!args[i].equals("-java") &&
2695                                         !args[i].equals("-cplus") &&
2696                                         (i < args.length));
2697
2698                         // Generate everything if we don't see "-java" or "-cplus"
2699                         if (i == args.length) {
2700                                 comp.generateJavaLocalInterfaces();
2701                                 comp.generateJavaInterfaces();
2702                                 comp.generateJavaStubClasses();
2703                                 comp.generateJavaCallbackStubClasses();
2704                                 comp.generateJavaSkeletonClass();
2705                                 comp.generateJavaCallbackSkeletonClass();
2706                                 comp.generateCplusLocalInterfaces();
2707                                 comp.generateCPlusInterfaces();
2708                                 comp.generateCPlusStubClasses();
2709                                 comp.generateCPlusCallbackStubClasses();
2710                                 comp.generateCplusSkeletonClass();
2711                                 comp.generateCplusCallbackSkeletonClass();
2712                         } else {
2713                         // Check other options
2714                                 while(i < args.length) {
2715                                         // Error checking
2716                                         if (!args[i].equals("-java") &&
2717                                                 !args[i].equals("-cplus")) {
2718                                                 throw new Error("IoTCompiler: ERROR - unrecognized command line option: " + args[i]);
2719                                         } else {
2720                                                 if (i + 1 < args.length) {
2721                                                         comp.setDirectory(args[i+1]);
2722                                                 } else
2723                                                         throw new Error("IoTCompiler: ERROR - please provide <directory> after option: " + args[i]);
2724
2725                                                 if (args[i].equals("-java")) {
2726                                                         comp.generateJavaLocalInterfaces();
2727                                                         comp.generateJavaInterfaces();
2728                                                         comp.generateJavaStubClasses();
2729                                                         comp.generateJavaCallbackStubClasses();
2730                                                         comp.generateJavaSkeletonClass();
2731                                                         comp.generateJavaCallbackSkeletonClass();
2732                                                 } else {
2733                                                         comp.generateCplusLocalInterfaces();
2734                                                         comp.generateCPlusInterfaces();
2735                                                         comp.generateCPlusStubClasses();
2736                                                         comp.generateCPlusCallbackStubClasses();
2737                                                         comp.generateCplusSkeletonClass();
2738                                                         comp.generateCplusCallbackSkeletonClass();
2739                                                 }
2740                                         }
2741                                         i = i + 2;
2742                                 }
2743                         }
2744                 } else {
2745                 // Need to at least have exactly 2 parameters, i.e. main policy file and requires file
2746                         IoTCompiler.printUsage();
2747                         throw new Error("IoTCompiler: At least two arguments (main and requires policy files) have to be provided!");
2748                 }
2749         }
2750 }
2751
2752
2753
2754