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