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