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