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