3 import java_cup.runtime.ComplexSymbolFactory;
4 import java_cup.runtime.ScannerBuffer;
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;
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;
30 import iotrmi.Java.IoTRMITypes;
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.
38 * @author Rahmadi Trimananda <rahmadi.trimananda @ uci.edu>
42 public class IoTCompiler {
47 // Maps multiple interfaces to multiple objects of ParseTreeHandler
48 private Map<String,ParseTreeHandler> mapIntfacePTH;
49 private Map<String,DeclarationHandler> mapIntDeclHand;
50 private Map<String,Map<String,Set<String>>> mapInt2NewInts;
51 private Map<String,String> mapInt2NewIntName;
52 private Map<String,List<String>> mapInt2Drv;
53 // Data structure to store our types (primitives and non-primitives) for compilation
54 private Map<String,String> mapPrimitives;
55 private Map<String,String> mapNonPrimitivesJava;
56 private Map<String,String> mapNonPrimitivesCplus;
57 // Other data structures
58 private Map<String,Integer> mapIntfaceObjId; // Maps interface name to object Id
59 private Map<String,Integer> mapNewIntfaceObjId; // Maps new interface name to its object Id (keep track of stubs)
60 private PrintWriter pw;
62 private String subdir;
63 private Map<String,Integer> mapPortCount; // Counter for ports
64 private static int portCount = 0;
65 private static int countObjId = 1; // Always increment object Id for a new stub/skeleton
66 private String mainClass;
67 private String controllerClass;
73 private final static String OUTPUT_DIRECTORY = "output_files";
74 private final static String INTERFACES_DIRECTORY = "interfaces";
75 private final static String VIRTUALS_DIRECTORY = "virtuals";
76 private final static String DRIVERS_DIRECTORY = "drivers";
77 private final static String CONTROLLER_DIRECTORY = "controller";
78 private final static String CODE_PREFIX = "iotcode";
79 private final static String INTERFACE_PACKAGE = "iotcode.interfaces";
82 private enum ParamCategory {
84 PRIMITIVES, // All the primitive types, e.g. byte, short, int, long, etc.
85 NONPRIMITIVES, // Non-primitive types, e.g. Set, Map, List, etc.
87 STRUCT, // Struct type
88 USERDEFINED // Assumed as driver classes
95 public IoTCompiler() {
97 mapIntfacePTH = new HashMap<String,ParseTreeHandler>();
98 mapIntDeclHand = new HashMap<String,DeclarationHandler>();
99 mapInt2NewInts = new HashMap<String,Map<String,Set<String>>>();
100 mapInt2NewIntName = new HashMap<String,String>();
101 mapInt2Drv = new HashMap<String,List<String>>();
102 mapIntfaceObjId = new HashMap<String,Integer>();
103 mapNewIntfaceObjId = new HashMap<String,Integer>();
104 mapPrimitives = new HashMap<String,String>();
105 arraysToMap(mapPrimitives, IoTRMITypes.primitivesJava, IoTRMITypes.primitivesCplus);
106 mapNonPrimitivesJava = new HashMap<String,String>();
107 arraysToMap(mapNonPrimitivesJava, IoTRMITypes.nonPrimitivesJava, IoTRMITypes.nonPrimitiveJavaLibs);
108 mapNonPrimitivesCplus = new HashMap<String,String>();
109 arraysToMap(mapNonPrimitivesCplus, IoTRMITypes.nonPrimitivesJava, IoTRMITypes.nonPrimitivesCplus);
110 mapPortCount = new HashMap<String,Integer>();
112 dir = OUTPUT_DIRECTORY;
115 controllerClass = null;
120 * setDriverClass() sets the name of the driver class.
122 public void setDriverClass(String intface, String driverClass) {
124 List<String> drvList = mapInt2Drv.get(intface);
126 drvList = new ArrayList<String>();
127 drvList.add(driverClass);
128 mapInt2Drv.put(intface, drvList);
133 * setControllerClass() sets the name of the controller class.
135 public void setControllerClass(String _controllerClass) {
137 controllerClass = _controllerClass;
142 * setDataStructures() sets parse tree and other data structures based on policy files.
144 * It also generates parse tree (ParseTreeHandler) and
145 * copies useful information from parse tree into
146 * InterfaceDecl, CapabilityDecl, and RequiresDecl
148 * Additionally, the data structure handles are
149 * returned from tree-parsing for further process.
151 public void setDataStructures(String origInt, ParseNode pnPol, ParseNode pnReq) {
153 ParseTreeHandler ptHandler = new ParseTreeHandler(origInt, pnPol, pnReq);
154 DeclarationHandler decHandler = new DeclarationHandler();
155 // Process ParseNode and generate Declaration objects
157 ptHandler.processInterfaceDecl();
158 InterfaceDecl intDecl = ptHandler.getInterfaceDecl();
159 decHandler.addInterfaceDecl(origInt, intDecl);
161 ptHandler.processCapabilityDecl();
162 CapabilityDecl capDecl = ptHandler.getCapabilityDecl();
163 decHandler.addCapabilityDecl(origInt, capDecl);
165 ptHandler.processRequiresDecl();
166 RequiresDecl reqDecl = ptHandler.getRequiresDecl();
167 decHandler.addRequiresDecl(origInt, reqDecl);
169 ptHandler.processEnumDecl();
170 EnumDecl enumDecl = ptHandler.getEnumDecl();
171 decHandler.addEnumDecl(origInt, enumDecl);
173 ptHandler.processStructDecl();
174 StructDecl structDecl = ptHandler.getStructDecl();
175 decHandler.addStructDecl(origInt, structDecl);
177 mapIntfacePTH.put(origInt, ptHandler);
178 mapIntDeclHand.put(origInt, decHandler);
179 // Set object Id counter to 0 for each interface
180 mapIntfaceObjId.put(origInt, countObjId++);
185 * setObjectId() updates the object Id. This option is useful
186 * when the stub/skeleton are also used in other apps, so that
187 * we can set a single object Id for the stub/skeleton.
189 private void setObjectId(String intface, String objectId) {
191 mapIntfaceObjId.put(intface, Integer.parseInt(objectId));
196 * getMethodsForIntface() reads for methods in the data structure
198 * It is going to give list of methods for a certain interface
199 * based on the declaration of capabilities.
201 public void getMethodsForIntface(String origInt) {
203 ParseTreeHandler ptHandler = mapIntfacePTH.get(origInt);
204 Map<String,Set<String>> mapNewIntMethods = new HashMap<String,Set<String>>();
205 // Get set of new interfaces, e.g. CameraWithCaptureAndData
206 // Generate this new interface with all the methods it needs
207 // from different capabilities it declares
208 DeclarationHandler decHandler = mapIntDeclHand.get(origInt);
209 RequiresDecl reqDecl = (RequiresDecl) decHandler.getRequiresDecl(origInt);
210 Set<String> setIntfaces = reqDecl.getInterfaces();
211 for (String strInt : setIntfaces) {
213 // Initialize a set of methods
214 Set<String> setMethods = new HashSet<String>();
215 // Get list of capabilities, e.g. ImageCapture, VideoRecording, etc.
216 List<String> listCapab = reqDecl.getCapabList(strInt);
217 for (String strCap : listCapab) {
219 // Get list of methods for each capability
220 CapabilityDecl capDecl = (CapabilityDecl) decHandler.getCapabilityDecl(origInt);
221 List<String> listCapabMeth = capDecl.getMethods(strCap);
222 for (String strMeth : listCapabMeth) {
224 // Add methods into setMethods
225 // This is to also handle redundancies (say two capabilities
226 // share the same methods)
227 setMethods.add(strMeth);
230 // Add interface and methods information into map
231 mapNewIntMethods.put(strInt, setMethods);
232 // Map new interface method name to the original interface
233 // TODO: perhaps need to check in the future if we have more than 1 stub interface for one original interface
234 mapInt2NewIntName.put(origInt, strInt);
235 if (mainClass == null) // Take the first class as the main class (whichever is placed first in the order of compilation files)
238 // Map the map of interface-methods to the original interface
239 mapInt2NewInts.put(origInt, mapNewIntMethods);
248 * HELPER: writeMethodJavaLocalInterface() writes the method of the local interface
250 private void writeMethodJavaLocalInterface(Collection<String> methods, InterfaceDecl intDecl) {
252 for (String method : methods) {
254 List<String> methParams = intDecl.getMethodParams(method);
255 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
256 print("public " + intDecl.getMethodType(method) + " " +
257 intDecl.getMethodId(method) + "(");
258 for (int i = 0; i < methParams.size(); i++) {
259 // Check for params with driver class types and exchange it
260 // with its remote interface
261 String paramType = checkAndGetParamClass(methPrmTypes.get(i));
262 print(paramType + " " + methParams.get(i));
263 // Check if this is the last element (don't print a comma)
264 if (i != methParams.size() - 1) {
274 * HELPER: writeMethodJavaInterface() writes the method of the interface
276 private void writeMethodJavaInterface(Collection<String> methods, InterfaceDecl intDecl) {
278 for (String method : methods) {
280 List<String> methParams = intDecl.getMethodParams(method);
281 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
282 print("public " + intDecl.getMethodType(method) + " " +
283 intDecl.getMethodId(method) + "(");
284 for (int i = 0; i < methParams.size(); i++) {
285 // Check for params with driver class types and exchange it
286 // with its remote interface
287 String paramType = methPrmTypes.get(i);
288 print(paramType + " " + methParams.get(i));
289 // Check if this is the last element (don't print a comma)
290 if (i != methParams.size() - 1) {
300 * HELPER: generateEnumJava() writes the enumeration declaration
302 private void generateEnumJava() throws IOException {
304 // Create a new directory
305 createDirectory(dir);
306 String path = createDirectories(dir, INTERFACES_DIRECTORY);
307 for (String intface : mapIntfacePTH.keySet()) {
308 // Get the right EnumDecl
309 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
310 EnumDecl enumDecl = (EnumDecl) decHandler.getEnumDecl(intface);
311 Set<String> enumTypes = enumDecl.getEnumDeclarations();
312 // Iterate over enum declarations
313 for (String enType : enumTypes) {
314 // Open a new file to write into
315 FileWriter fw = new FileWriter(path + "/" + enType + ".java");
316 pw = new PrintWriter(new BufferedWriter(fw));
317 println("package " + INTERFACE_PACKAGE + ";\n");
318 println("public enum " + enType + " {");
319 List<String> enumMembers = enumDecl.getMembers(enType);
320 for (int i = 0; i < enumMembers.size(); i++) {
322 String member = enumMembers.get(i);
324 // Check if this is the last element (don't print a comma)
325 if (i != enumMembers.size() - 1)
332 System.out.println("IoTCompiler: Generated enum class " + enType + ".java...");
339 * HELPER: generateStructJava() writes the struct declaration
341 private void generateStructJava() throws IOException {
343 // Create a new directory
344 createDirectory(dir);
345 String path = createDirectories(dir, INTERFACES_DIRECTORY);
346 for (String intface : mapIntfacePTH.keySet()) {
347 // Get the right StructDecl
348 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
349 StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
350 List<String> structTypes = structDecl.getStructTypes();
351 // Iterate over enum declarations
352 for (String stType : structTypes) {
353 // Open a new file to write into
354 FileWriter fw = new FileWriter(path + "/" + stType + ".java");
355 pw = new PrintWriter(new BufferedWriter(fw));
356 println("package " + INTERFACE_PACKAGE + ";\n");
357 println("public class " + stType + " {");
358 List<String> structMemberTypes = structDecl.getMemberTypes(stType);
359 List<String> structMembers = structDecl.getMembers(stType);
360 for (int i = 0; i < structMembers.size(); i++) {
362 String memberType = structMemberTypes.get(i);
363 String member = structMembers.get(i);
364 println("public static " + memberType + " " + member + ";");
368 System.out.println("IoTCompiler: Generated struct class " + stType + ".java...");
375 * generateJavaLocalInterface() writes the local interface and provides type-checking.
377 * It needs to rewrite and exchange USERDEFINED types in input parameters of stub
378 * and original interfaces, e.g. exchange Camera and CameraWithVideoAndRecording.
379 * The local interface has to be the input parameter for the stub and the stub
380 * interface has to be the input parameter for the local class.
382 public void generateJavaLocalInterfaces() throws IOException {
384 // Create a new directory
385 createDirectory(dir);
386 String path = createDirectories(dir, INTERFACES_DIRECTORY);
387 for (String intface : mapIntfacePTH.keySet()) {
388 // Open a new file to write into
389 FileWriter fw = new FileWriter(path + "/" + intface + ".java");
390 pw = new PrintWriter(new BufferedWriter(fw));
391 // Pass in set of methods and get import classes
392 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
393 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
394 List<String> methods = intDecl.getMethods();
395 Set<String> importClasses = getImportClasses(methods, intDecl);
396 List<String> stdImportClasses = getStandardJavaIntfaceImportClasses();
397 List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
398 println("package " + INTERFACE_PACKAGE + ";\n");
399 printImportStatements(allImportClasses);
400 // Write interface header
402 println("public interface " + intface + " {");
404 writeMethodJavaLocalInterface(methods, intDecl);
407 System.out.println("IoTCompiler: Generated local interface " + intface + ".java...");
413 * HELPER: updateIntfaceObjIdMap() updates the mapping between new interface and object Id
415 private void updateIntfaceObjIdMap(String intface, String newIntface) {
417 // We are assuming that we only generate one stub per one skeleton at this point @Feb 2017
418 Integer objId = mapIntfaceObjId.get(intface);
419 mapNewIntfaceObjId.put(newIntface, objId);
424 * generateJavaInterfaces() generate stub interfaces based on the methods list in Java
426 public void generateJavaInterfaces() throws IOException {
428 // Create a new directory
429 String path = createDirectories(dir, subdir);
430 path = createDirectories(dir + "/" + subdir, INTERFACES_DIRECTORY);
431 for (String intface : mapIntfacePTH.keySet()) {
433 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
434 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
436 // Open a new file to write into
437 String newIntface = intMeth.getKey();
438 FileWriter fw = new FileWriter(path + "/" + newIntface + ".java");
439 pw = new PrintWriter(new BufferedWriter(fw));
440 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
441 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
442 // Pass in set of methods and get import classes
443 Set<String> methods = intMeth.getValue();
444 Set<String> importClasses = getImportClasses(methods, intDecl);
445 List<String> stdImportClasses = getStandardJavaIntfaceImportClasses();
446 List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
447 println("package " + INTERFACE_PACKAGE + ";\n");
448 printImportStatements(allImportClasses);
449 // Write interface header
451 println("public interface " + newIntface + " {\n");
452 updateIntfaceObjIdMap(intface, newIntface);
454 writeMethodJavaInterface(methods, intDecl);
457 System.out.println("IoTCompiler: Generated interface " + newIntface + ".java...");
464 * HELPER: writePropertiesJavaPermission() writes the permission in properties
466 private void writePropertiesJavaPermission(String intface, InterfaceDecl intDecl) {
468 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
469 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
470 String newIntface = intMeth.getKey();
471 int newObjectId = getNewIntfaceObjectId(newIntface);
472 Set<String> methodIds = intMeth.getValue();
473 print("private static Integer[] object" + newObjectId + "Permission = { ");
475 for (String methodId : methodIds) {
476 int methodNumId = intDecl.getMethodNumId(methodId);
477 print(Integer.toString(methodNumId));
478 // Check if this is the last element (don't print a comma)
479 if (i != methodIds.size() - 1) {
485 println("private static List<Integer> set" + newObjectId + "Allowed;");
491 * HELPER: writePropertiesJavaStub() writes the properties of the stub class
493 private void writePropertiesJavaStub(String intface, Set<String> methods, InterfaceDecl intDecl) {
496 Integer objId = mapIntfaceObjId.get(intface);
497 println("private int objectId = " + objId + ";");
498 println("private IoTRMIComm rmiComm;");
499 // Write the list of AtomicBoolean variables
500 println("// Synchronization variables");
501 for (String method : methods) {
502 // Generate AtomicBooleans for methods that have return values
503 String returnType = intDecl.getMethodType(method);
504 int methodNumId = intDecl.getMethodNumId(method);
505 if (!returnType.equals("void")) {
506 println("private AtomicBoolean retValueReceived" + methodNumId + " = new AtomicBoolean(false);");
514 * HELPER: writeConstructorJavaPermission() writes the permission in constructor
516 private void writeConstructorJavaPermission(String intface) {
518 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
519 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
520 String newIntface = intMeth.getKey();
521 int newObjectId = getNewIntfaceObjectId(newIntface);
522 println("set" + newObjectId + "Allowed = new ArrayList<Integer>(Arrays.asList(object" + newObjectId +"Permission));");
528 * HELPER: writeConstructorJavaStub() writes the constructor of the stub class
530 private void writeConstructorJavaStub(String intface, String newStubClass, Set<String> methods, InterfaceDecl intDecl) {
532 println("public " + newStubClass + "(int _localPortSend, int _localPortRecv, int _portSend, int _portRecv, String _skeletonAddress, int _rev) throws Exception {");
533 println("if (_localPortSend != 0 && _localPortRecv != 0) {");
534 println("rmiComm = new IoTRMICommClient(_localPortSend, _localPortRecv, _portSend, _portRecv, _skeletonAddress, _rev);");
537 println("rmiComm = new IoTRMICommClient(_portSend, _portRecv, _skeletonAddress, _rev);");
539 // Register the AtomicBoolean variables
540 for (String method : methods) {
541 // Generate AtomicBooleans for methods that have return values
542 String returnType = intDecl.getMethodType(method);
543 int methodNumId = intDecl.getMethodNumId(method);
544 if (!returnType.equals("void")) {
545 println("rmiComm.registerStub(objectId, " + methodNumId + ", retValueReceived" + methodNumId + ");");
548 println("IoTRMIUtil.mapStub.put(objectId, this);");
554 * HELPER: writeCallbackConstructorJavaStub() writes the callback constructor of the stub class
556 private void writeCallbackConstructorJavaStub(String intface, String newStubClass, Set<String> methods, InterfaceDecl intDecl) {
558 println("public " + newStubClass + "(IoTRMIComm _rmiComm, int _objectId) throws Exception {");
559 println("rmiComm = _rmiComm;");
560 println("objectId = _objectId;");
561 // Register the AtomicBoolean variables
562 for (String method : methods) {
563 // Generate AtomicBooleans for methods that have return values
564 String returnType = intDecl.getMethodType(method);
565 int methodNumId = intDecl.getMethodNumId(method);
566 if (!returnType.equals("void")) {
567 println("rmiComm.registerStub(objectId, " + methodNumId + ", retValueReceived" + methodNumId + ");");
575 * HELPER: getPortCount() gets port count for different stubs and skeletons
577 private int getPortCount(String intface) {
579 if (!mapPortCount.containsKey(intface))
580 mapPortCount.put(intface, portCount++);
581 return mapPortCount.get(intface);
586 * HELPER: checkAndWriteEnumTypeJavaStub() writes the enum type (convert from enum to int)
588 private void checkAndWriteEnumTypeJavaStub(List<String> methParams, List<String> methPrmTypes) {
590 // Iterate and find enum declarations
591 for (int i = 0; i < methParams.size(); i++) {
592 String paramType = methPrmTypes.get(i);
593 String param = methParams.get(i);
594 String simpleType = getGenericType(paramType);
595 if (isEnumClass(simpleType)) {
596 // Check if this is enum type
597 if (isArray(param)) { // An array
598 println("int len" + i + " = " + getSimpleIdentifier(param) + ".length;");
599 println("int paramEnum" + i + "[] = new int[len" + i + "];");
600 println("for (int i = 0; i < len" + i + "; i++) {");
601 println("paramEnum" + i + "[i] = " + getSimpleIdentifier(param) + "[i].ordinal();");
603 } else if (isList(paramType)) { // A list
604 println("int len" + i + " = " + getSimpleIdentifier(param) + ".size();");
605 println("int paramEnum" + i + "[] = new int[len" + i + "];");
606 println("for (int i = 0; i < len" + i + "; i++) {");
607 println("paramEnum" + i + "[i] = " + getSimpleIdentifier(param) + ".get(i).ordinal();");
609 } else { // Just one element
610 println("int paramEnum" + i + "[] = new int[1];");
611 println("paramEnum" + i + "[0] = " + param + ".ordinal();");
619 * HELPER: checkAndWriteEnumRetTypeJavaStub() writes the enum return type (convert from enum to int)
621 private void checkAndWriteEnumRetTypeJavaStub(String retType, String method, InterfaceDecl intDecl) {
623 // Write the wait-for-return-value part
624 writeWaitForReturnValueJava(method, intDecl, "Object retObj = rmiComm.getReturnValue(retType, null);");
625 // Strips off array "[]" for return type
626 String pureType = getSimpleArrayType(getGenericType(retType));
627 // Take the inner type of generic
628 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
629 pureType = getGenericType(retType);
630 if (isEnumClass(pureType)) {
631 // Check if this is enum type
633 println("int[] retEnum = (int[]) retObj;");
634 println(pureType + "[] enumVals = " + pureType + ".values();");
635 if (isArray(retType)) { // An array
636 println("int retLen = retEnum.length;");
637 println(pureType + "[] enumRetVal = new " + pureType + "[retLen];");
638 println("for (int i = 0; i < retLen; i++) {");
639 println("enumRetVal[i] = enumVals[retEnum[i]];");
641 } else if (isList(retType)) { // A list
642 println("int retLen = retEnum.length;");
643 println("List<" + pureType + "> enumRetVal = new ArrayList<" + pureType + ">();");
644 println("for (int i = 0; i < retLen; i++) {");
645 println("enumRetVal.add(enumVals[retEnum[i]]);");
647 } else { // Just one element
648 println(pureType + " enumRetVal = enumVals[retEnum[0]];");
650 println("return enumRetVal;");
656 * HELPER: checkAndWriteStructSetupJavaStub() writes the struct type setup
658 private void checkAndWriteStructSetupJavaStub(List<String> methParams, List<String> methPrmTypes,
659 InterfaceDecl intDecl, String method) {
661 // Iterate and find struct declarations
662 for (int i = 0; i < methParams.size(); i++) {
663 String paramType = methPrmTypes.get(i);
664 String param = methParams.get(i);
665 String simpleType = getGenericType(paramType);
666 if (isStructClass(simpleType)) {
667 // Check if this is enum type
668 int methodNumId = intDecl.getMethodNumId(method);
669 String helperMethod = methodNumId + "struct" + i;
670 println("int methodIdStruct" + i + " = " + intDecl.getHelperMethodNumId(helperMethod) + ";");
671 println("Class<?>[] paramClsStruct" + i + " = new Class<?>[] { int.class };");
672 if (isArray(param)) { // An array
673 println("Object[] paramObjStruct" + i + " = new Object[] { " + getSimpleArrayType(param) + ".length };");
674 } else if (isList(paramType)) { // A list
675 println("Object[] paramObjStruct" + i + " = new Object[] { " + getSimpleArrayType(param) + ".size() };");
676 } else { // Just one element
677 println("Object[] paramObjStruct" + i + " = new Object[] { new Integer(1) };");
679 println("rmiComm.remoteCall(objectId, methodIdStruct" + i +
680 ", paramClsStruct" + i + ", paramObjStruct" + i + ");\n");
687 * HELPER: isStructPresent() checks presence of struct
689 private boolean isStructPresent(List<String> methParams, List<String> methPrmTypes) {
691 // Iterate and find enum declarations
692 for (int i = 0; i < methParams.size(); i++) {
693 String paramType = methPrmTypes.get(i);
694 String param = methParams.get(i);
695 String simpleType = getGenericType(paramType);
696 if (isStructClass(simpleType))
704 * HELPER: writeLengthStructParamClassJavaStub() writes lengths of parameters
706 private void writeLengthStructParamClassJavaStub(List<String> methParams, List<String> methPrmTypes) {
708 // Iterate and find struct declarations - count number of params
709 for (int i = 0; i < methParams.size(); i++) {
710 String paramType = methPrmTypes.get(i);
711 String param = methParams.get(i);
712 String simpleType = getGenericType(paramType);
713 if (isStructClass(simpleType)) {
714 int members = getNumOfMembers(simpleType);
715 if (isArray(param)) { // An array
716 String structLen = getSimpleArrayType(param) + ".length";
717 print(members + "*" + structLen);
718 } else if (isList(paramType)) { // A list
719 String structLen = getSimpleArrayType(param) + ".size()";
720 print(members + "*" + structLen);
722 print(Integer.toString(members));
725 if (i != methParams.size() - 1) {
733 * HELPER: writeStructMembersJavaStub() writes parameters of struct
735 private void writeStructMembersJavaStub(String simpleType, String paramType, String param) {
737 // Get the struct declaration for this struct and generate initialization code
738 StructDecl structDecl = getStructDecl(simpleType);
739 List<String> memTypes = structDecl.getMemberTypes(simpleType);
740 List<String> members = structDecl.getMembers(simpleType);
741 if (isArray(param)) { // An array
742 println("for(int i = 0; i < " + getSimpleIdentifier(param) + ".length; i++) {");
743 for (int i = 0; i < members.size(); i++) {
744 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
745 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
746 print("paramObj[pos++] = " + getSimpleIdentifier(param) + "[i].");
747 print(getSimpleIdentifier(members.get(i)));
751 } else if (isList(paramType)) { // A list
752 println("for(int i = 0; i < " + getSimpleIdentifier(param) + ".size(); i++) {");
753 for (int i = 0; i < members.size(); i++) {
754 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
755 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
756 print("paramObj[pos++] = " + getSimpleIdentifier(param) + ".get(i).");
757 print(getSimpleIdentifier(members.get(i)));
761 } else { // Just one struct element
762 for (int i = 0; i < members.size(); i++) {
763 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
764 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
765 print("paramObj[pos++] = " + getSimpleIdentifier(param) + ".");
766 print(getSimpleIdentifier(members.get(i)));
774 * HELPER: writeStructParamClassJavaStub() writes parameters if struct is present
776 private void writeStructParamClassJavaStub(List<String> methParams, List<String> methPrmTypes, Set<String> callbackType) {
778 print("int paramLen = ");
779 writeLengthStructParamClassJavaStub(methParams, methPrmTypes);
781 println("Object[] paramObj = new Object[paramLen];");
782 println("Class<?>[] paramCls = new Class<?>[paramLen];");
783 println("int pos = 0;");
784 // Iterate again over the parameters
785 for (int i = 0; i < methParams.size(); i++) {
786 String paramType = methPrmTypes.get(i);
787 String param = methParams.get(i);
788 String simpleType = getGenericType(paramType);
789 if (isStructClass(simpleType)) {
790 writeStructMembersJavaStub(simpleType, paramType, param);
791 } else if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
792 println("paramCls[pos] = int[].class;");
793 println("paramObj[pos++] = objIdSent" + i + ";");
795 String prmType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
796 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
797 print("paramObj[pos++] = ");
798 print(getEnumParam(methPrmTypes.get(i), getSimpleIdentifier(methParams.get(i)), i));
807 * HELPER: writeStructRetMembersJavaStub() writes parameters of struct for return statement
809 private void writeStructRetMembersJavaStub(String simpleType, String retType) {
811 // Get the struct declaration for this struct and generate initialization code
812 StructDecl structDecl = getStructDecl(simpleType);
813 List<String> memTypes = structDecl.getMemberTypes(simpleType);
814 List<String> members = structDecl.getMembers(simpleType);
815 if (isArrayOrList(retType, retType)) { // An array or list
816 println("for(int i = 0; i < retLen; i++) {");
818 if (isArray(retType)) { // An array
819 for (int i = 0; i < members.size(); i++) {
820 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
821 print("structRet[i]." + getSimpleIdentifier(members.get(i)));
822 println(" = (" + getSimpleType(getEnumType(prmType)) + ") retActualObj[retObjPos++];");
825 } else if (isList(retType)) { // A list
826 println(simpleType + " structRetMem = new " + simpleType + "();");
827 for (int i = 0; i < members.size(); i++) {
828 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
829 print("structRetMem." + getSimpleIdentifier(members.get(i)));
830 println(" = (" + getSimpleType(getEnumType(prmType)) + ") retActualObj[retObjPos++];");
832 println("structRet.add(structRetMem);");
834 } else { // Just one struct element
835 for (int i = 0; i < members.size(); i++) {
836 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
837 print("structRet." + getSimpleIdentifier(members.get(i)));
838 println(" = (" + getSimpleType(getEnumType(prmType)) + ") retActualObj[retObjPos++];");
841 println("return structRet;");
846 * HELPER: writeStructReturnJavaStub() writes parameters if struct is present for return statement
848 private void writeStructReturnJavaStub(String simpleType, String retType, String method, InterfaceDecl intDecl) {
850 // Handle the returned struct size
851 writeWaitForReturnValueJava(method, intDecl, "Object retObj = rmiComm.getReturnValue(retType, null);");
852 // Minimum retLen is 1 if this is a single struct object
853 println("int retLen = (int) retObj;");
854 int numMem = getNumOfMembers(simpleType);
855 println("Class<?>[] retCls = new Class<?>[" + numMem + "*retLen];");
856 println("Class<?>[] retClsVal = new Class<?>[" + numMem + "*retLen];");
857 println("int retPos = 0;");
858 // Get the struct declaration for this struct and generate initialization code
859 StructDecl structDecl = getStructDecl(simpleType);
860 List<String> memTypes = structDecl.getMemberTypes(simpleType);
861 List<String> members = structDecl.getMembers(simpleType);
862 if (isArrayOrList(retType, retType)) { // An array or list
863 println("for(int i = 0; i < retLen; i++) {");
864 for (int i = 0; i < members.size(); i++) {
865 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
866 println("retCls[retPos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
867 println("retClsVal[retPos++] = null;");
870 } else { // Just one struct element
871 for (int i = 0; i < members.size(); i++) {
872 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
873 println("retCls[retPos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
874 println("retClsVal[retPos++] = null;");
877 // Handle the actual returned struct
878 writeWaitForReturnValueJava(method, intDecl, "Object[] retActualObj = rmiComm.getStructObjects(retCls, retClsVal);");
879 if (isArray(retType)) { // An array
880 println(simpleType + "[] structRet = new " + simpleType + "[retLen];");
881 println("for(int i = 0; i < retLen; i++) {");
882 println("structRet[i] = new " + simpleType + "();");
884 } else if (isList(retType)) { // A list
885 println("List<" + simpleType + "> structRet = new ArrayList<" + simpleType + ">();");
887 println(simpleType + " structRet = new " + simpleType + "();");
888 println("int retObjPos = 0;");
889 writeStructRetMembersJavaStub(simpleType, retType);
894 * HELPER: writeWaitForReturnValueJava() writes the synchronization part for return values
896 private void writeWaitForReturnValueJava(String method, InterfaceDecl intDecl, String getReturnValue) {
898 println("// Waiting for return value");
899 int methodNumId = intDecl.getMethodNumId(method);
900 println("while (!retValueReceived" + methodNumId + ".get());");
901 println(getReturnValue);
902 println("retValueReceived" + methodNumId + ".set(false);");
903 println("rmiComm.setGetReturnBytes();\n");
908 * HELPER: writeStdMethodBodyJavaStub() writes the standard method body in the stub class
910 private void writeStdMethodBodyJavaStub(InterfaceDecl intDecl, List<String> methParams,
911 List<String> methPrmTypes, String method, Set<String> callbackType) {
913 checkAndWriteStructSetupJavaStub(methParams, methPrmTypes, intDecl, method);
914 println("int methodId = " + intDecl.getMethodNumId(method) + ";");
915 String retType = intDecl.getMethodType(method);
916 println("Class<?> retType = " + getSimpleType(getStructType(getEnumType(retType))) + ".class;");
917 checkAndWriteEnumTypeJavaStub(methParams, methPrmTypes);
918 // Generate array of parameter types
919 if (isStructPresent(methParams, methPrmTypes)) {
920 writeStructParamClassJavaStub(methParams, methPrmTypes, callbackType);
922 print("Class<?>[] paramCls = new Class<?>[] { ");
923 for (int i = 0; i < methParams.size(); i++) {
924 String prmType = methPrmTypes.get(i);
925 if (checkCallbackType(prmType, callbackType)) { // Check if this has callback object
926 print("int[].class");
927 } else { // Generate normal classes if it's not a callback object
928 String paramType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
929 print(getSimpleType(getEnumType(paramType)) + ".class");
931 // Check if this is the last element (don't print a comma)
932 if (i != methParams.size() - 1) {
937 // Generate array of parameter objects
938 print("Object[] paramObj = new Object[] { ");
939 for (int i = 0; i < methParams.size(); i++) {
940 String paramType = methPrmTypes.get(i);
941 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
942 print("objIdSent" + i);
944 print(getEnumParam(methPrmTypes.get(i), getSimpleIdentifier(methParams.get(i)), i));
945 // Check if this is the last element (don't print a comma)
946 if (i != methParams.size() - 1) {
952 // Send method call first and wait for return value separately
953 println("rmiComm.remoteCall(objectId, methodId, paramCls, paramObj);");
954 // Check if this is "void"
955 if (!retType.equals("void")) { // We do have a return value
956 // Generate array of parameter types
957 if (isStructClass(getGenericType(getSimpleArrayType(retType)))) {
958 writeStructReturnJavaStub(getGenericType(getSimpleArrayType(retType)), retType, method, intDecl);
960 // This is an enum type
961 if (getParamCategory(getGenericType(getSimpleArrayType(retType))) == ParamCategory.ENUM) {
962 //println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
963 checkAndWriteEnumRetTypeJavaStub(retType, method, intDecl);
964 } else if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES) {
965 // Check if the return value NONPRIMITIVES
966 String retGenValType = getGenericType(retType);
967 println("Class<?> retGenValType = " + retGenValType + ".class;");
968 writeWaitForReturnValueJava(method, intDecl, "Object retObj = rmiComm.getReturnValue(retType, retGenValType);");
969 println("return (" + retType + ")retObj;");
971 writeWaitForReturnValueJava(method, intDecl, "Object retObj = rmiComm.getReturnValue(retType, null);");
972 println("return (" + retType + ")retObj;");
980 * HELPER: returnGenericCallbackType() returns the callback type
982 private String returnGenericCallbackType(String paramType) {
984 if (getParamCategory(paramType) == ParamCategory.NONPRIMITIVES)
985 return getGenericType(paramType);
992 * HELPER: checkCallbackType() checks the callback type
994 private boolean checkCallbackType(String paramType, Set<String> callbackType) {
996 String prmType = returnGenericCallbackType(paramType);
997 if (callbackType == null) // If there is no callbackType it means not a callback method
1000 for (String type : callbackType) {
1001 if (type.equals(prmType))
1002 return true; // Check callbackType one by one
1010 * HELPER: checkCallbackType() checks the callback type
1012 private boolean checkCallbackType(String paramType, String callbackType) {
1014 String prmType = returnGenericCallbackType(paramType);
1015 if (callbackType == null) // If there is no callbackType it means not a callback method
1018 return callbackType.equals(prmType);
1023 * HELPER: writeCallbackInstantiationMethodBodyJavaStub() writes the callback object instantiation in the method of the stub class
1025 private void writeCallbackInstantiationMethodBodyJavaStub(String paramIdent, String callbackType, int counter, boolean isMultipleCallbacks) {
1027 println("if (!IoTRMIUtil.mapSkel.containsKey(" + paramIdent + ")) {");
1028 println("int newObjIdSent = rmiComm.getObjectIdCounter();");
1029 if (isMultipleCallbacks)
1030 println("objIdSent" + counter + "[cnt" + counter + "++] = newObjIdSent;");
1032 println("objIdSent" + counter + "[0] = newObjIdSent;");
1033 println("rmiComm.decrementObjectIdCounter();");
1034 println(callbackType + "_Skeleton skel" + counter + " = new " + callbackType + "_Skeleton(" + paramIdent + ", rmiComm, newObjIdSent);");
1035 println("IoTRMIUtil.mapSkel.put(" + paramIdent + ", skel" + counter + ");");
1036 println("IoTRMIUtil.mapSkelId.put(" + paramIdent + ", newObjIdSent);");
1037 println("Thread thread = new Thread() {");
1038 println("public void run() {");
1040 println("skel" + counter + ".___waitRequestInvokeMethod();");
1041 println("} catch (Exception ex) {");
1042 println("ex.printStackTrace();");
1043 println("throw new Error(\"Exception when trying to run ___waitRequestInvokeMethod() for " +
1044 callbackType + "_Skeleton!\");");
1048 println("thread.start();");
1049 println("while(!skel" + counter + ".didAlreadyInitWaitInvoke());");
1053 println("int newObjIdSent = IoTRMIUtil.mapSkelId.get(" + paramIdent + ");");
1054 if (isMultipleCallbacks)
1055 println("objIdSent" + counter + "[cnt" + counter + "++] = newObjIdSent;");
1057 println("objIdSent" + counter + "[0] = newObjIdSent;");
1063 * HELPER: writeCallbackMethodBodyJavaStub() writes the callback method of the stub class
1065 private void writeCallbackMethodBodyJavaStub(InterfaceDecl intDecl, List<String> methParams,
1066 List<String> methPrmTypes, String method, Set<String> callbackType) {
1068 // Determine callback object counter type (List vs. single variable)
1069 for (int i = 0; i < methParams.size(); i++) {
1070 String paramType = methPrmTypes.get(i);
1071 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
1072 print("int[] objIdSent" + i + " = ");
1073 String param = methParams.get(i);
1074 if (isArray(methParams.get(i)))
1075 println("new int[" + getSimpleIdentifier(methParams.get(i)) + ".length];");
1076 else if (isList(methPrmTypes.get(i)))
1077 println("new int[" + getSimpleIdentifier(methParams.get(i)) + ".size()];");
1079 println("new int[1];");
1083 // Check if this is single object, array, or list of objects
1084 for (int i = 0; i < methParams.size(); i++) {
1085 String paramType = methPrmTypes.get(i);
1086 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
1087 String param = methParams.get(i);
1088 if (isArrayOrList(paramType, param)) { // Generate loop
1089 println("int cnt" + i + " = 0;");
1090 println("for (" + getGenericType(paramType) + " cb : " + getSimpleIdentifier(param) + ") {");
1091 writeCallbackInstantiationMethodBodyJavaStub("cb", returnGenericCallbackType(paramType), i, true);
1093 writeCallbackInstantiationMethodBodyJavaStub(getSimpleIdentifier(param), returnGenericCallbackType(paramType), i, false);
1094 if (isArrayOrList(paramType, param))
1099 println(" catch (Exception ex) {");
1100 println("ex.printStackTrace();");
1101 println("throw new Error(\"Exception when generating skeleton objects!\");");
1107 * HELPER: writeMethodJavaStub() writes the methods of the stub class
1109 private void writeMethodJavaStub(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses, String newStubClass) {
1111 for (String method : methods) {
1113 List<String> methParams = intDecl.getMethodParams(method);
1114 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1115 print("public " + intDecl.getMethodType(method) + " " +
1116 intDecl.getMethodId(method) + "(");
1117 boolean isCallbackMethod = false;
1118 //String callbackType = null;
1119 Set<String> callbackType = new HashSet<String>();
1120 for (int i = 0; i < methParams.size(); i++) {
1122 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
1123 // Check if this has callback object
1124 if (callbackClasses.contains(paramType)) {
1125 isCallbackMethod = true;
1126 //callbackType = paramType;
1127 callbackType.add(paramType);
1128 // Even if there're 2 callback arguments, we expect them to be of the same interface
1130 print(methPrmTypes.get(i) + " " + methParams.get(i));
1131 // Check if this is the last element (don't print a comma)
1132 if (i != methParams.size() - 1) {
1137 // Now, write the body of stub!
1138 if (isCallbackMethod)
1139 writeCallbackMethodBodyJavaStub(intDecl, methParams, methPrmTypes, method, callbackType);
1140 writeStdMethodBodyJavaStub(intDecl, methParams, methPrmTypes, method, callbackType);
1147 * HELPER: getStubInterface() gets stub interface name based on original interface
1149 public String getStubInterface(String intface) {
1151 return mapInt2NewIntName.get(intface);
1156 * generateJavaStubClasses() generate stubs based on the methods list in Java
1158 public void generateJavaStubClasses() throws IOException {
1160 // Create a new directory
1161 String path = createDirectories(dir, subdir);
1162 for (String intface : mapIntfacePTH.keySet()) {
1164 // Check if there is more than 1 class that uses the same interface
1165 List<String> drvList = mapInt2Drv.get(intface);
1166 for(int i = 0; i < drvList.size(); i++) {
1168 String driverClass = drvList.get(i);
1169 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
1170 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
1172 // Open a new file to write into
1173 String newIntface = intMeth.getKey();
1174 String newStubClass = newIntface + "_Stub";
1175 String packageClass = null;
1176 // Check if this interface is a callback class
1177 if(isCallbackClass(intface)) {
1178 packageClass = CODE_PREFIX + "." + driverClass;
1179 path = createDirectories(dir + "/" + subdir + "/" + DRIVERS_DIRECTORY, driverClass);
1181 packageClass = controllerClass;
1182 path = createDirectories(dir + "/" + subdir + "/" + CONTROLLER_DIRECTORY, controllerClass);
1184 FileWriter fw = new FileWriter(path + "/" + newStubClass + ".java");
1185 pw = new PrintWriter(new BufferedWriter(fw));
1186 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
1187 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
1188 // Pass in set of methods and get import classes
1189 Set<String> methods = intMeth.getValue();
1190 Set<String> importClasses = getImportClasses(methods, intDecl);
1191 List<String> stdImportClasses = getStandardJavaImportClasses();
1192 List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
1193 // Find out if there are callback objects
1194 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
1195 boolean callbackExist = !callbackClasses.isEmpty();
1196 println("package " + packageClass + ";\n");
1197 printImportStatements(allImportClasses);
1198 println("\nimport " + INTERFACE_PACKAGE + ".*;\n");
1199 // Write class header
1200 println("public class " + newStubClass + " implements " + newIntface + " {\n");
1202 writePropertiesJavaStub(intface, intMeth.getValue(), intDecl);
1203 // Write constructor
1204 writeConstructorJavaStub(intface, newStubClass, intMeth.getValue(), intDecl);
1205 // Write callback constructor (used if this stub is treated as a callback stub)
1206 writeCallbackConstructorJavaStub(intface, newStubClass, intMeth.getValue(), intDecl);
1208 writeMethodJavaStub(intMeth.getValue(), intDecl, callbackClasses, newStubClass);
1211 System.out.println("IoTCompiler: Generated stub class " + newStubClass + ".java...");
1219 * HELPER: writePropertiesJavaSkeleton() writes the properties of the skeleton class
1221 private void writePropertiesJavaSkeleton(String intface, InterfaceDecl intDecl) {
1223 println("private " + intface + " mainObj;");
1224 Integer objId = mapIntfaceObjId.get(intface);
1225 println("private int objectId = " + objId + ";");
1226 println("// Communications and synchronizations");
1227 println("private IoTRMIComm rmiComm;");
1228 println("private AtomicBoolean didAlreadyInitWaitInvoke;");
1229 println("private AtomicBoolean methodReceived;");
1230 println("private byte[] methodBytes = null;");
1231 println("// Permissions");
1232 writePropertiesJavaPermission(intface, intDecl);
1238 * HELPER: writeStructPermissionJavaSkeleton() writes permission for struct helper
1240 private void writeStructPermissionJavaSkeleton(Collection<String> methods, InterfaceDecl intDecl, String intface) {
1242 // Use this set to handle two same methodIds
1243 for (String method : methods) {
1244 List<String> methParams = intDecl.getMethodParams(method);
1245 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1246 // Check for params with structs
1247 for (int i = 0; i < methParams.size(); i++) {
1248 String paramType = methPrmTypes.get(i);
1249 String param = methParams.get(i);
1250 String simpleType = getGenericType(paramType);
1251 if (isStructClass(simpleType)) {
1252 int methodNumId = intDecl.getMethodNumId(method);
1253 String helperMethod = methodNumId + "struct" + i;
1254 int methodHelperNumId = intDecl.getHelperMethodNumId(helperMethod);
1255 // Iterate over interfaces to give permissions to
1256 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
1257 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
1258 String newIntface = intMeth.getKey();
1259 int newObjectId = getNewIntfaceObjectId(newIntface);
1260 println("set" + newObjectId + "Allowed.add(" + methodHelperNumId + ");");
1269 * HELPER: writeConstructorJavaSkeleton() writes the constructor of the skeleton class
1271 private void writeConstructorJavaSkeleton(String newSkelClass, String intface, InterfaceDecl intDecl,
1272 Collection<String> methods, boolean callbackExist) {
1274 println("public " + newSkelClass + "(" + intface + " _mainObj, int _portSend, int _portRecv) throws Exception {");
1275 println("mainObj = _mainObj;");
1276 println("rmiComm = new IoTRMICommServer(_portSend, _portRecv);");
1277 // Generate permission control initialization
1278 writeConstructorJavaPermission(intface);
1279 writeStructPermissionJavaSkeleton(methods, intDecl, intface);
1280 println("IoTRMIUtil.mapSkel.put(_mainObj, this);");
1281 println("IoTRMIUtil.mapSkelId.put(_mainObj, objectId);");
1282 println("didAlreadyInitWaitInvoke = new AtomicBoolean(false);");
1283 println("methodReceived = new AtomicBoolean(false);");
1284 println("rmiComm.registerSkeleton(objectId, methodReceived);");
1285 println("Thread thread1 = new Thread() {");
1286 println("public void run() {");
1288 println("___waitRequestInvokeMethod();");
1290 println("catch (Exception ex)");
1292 println("ex.printStackTrace();");
1296 println("thread1.start();");
1302 * HELPER: writeCallbackConstructorJavaSkeleton() writes the constructor of the skeleton class
1304 private void writeCallbackConstructorJavaSkeleton(String newSkelClass, String intface, InterfaceDecl intDecl,
1305 Collection<String> methods, boolean callbackExist) {
1307 println("public " + newSkelClass + "(" + intface + " _mainObj, IoTRMIComm _rmiComm, int _objectId) throws Exception {");
1308 println("mainObj = _mainObj;");
1309 println("rmiComm = _rmiComm;");
1310 println("objectId = _objectId;");
1311 // Generate permission control initialization
1312 writeConstructorJavaPermission(intface);
1313 writeStructPermissionJavaSkeleton(methods, intDecl, intface);
1314 println("didAlreadyInitWaitInvoke = new AtomicBoolean(false);");
1315 println("methodReceived = new AtomicBoolean(false);");
1316 println("rmiComm.registerSkeleton(objectId, methodReceived);");
1322 * HELPER: writeStdMethodBodyJavaSkeleton() writes the standard method body in the skeleton class
1324 private void writeStdMethodBodyJavaSkeleton(List<String> methParams, String methodId, String methodType) {
1326 if (methodType.equals("void"))
1327 print("mainObj." + methodId + "(");
1329 print("return mainObj." + methodId + "(");
1330 for (int i = 0; i < methParams.size(); i++) {
1332 print(getSimpleIdentifier(methParams.get(i)));
1333 // Check if this is the last element (don't print a comma)
1334 if (i != methParams.size() - 1) {
1343 * HELPER: writeMethodJavaSkeleton() writes the method of the skeleton class
1345 private void writeMethodJavaSkeleton(Collection<String> methods, InterfaceDecl intDecl) {
1347 for (String method : methods) {
1349 List<String> methParams = intDecl.getMethodParams(method);
1350 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1351 String methodId = intDecl.getMethodId(method);
1352 print("public " + intDecl.getMethodType(method) + " " + methodId + "(");
1353 for (int i = 0; i < methParams.size(); i++) {
1355 String origParamType = methPrmTypes.get(i);
1356 String paramType = checkAndGetParamClass(origParamType);
1357 print(paramType + " " + methParams.get(i));
1358 // Check if this is the last element (don't print a comma)
1359 if (i != methParams.size() - 1) {
1364 // Now, write the body of skeleton!
1365 writeStdMethodBodyJavaSkeleton(methParams, methodId, intDecl.getMethodType(method));
1372 * HELPER: writeCallbackInstantiationJavaStubGeneration() writes the instantiation of callback stubs
1374 private void writeCallbackInstantiationJavaStubGeneration(String exchParamType, int counter) {
1376 println(exchParamType + " newStub" + counter + " = null;");
1377 println("if(!IoTRMIUtil.mapStub.containsKey(objIdRecv" + counter + ")) {");
1378 println("newStub" + counter + " = new " + exchParamType + "_Stub(rmiComm, objIdRecv" + counter + ");");
1379 println("IoTRMIUtil.mapStub.put(objIdRecv" + counter + ", newStub" + counter + ");");
1380 println("rmiComm.setObjectIdCounter(objIdRecv" + counter + ");");
1381 println("rmiComm.decrementObjectIdCounter();");
1384 println("newStub" + counter + " = (" + exchParamType + "_Stub) IoTRMIUtil.mapStub.get(objIdRecv" + counter + ");");
1390 * HELPER: writeCallbackJavaStubGeneration() writes the callback stub generation part
1392 private Map<Integer,String> writeCallbackJavaStubGeneration(List<String> methParams, List<String> methPrmTypes,
1393 Set<String> callbackType, boolean isStructMethod) {
1395 Map<Integer,String> mapStubParam = new HashMap<Integer,String>();
1396 String offsetPfx = "";
1398 offsetPfx = "offset";
1399 // Iterate over callback objects
1400 for (int i = 0; i < methParams.size(); i++) {
1401 String paramType = methPrmTypes.get(i);
1402 String param = methParams.get(i);
1403 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
1404 String exchParamType = checkAndGetParamClass(getGenericType(paramType));
1405 // Print array if this is array or list if this is a list of callback objects
1406 println("int[] stubIdArray" + i + " = (int[]) paramObj[" + offsetPfx + i + "];");
1407 if (isArray(param)) {
1408 println("int numStubs" + i + " = stubIdArray" + i + ".length;");
1409 println(exchParamType + "[] stub" + i + " = new " + exchParamType + "[numStubs" + i + "];");
1410 } else if (isList(paramType)) {
1411 println("int numStubs" + i + " = stubIdArray" + i + ".length;");
1412 println("List<" + exchParamType + "> stub" + i + " = new ArrayList<" + exchParamType + ">();");
1414 println("int objIdRecv" + i + " = stubIdArray" + i + "[0];");
1415 writeCallbackInstantiationJavaStubGeneration(exchParamType, i);
1418 // Generate a loop if needed
1419 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
1420 String exchParamType = checkAndGetParamClass(getGenericType(paramType));
1421 if (isArray(param)) {
1422 println("for (int i = 0; i < numStubs" + i + "; i++) {");
1423 println("int objIdRecv" + i + " = stubIdArray" + i + "[i];");
1424 writeCallbackInstantiationJavaStubGeneration(exchParamType, i);
1425 println("stub" + i + "[i] = newStub" + i + ";");
1427 } else if (isList(paramType)) {
1428 println("for (int i = 0; i < numStubs" + i + "; i++) {");
1429 println("int objIdRecv" + i + " = stubIdArray" + i + "[i];");
1430 writeCallbackInstantiationJavaStubGeneration(exchParamType, i);
1431 println("stub" + i + ".add(newStub" + i + ");");
1434 println(exchParamType + " stub" + i + " = newStub" + i + ";");
1435 mapStubParam.put(i, "stub" + i); // List of all stub parameters
1438 return mapStubParam;
1443 * HELPER: checkAndWriteEnumTypeJavaSkeleton() writes the enum type (convert from enum to int)
1445 private void checkAndWriteEnumTypeJavaSkeleton(List<String> methParams, List<String> methPrmTypes, boolean isStructMethod) {
1447 String offsetPfx = "";
1449 offsetPfx = "offset";
1450 // Iterate and find enum declarations
1451 boolean printed = false;
1452 for (int i = 0; i < methParams.size(); i++) {
1453 String paramType = methPrmTypes.get(i);
1454 String param = methParams.get(i);
1455 String simpleType = getGenericType(paramType);
1456 if (isEnumClass(simpleType)) {
1457 // Check if this is enum type
1458 println("int paramInt" + i + "[] = (int[]) paramObj[" + offsetPfx + i + "];");
1460 println(simpleType + "[] enumVals = " + simpleType + ".values();");
1463 if (isArray(param)) { // An array
1464 println("int len" + i + " = paramInt" + i + ".length;");
1465 println(simpleType + "[] paramEnum" + i + " = new " + simpleType + "[len" + i + "];");
1466 println("for (int i = 0; i < len" + i + "; i++) {");
1467 println("paramEnum" + i + "[i] = enumVals[paramInt" + i + "[i]];");
1469 } else if (isList(paramType)) { // A list
1470 println("int len" + i + " = paramInt" + i + ".length;");
1471 println("List<" + simpleType + "> paramEnum" + i + " = new ArrayList<" + simpleType + ">();");
1472 println("for (int i = 0; i < len" + i + "; i++) {");
1473 println("paramEnum" + i + ".add(enumVals[paramInt" + i + "[i]]);");
1475 } else { // Just one element
1476 println(simpleType + " paramEnum" + i + " = enumVals[paramInt" + i + "[0]];");
1484 * HELPER: checkAndWriteEnumRetTypeJavaSkeleton() writes the enum return type (convert from enum to int)
1486 private void checkAndWriteEnumRetTypeJavaSkeleton(String retType, String methodId) {
1488 // Strips off array "[]" for return type
1489 String pureType = getSimpleArrayType(getGenericType(retType));
1490 // Take the inner type of generic
1491 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
1492 pureType = getGenericType(retType);
1493 if (isEnumClass(pureType)) {
1494 // Check if this is enum type
1496 if (isArray(retType)) { // An array
1497 print(pureType + "[] retEnum = " + methodId + "(");
1498 } else if (isList(retType)) { // A list
1499 print("List<" + pureType + "> retEnum = " + methodId + "(");
1500 } else { // Just one element
1501 print(pureType + " retEnum = " + methodId + "(");
1508 * HELPER: checkAndWriteEnumRetConvJavaSkeleton() writes the enum return type (convert from enum to int)
1510 private void checkAndWriteEnumRetConvJavaSkeleton(String retType) {
1512 // Strips off array "[]" for return type
1513 String pureType = getSimpleArrayType(getGenericType(retType));
1514 // Take the inner type of generic
1515 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
1516 pureType = getGenericType(retType);
1517 if (isEnumClass(pureType)) {
1518 // Check if this is enum type
1519 if (isArray(retType)) { // An array
1520 println("int retLen = retEnum.length;");
1521 println("int[] retEnumVal = new int[retLen];");
1522 println("for (int i = 0; i < retLen; i++) {");
1523 println("retEnumVal[i] = retEnum[i].ordinal();");
1525 } else if (isList(retType)) { // A list
1526 println("int retLen = retEnum.size();");
1527 println("int[] retEnumVal = new int[retLen];");
1528 println("for (int i = 0; i < retLen; i++) {");
1529 println("retEnumVal[i] = retEnum.get(i).ordinal();");
1531 } else { // Just one element
1532 println("int[] retEnumVal = new int[1];");
1533 println("retEnumVal[0] = retEnum.ordinal();");
1535 println("Object retObj = retEnumVal;");
1541 * HELPER: writeLengthStructParamClassSkeleton() writes lengths of params
1543 private void writeLengthStructParamClassSkeleton(List<String> methParams, List<String> methPrmTypes,
1544 String method, InterfaceDecl intDecl) {
1546 // Iterate and find struct declarations - count number of params
1547 for (int i = 0; i < methParams.size(); i++) {
1548 String paramType = methPrmTypes.get(i);
1549 String param = methParams.get(i);
1550 String simpleType = getGenericType(paramType);
1551 if (isStructClass(simpleType)) {
1552 int members = getNumOfMembers(simpleType);
1553 print(Integer.toString(members) + "*");
1554 int methodNumId = intDecl.getMethodNumId(method);
1555 print("struct" + methodNumId + "Size" + i);
1558 if (i != methParams.size() - 1) {
1566 * HELPER: writeStructMembersJavaSkeleton() writes member parameters of struct
1568 private void writeStructMembersJavaSkeleton(String simpleType, String paramType,
1569 String param, String method, InterfaceDecl intDecl, int iVar) {
1571 // Get the struct declaration for this struct and generate initialization code
1572 StructDecl structDecl = getStructDecl(simpleType);
1573 List<String> memTypes = structDecl.getMemberTypes(simpleType);
1574 List<String> members = structDecl.getMembers(simpleType);
1575 if (isArrayOrList(paramType, param)) { // An array or list
1576 int methodNumId = intDecl.getMethodNumId(method);
1577 String counter = "struct" + methodNumId + "Size" + iVar;
1578 println("for(int i = 0; i < " + counter + "; i++) {");
1580 if (isArrayOrList(paramType, param)) { // An array or list
1581 for (int i = 0; i < members.size(); i++) {
1582 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
1583 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
1584 println("paramClsGen[pos++] = null;");
1587 } else { // Just one struct element
1588 for (int i = 0; i < members.size(); i++) {
1589 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
1590 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
1591 println("paramClsGen[pos++] = null;");
1598 * HELPER: writeStructMembersInitJavaSkeleton() writes member parameters initialization of struct
1600 private void writeStructMembersInitJavaSkeleton(InterfaceDecl intDecl, List<String> methParams,
1601 List<String> methPrmTypes, String method) {
1603 println("int objPos = 0;");
1604 for (int i = 0; i < methParams.size(); i++) {
1605 String paramType = methPrmTypes.get(i);
1606 String param = methParams.get(i);
1607 String simpleType = getGenericType(paramType);
1608 if (isStructClass(simpleType)) {
1609 int methodNumId = intDecl.getMethodNumId(method);
1610 String counter = "struct" + methodNumId + "Size" + i;
1612 if (isArray(param)) { // An array
1613 println(simpleType + "[] paramStruct" + i + " = new " + simpleType + "[" + counter + "];");
1614 println("for(int i = 0; i < " + counter + "; i++) {");
1615 println("paramStruct" + i + "[i] = new " + simpleType + "();");
1617 } else if (isList(paramType)) { // A list
1618 println("List<" + simpleType + "> paramStruct" + i + " = new ArrayList<" + simpleType + ">();");
1620 println(simpleType + " paramStruct" + i + " = new " + simpleType + "();");
1621 // Initialize members
1622 StructDecl structDecl = getStructDecl(simpleType);
1623 List<String> members = structDecl.getMembers(simpleType);
1624 List<String> memTypes = structDecl.getMemberTypes(simpleType);
1625 if (isArrayOrList(paramType, param)) { // An array or list
1626 println("for(int i = 0; i < " + counter + "; i++) {");
1628 if (isArray(param)) { // An array
1629 for (int j = 0; j < members.size(); j++) {
1630 String prmType = checkAndGetArray(memTypes.get(j), members.get(j));
1631 print("paramStruct" + i + "[i]." + getSimpleIdentifier(members.get(j)));
1632 println(" = (" + getSimpleType(getEnumType(prmType)) + ") paramObj[objPos++];");
1635 } else if (isList(paramType)) { // A list
1636 println(simpleType + " paramStructMem = new " + simpleType + "();");
1637 for (int j = 0; j < members.size(); j++) {
1638 String prmType = checkAndGetArray(memTypes.get(j), members.get(j));
1639 print("paramStructMem." + getSimpleIdentifier(members.get(j)));
1640 println(" = (" + getSimpleType(getEnumType(prmType)) + ") paramObj[objPos++];");
1642 println("paramStruct" + i + ".add(paramStructMem);");
1644 } else { // Just one struct element
1645 for (int j = 0; j < members.size(); j++) {
1646 String prmType = checkAndGetArray(memTypes.get(j), members.get(j));
1647 print("paramStruct" + i + "." + getSimpleIdentifier(members.get(j)));
1648 println(" = (" + getSimpleType(getEnumType(prmType)) + ") paramObj[objPos++];");
1652 // Take offsets of parameters
1653 println("int offset" + i +" = objPos++;");
1660 * HELPER: writeStructReturnJavaSkeleton() writes struct for return statement
1662 private void writeStructReturnJavaSkeleton(String simpleType, String retType) {
1664 // Minimum retLen is 1 if this is a single struct object
1665 if (isArray(retType))
1666 println("int retLen = retStruct.length;");
1667 else if (isList(retType))
1668 println("int retLen = retStruct.size();");
1669 else // Just single struct object
1670 println("int retLen = 1;");
1671 println("Object retLenObj = retLen;");
1672 println("rmiComm.sendReturnObj(retLenObj, localMethodBytes);");
1673 int numMem = getNumOfMembers(simpleType);
1674 println("Class<?>[] retCls = new Class<?>[" + numMem + "*retLen];");
1675 println("Object[] retObj = new Object[" + numMem + "*retLen];");
1676 println("int retPos = 0;");
1677 // Get the struct declaration for this struct and generate initialization code
1678 StructDecl structDecl = getStructDecl(simpleType);
1679 List<String> memTypes = structDecl.getMemberTypes(simpleType);
1680 List<String> members = structDecl.getMembers(simpleType);
1681 if (isArray(retType)) { // An array or list
1682 println("for(int i = 0; i < retLen; i++) {");
1683 for (int i = 0; i < members.size(); i++) {
1684 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
1685 println("retCls[retPos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
1686 print("retObj[retPos++] = retStruct[i].");
1687 print(getEnumParam(memTypes.get(i), getSimpleIdentifier(members.get(i)), i));
1691 } else if (isList(retType)) { // An array or list
1692 println("for(int i = 0; i < retLen; i++) {");
1693 for (int i = 0; i < members.size(); i++) {
1694 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
1695 println("retCls[retPos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
1696 print("retObj[retPos++] = retStruct.get(i).");
1697 print(getEnumParam(memTypes.get(i), getSimpleIdentifier(members.get(i)), i));
1701 } else { // Just one struct element
1702 for (int i = 0; i < members.size(); i++) {
1703 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
1704 println("retCls[retPos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
1705 print("retObj[retPos++] = retStruct.");
1706 print(getEnumParam(memTypes.get(i), getSimpleIdentifier(members.get(i)), i));
1715 * HELPER: writeMethodHelperReturnJavaSkeleton() writes return statement part in skeleton
1717 private void writeMethodHelperReturnJavaSkeleton(InterfaceDecl intDecl, List<String> methParams,
1718 List<String> methPrmTypes, String method, boolean isCallbackMethod, Set<String> callbackType,
1719 boolean isStructMethod) {
1721 checkAndWriteEnumTypeJavaSkeleton(methParams, methPrmTypes, isStructMethod);
1722 Map<Integer,String> mapStubParam = null;
1723 if (isCallbackMethod) {
1725 mapStubParam = writeCallbackJavaStubGeneration(methParams, methPrmTypes, callbackType, isStructMethod);
1727 // Check if this is "void"
1728 String retType = intDecl.getMethodType(method);
1729 if (retType.equals("void")) {
1730 print(intDecl.getMethodId(method) + "(");
1731 } else if (isEnumClass(getSimpleArrayType(getGenericType(retType)))) { // Enum type
1732 checkAndWriteEnumRetTypeJavaSkeleton(retType, intDecl.getMethodId(method));
1733 } else if (isStructClass(getSimpleArrayType(getGenericType(retType)))) { // Struct type
1734 print(retType + " retStruct = " + intDecl.getMethodId(method) + "(");
1735 } else { // We do have a return value
1736 print("Object retObj = " + intDecl.getMethodId(method) + "(");
1738 for (int i = 0; i < methParams.size(); i++) {
1740 String paramType = methPrmTypes.get(i);
1741 if (isCallbackMethod && checkCallbackType(paramType, callbackType)) {
1742 print(mapStubParam.get(i)); // Get the callback parameter
1743 } else if (isEnumClass(getGenericType(paramType))) { // Enum class
1744 print(getEnumParam(paramType, methParams.get(i), i));
1745 } else if (isStructClass(getGenericType(paramType))) {
1746 print("paramStruct" + i);
1748 String prmType = checkAndGetArray(paramType, methParams.get(i));
1750 print("(" + prmType + ") paramObj[offset" + i + "]");
1752 print("(" + prmType + ") paramObj[" + i + "]");
1754 if (i != methParams.size() - 1)
1758 if (!retType.equals("void")) {
1759 if (isEnumClass(getSimpleArrayType(getGenericType(retType)))) { // Enum type
1760 checkAndWriteEnumRetConvJavaSkeleton(retType);
1761 println("rmiComm.sendReturnObj(retObj, localMethodBytes);");
1762 } else if (isStructClass(getSimpleArrayType(getGenericType(retType)))) { // Struct type
1763 writeStructReturnJavaSkeleton(getSimpleArrayType(getGenericType(retType)), retType);
1764 println("rmiComm.sendReturnObj(retCls, retObj, localMethodBytes);");
1766 println("rmiComm.sendReturnObj(retObj, localMethodBytes);");
1768 if (isCallbackMethod) { // Catch exception if this is callback
1770 println(" catch(Exception ex) {");
1771 println("ex.printStackTrace();");
1772 println("throw new Error(\"Exception from callback object instantiation!\");");
1779 * HELPER: writeMethodHelperStructJavaSkeleton() writes the struct in skeleton
1781 private void writeMethodHelperStructJavaSkeleton(InterfaceDecl intDecl, List<String> methParams,
1782 List<String> methPrmTypes, String method, Set<String> callbackClasses) {
1784 // Generate array of parameter objects
1785 boolean isCallbackMethod = false;
1786 Set<String> callbackType = new HashSet<String>();
1787 println("byte[] localMethodBytes = methodBytes;");
1788 println("rmiComm.setGetMethodBytes();");
1789 print("int paramLen = ");
1790 writeLengthStructParamClassSkeleton(methParams, methPrmTypes, method, intDecl);
1792 println("Class<?>[] paramCls = new Class<?>[paramLen];");
1793 println("Class<?>[] paramClsGen = new Class<?>[paramLen];");
1794 println("int pos = 0;");
1795 // Iterate again over the parameters
1796 for (int i = 0; i < methParams.size(); i++) {
1797 String paramType = methPrmTypes.get(i);
1798 String param = methParams.get(i);
1799 String simpleType = getGenericType(paramType);
1800 if (isStructClass(simpleType)) {
1801 writeStructMembersJavaSkeleton(simpleType, paramType, param, method, intDecl, i);
1803 String prmType = returnGenericCallbackType(methPrmTypes.get(i));
1804 if (callbackClasses.contains(prmType)) {
1805 isCallbackMethod = true;
1806 //callbackType = prmType;
1807 callbackType.add(prmType);
1808 println("paramCls[pos] = int[].class;");
1809 println("paramClsGen[pos++] = null;");
1810 } else { // Generate normal classes if it's not a callback object
1811 String paramTypeOth = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
1812 println("paramCls[pos] = " + getSimpleType(getEnumType(paramTypeOth)) + ".class;");
1813 print("paramClsGen[pos++] = ");
1814 String prmTypeOth = methPrmTypes.get(i);
1815 if (getParamCategory(prmTypeOth) == ParamCategory.NONPRIMITIVES)
1816 println(getTypeOfGeneric(prmType)[0] + ".class;");
1822 println("Object[] paramObj = rmiComm.getMethodParams(paramCls, paramClsGen, localMethodBytes);");
1823 writeStructMembersInitJavaSkeleton(intDecl, methParams, methPrmTypes, method);
1824 // Write the return value part
1825 writeMethodHelperReturnJavaSkeleton(intDecl, methParams, methPrmTypes, method, isCallbackMethod, callbackType, true);
1830 * HELPER: writeStdMethodHelperBodyJavaSkeleton() writes the standard method body helper in the skeleton class
1832 private void writeStdMethodHelperBodyJavaSkeleton(InterfaceDecl intDecl, List<String> methParams,
1833 List<String> methPrmTypes, String method, Set<String> callbackClasses) {
1835 // Generate array of parameter objects
1836 boolean isCallbackMethod = false;
1837 Set<String> callbackType = new HashSet<String>();
1838 println("byte[] localMethodBytes = methodBytes;");
1839 println("rmiComm.setGetMethodBytes();");
1840 print("Object[] paramObj = rmiComm.getMethodParams(new Class<?>[] { ");
1841 for (int i = 0; i < methParams.size(); i++) {
1843 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
1844 if (callbackClasses.contains(paramType)) {
1845 isCallbackMethod = true;
1846 callbackType.add(paramType);
1847 print("int[].class");
1848 } else { // Generate normal classes if it's not a callback object
1849 String prmType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
1850 print(getSimpleType(getEnumType(prmType)) + ".class");
1852 if (i != methParams.size() - 1)
1855 // Generate generic class if it's a generic type.. null otherwise
1856 print(" }, new Class<?>[] { ");
1857 for (int i = 0; i < methParams.size(); i++) {
1858 String prmType = methPrmTypes.get(i);
1859 if ((getParamCategory(prmType) == ParamCategory.NONPRIMITIVES) &&
1860 !isEnumClass(getGenericType(prmType)) &&
1861 !callbackClasses.contains(getGenericType(prmType)))
1862 print(getGenericType(prmType) + ".class");
1865 if (i != methParams.size() - 1)
1868 println(" }, localMethodBytes);");
1869 // Write the return value part
1870 writeMethodHelperReturnJavaSkeleton(intDecl, methParams, methPrmTypes, method, isCallbackMethod, callbackType, false);
1875 * HELPER: writeMethodHelperJavaSkeleton() writes the method helper of the skeleton class
1877 private void writeMethodHelperJavaSkeleton(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
1879 // Use this set to handle two same methodIds
1880 Set<String> uniqueMethodIds = new HashSet<String>();
1881 for (String method : methods) {
1883 List<String> methParams = intDecl.getMethodParams(method);
1884 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1885 if (isStructPresent(methParams, methPrmTypes)) { // Treat struct differently
1886 String methodId = intDecl.getMethodId(method);
1887 print("public void ___");
1888 String helperMethod = methodId;
1889 if (uniqueMethodIds.contains(methodId))
1890 helperMethod = helperMethod + intDecl.getMethodNumId(method);
1892 uniqueMethodIds.add(methodId);
1893 String retType = intDecl.getMethodType(method);
1894 print(helperMethod + "(");
1895 boolean begin = true;
1896 for (int i = 0; i < methParams.size(); i++) { // Print size variables
1897 String paramType = methPrmTypes.get(i);
1898 String param = methParams.get(i);
1899 String simpleType = getGenericType(paramType);
1900 if (isStructClass(simpleType)) {
1901 if (!begin) // Generate comma for not the beginning variable
1905 int methodNumId = intDecl.getMethodNumId(method);
1906 print("int struct" + methodNumId + "Size" + i);
1909 // Check if this is "void"
1910 if (retType.equals("void"))
1913 println(") throws IOException {");
1914 writeMethodHelperStructJavaSkeleton(intDecl, methParams, methPrmTypes, method, callbackClasses);
1917 String methodId = intDecl.getMethodId(method);
1918 print("public void ___");
1919 String helperMethod = methodId;
1920 if (uniqueMethodIds.contains(methodId))
1921 helperMethod = helperMethod + intDecl.getMethodNumId(method);
1923 uniqueMethodIds.add(methodId);
1924 // Check if this is "void"
1925 String retType = intDecl.getMethodType(method);
1926 if (retType.equals("void"))
1927 println(helperMethod + "() {");
1929 println(helperMethod + "() throws IOException {");
1930 // Now, write the helper body of skeleton!
1931 writeStdMethodHelperBodyJavaSkeleton(intDecl, methParams, methPrmTypes, method, callbackClasses);
1935 // Write method helper for structs
1936 writeMethodHelperStructSetupJavaSkeleton(methods, intDecl);
1941 * HELPER: writeMethodHelperStructSetupJavaSkeleton() writes the method helper of struct setup in skeleton class
1943 private void writeMethodHelperStructSetupJavaSkeleton(Collection<String> methods,
1944 InterfaceDecl intDecl) {
1946 // Use this set to handle two same methodIds
1947 for (String method : methods) {
1949 List<String> methParams = intDecl.getMethodParams(method);
1950 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1951 // Check for params with structs
1952 for (int i = 0; i < methParams.size(); i++) {
1953 String paramType = methPrmTypes.get(i);
1954 String param = methParams.get(i);
1955 String simpleType = getGenericType(paramType);
1956 if (isStructClass(simpleType)) {
1957 int methodNumId = intDecl.getMethodNumId(method);
1958 print("public int ___");
1959 String helperMethod = methodNumId + "struct" + i;
1960 println(helperMethod + "() {");
1961 // Now, write the helper body of skeleton!
1962 println("byte[] localMethodBytes = methodBytes;");
1963 println("rmiComm.setGetMethodBytes();");
1964 println("Object[] paramObj = rmiComm.getMethodParams(new Class<?>[] { int.class }, new Class<?>[] { null }, localMethodBytes);");
1965 println("return (int) paramObj[0];");
1974 * HELPER: writeMethodHelperStructSetupJavaCallbackSkeleton() writes the method helper of struct setup in callback skeleton class
1976 private void writeMethodHelperStructSetupJavaCallbackSkeleton(Collection<String> methods,
1977 InterfaceDecl intDecl) {
1979 // Use this set to handle two same methodIds
1980 for (String method : methods) {
1982 List<String> methParams = intDecl.getMethodParams(method);
1983 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1984 // Check for params with structs
1985 for (int i = 0; i < methParams.size(); i++) {
1986 String paramType = methPrmTypes.get(i);
1987 String param = methParams.get(i);
1988 String simpleType = getGenericType(paramType);
1989 if (isStructClass(simpleType)) {
1990 int methodNumId = intDecl.getMethodNumId(method);
1991 print("public int ___");
1992 String helperMethod = methodNumId + "struct" + i;
1993 println(helperMethod + "(IoTRMIObject rmiObj) {");
1994 // Now, write the helper body of skeleton!
1995 println("Object[] paramObj = rmiComm.getMethodParams(new Class<?>[] { int.class }, new Class<?>[] { null });");
1996 println("return (int) paramObj[0];");
2005 * HELPER: writeCountVarStructSkeleton() writes counter variable of struct for skeleton
2007 private void writeCountVarStructSkeleton(Collection<String> methods, InterfaceDecl intDecl) {
2009 // Use this set to handle two same methodIds
2010 for (String method : methods) {
2012 List<String> methParams = intDecl.getMethodParams(method);
2013 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2014 // Check for params with structs
2015 for (int i = 0; i < methParams.size(); i++) {
2016 String paramType = methPrmTypes.get(i);
2017 String param = methParams.get(i);
2018 String simpleType = getGenericType(paramType);
2019 if (isStructClass(simpleType)) {
2020 int methodNumId = intDecl.getMethodNumId(method);
2021 println("int struct" + methodNumId + "Size" + i + " = 0;");
2029 * HELPER: writeInputCountVarStructJavaSkeleton() writes input counter variable of struct for skeleton
2031 private boolean writeInputCountVarStructJavaSkeleton(String method, InterfaceDecl intDecl) {
2033 List<String> methParams = intDecl.getMethodParams(method);
2034 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2035 boolean structExist = false;
2036 boolean begin = true;
2037 // Check for params with structs
2038 for (int i = 0; i < methParams.size(); i++) {
2039 String paramType = methPrmTypes.get(i);
2040 String param = methParams.get(i);
2041 String simpleType = getGenericType(paramType);
2042 if (isStructClass(simpleType)) {
2048 int methodNumId = intDecl.getMethodNumId(method);
2049 print("struct" + methodNumId + "Size" + i + "Final");
2057 * HELPER: writeInputCountVarStructCplusSkeleton() writes input counter variable of struct for skeleton
2059 private boolean writeInputCountVarStructCplusSkeleton(String method, InterfaceDecl intDecl) {
2061 List<String> methParams = intDecl.getMethodParams(method);
2062 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2063 boolean structExist = false;
2064 boolean begin = true;
2065 // Check for params with structs
2066 for (int i = 0; i < methParams.size(); i++) {
2067 String paramType = methPrmTypes.get(i);
2068 String param = methParams.get(i);
2069 String simpleType = getGenericType(paramType);
2070 if (isStructClass(simpleType)) {
2076 int methodNumId = intDecl.getMethodNumId(method);
2077 print("struct" + methodNumId + "Size" + i);
2085 * HELPER: writeMethodCallStructJavaSkeleton() writes method call for wait invoke in skeleton
2087 private void writeMethodCallStructJavaSkeleton(Collection<String> methods, InterfaceDecl intDecl) {
2089 // Use this set to handle two same methodIds
2090 for (String method : methods) {
2092 List<String> methParams = intDecl.getMethodParams(method);
2093 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2094 // Check for params with structs
2095 for (int i = 0; i < methParams.size(); i++) {
2096 String paramType = methPrmTypes.get(i);
2097 String param = methParams.get(i);
2098 String simpleType = getGenericType(paramType);
2099 if (isStructClass(simpleType)) {
2100 int methodNumId = intDecl.getMethodNumId(method);
2102 String helperMethod = methodNumId + "struct" + i;
2103 String tempVar = "struct" + methodNumId + "Size" + i;
2104 print(intDecl.getHelperMethodNumId(helperMethod) + ": ");
2105 print(tempVar + " = ___");
2106 println(helperMethod + "(); break;");
2114 * HELPER: writeMethodCallStructCplusSkeleton() writes method call for wait invoke in skeleton
2116 private void writeMethodCallStructCplusSkeleton(Collection<String> methods, InterfaceDecl intDecl) {
2118 // Use this set to handle two same methodIds
2119 for (String method : methods) {
2121 List<String> methParams = intDecl.getMethodParams(method);
2122 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2123 // Check for params with structs
2124 for (int i = 0; i < methParams.size(); i++) {
2125 String paramType = methPrmTypes.get(i);
2126 String param = methParams.get(i);
2127 String simpleType = getGenericType(paramType);
2128 if (isStructClass(simpleType)) {
2129 int methodNumId = intDecl.getMethodNumId(method);
2131 String helperMethod = methodNumId + "struct" + i;
2132 String tempVar = "struct" + methodNumId + "Size" + i;
2133 print(intDecl.getHelperMethodNumId(helperMethod) + ": ");
2134 print(tempVar + " = ___");
2135 println(helperMethod + "(skel); break;");
2143 * HELPER: writeMethodCallStructCallbackSkeleton() writes method call for wait invoke in skeleton
2145 private void writeMethodCallStructCallbackSkeleton(Collection<String> methods, InterfaceDecl intDecl) {
2147 // Use this set to handle two same methodIds
2148 for (String method : methods) {
2150 List<String> methParams = intDecl.getMethodParams(method);
2151 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2152 // Check for params with structs
2153 for (int i = 0; i < methParams.size(); i++) {
2154 String paramType = methPrmTypes.get(i);
2155 String param = methParams.get(i);
2156 String simpleType = getGenericType(paramType);
2157 if (isStructClass(simpleType)) {
2158 int methodNumId = intDecl.getMethodNumId(method);
2160 String helperMethod = methodNumId + "struct" + i;
2161 String tempVar = "struct" + methodNumId + "Size" + i;
2162 print(intDecl.getHelperMethodNumId(helperMethod) + ": ");
2163 print(tempVar + " = ___");
2164 println(helperMethod + "(rmiObj); break;");
2172 * HELPER: writeJavaMethodPermission() writes permission checks in skeleton
2174 private void writeJavaMethodPermission(String intface) {
2176 // Get all the different stubs
2177 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
2178 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
2179 String newIntface = intMeth.getKey();
2180 int newObjectId = getNewIntfaceObjectId(newIntface);
2181 println("if (_objectId == objectId) {");
2182 println("if (!set" + newObjectId + "Allowed.contains(methodId)) {");
2183 println("throw new Error(\"Object with object Id: \" + _objectId + \" is not allowed to access method: \" + methodId);");
2187 println("continue;");
2194 * HELPER: writeFinalInputCountVarStructSkeleton() writes the final version of input counter variable of struct for skeleton
2196 private boolean writeFinalInputCountVarStructSkeleton(String method, InterfaceDecl intDecl) {
2198 List<String> methParams = intDecl.getMethodParams(method);
2199 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2200 boolean structExist = false;
2201 boolean begin = true;
2202 // Check for params with structs
2203 for (int i = 0; i < methParams.size(); i++) {
2204 String paramType = methPrmTypes.get(i);
2205 String param = methParams.get(i);
2206 String simpleType = getGenericType(paramType);
2207 if (isStructClass(simpleType)) {
2209 int methodNumId = intDecl.getMethodNumId(method);
2210 println("final int struct" + methodNumId + "Size" + i +
2211 "Final = struct" + methodNumId + "Size" + i + ";");
2219 * HELPER: writeJavaWaitRequestInvokeMethod() writes the main loop of the skeleton class
2221 private void writeJavaWaitRequestInvokeMethod(Collection<String> methods, InterfaceDecl intDecl, String intface) {
2223 // Use this set to handle two same methodIds
2224 Set<String> uniqueMethodIds = new HashSet<String>();
2225 println("public void ___waitRequestInvokeMethod() throws IOException {");
2226 // Write variables here if we have callbacks or enums or structs
2227 writeCountVarStructSkeleton(methods, intDecl);
2228 println("didAlreadyInitWaitInvoke.compareAndSet(false, true);");
2229 println("while (true) {");
2230 println("if (!methodReceived.get()) {");
2231 println("continue;");
2233 println("methodBytes = rmiComm.getMethodBytes();");
2234 println("methodReceived.set(false);");
2235 println("int _objectId = IoTRMIComm.getObjectId(methodBytes);");
2236 println("int methodId = IoTRMIComm.getMethodId(methodBytes);");
2237 // Generate permission check
2238 writeJavaMethodPermission(intface);
2239 println("switch (methodId) {");
2240 // Print methods and method Ids
2241 for (String method : methods) {
2242 String methodId = intDecl.getMethodId(method);
2243 int methodNumId = intDecl.getMethodNumId(method);
2244 println("case " + methodNumId + ":");
2245 // Check for stuct counters
2246 writeFinalInputCountVarStructSkeleton(method, intDecl);
2247 println("new Thread() {");
2248 println("public void run() {");
2251 String helperMethod = methodId;
2252 if (uniqueMethodIds.contains(methodId))
2253 helperMethod = helperMethod + methodNumId;
2255 uniqueMethodIds.add(methodId);
2256 print(helperMethod + "(");
2257 writeInputCountVarStructJavaSkeleton(method, intDecl);
2260 println("catch (Exception ex) {");
2261 println("ex.printStackTrace();");
2264 println("}.start();");
2267 String method = "___initCallBack()";
2268 writeMethodCallStructJavaSkeleton(methods, intDecl);
2269 println("default: ");
2270 println("throw new Error(\"Method Id \" + methodId + \" not recognized!\");");
2278 * HELPER: writeReturnDidAlreadyInitWaitInvoke() writes the function to return didAlreadyInitWaitInvoke
2280 private void writeReturnDidAlreadyInitWaitInvoke() {
2282 println("public boolean didAlreadyInitWaitInvoke() {");
2283 println("return didAlreadyInitWaitInvoke.get();");
2289 * generateJavaSkeletonClass() generate skeletons based on the methods list in Java
2291 public void generateJavaSkeletonClass() throws IOException {
2293 // Create a new directory
2294 String path = createDirectories(dir, subdir);
2295 for (String intface : mapIntfacePTH.keySet()) {
2297 // Check if there is more than 1 class that uses the same interface
2298 List<String> drvList = mapInt2Drv.get(intface);
2299 for(int i = 0; i < drvList.size(); i++) {
2302 String driverClass = drvList.get(i);
2303 // Open a new file to write into
2304 String newSkelClass = intface + "_Skeleton";
2305 String packageClass = null;
2306 // Check if this interface is a callback class
2307 if(isCallbackClass(intface)) {
2308 packageClass = controllerClass;
2309 path = createDirectories(dir + "/" + subdir + "/" + CONTROLLER_DIRECTORY, controllerClass);
2311 packageClass = CODE_PREFIX + "." + driverClass;
2312 path = createDirectories(dir + "/" + subdir + "/" + DRIVERS_DIRECTORY, driverClass);
2314 FileWriter fw = new FileWriter(path + "/" + newSkelClass + ".java");
2315 pw = new PrintWriter(new BufferedWriter(fw));
2316 // Pass in set of methods and get import classes
2317 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2318 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
2319 List<String> methods = intDecl.getMethods();
2320 Set<String> importClasses = getImportClasses(methods, intDecl);
2321 List<String> stdImportClasses = getStandardJavaImportClasses();
2322 List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
2323 // Find out if there are callback objects
2324 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
2325 boolean callbackExist = !callbackClasses.isEmpty();
2326 println("package " + packageClass + ";\n");
2327 printImportStatements(allImportClasses);
2328 println("\nimport " + INTERFACE_PACKAGE + ".*;\n");
2329 // Write class header
2330 println("public class " + newSkelClass + " implements " + intface + " {\n");
2332 writePropertiesJavaSkeleton(intface, intDecl);
2333 // Write constructor
2334 writeConstructorJavaSkeleton(newSkelClass, intface, intDecl, methods, callbackExist);
2335 // Write constructor that is called when this object is a callback object
2336 writeCallbackConstructorJavaSkeleton(newSkelClass, intface, intDecl, methods, callbackExist);
2337 // Write function to return didAlreadyInitWaitInvoke
2338 writeReturnDidAlreadyInitWaitInvoke();
2340 writeMethodJavaSkeleton(methods, intDecl);
2341 // Write method helper
2342 writeMethodHelperJavaSkeleton(methods, intDecl, callbackClasses);
2343 // Write waitRequestInvokeMethod() - main loop
2344 writeJavaWaitRequestInvokeMethod(methods, intDecl, intface);
2347 System.out.println("IoTCompiler: Generated skeleton class " + newSkelClass + ".java...");
2353 /*================================================================================
2357 *================================================================================/
2360 * HELPER: writeMethodCplusLocalInterface() writes the method of the local interface
2362 private void writeMethodCplusLocalInterface(Collection<String> methods, InterfaceDecl intDecl) {
2364 for (String method : methods) {
2366 List<String> methParams = intDecl.getMethodParams(method);
2367 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2368 print("virtual " + checkAndGetCplusType(intDecl.getMethodType(method)) + " " +
2369 intDecl.getMethodId(method) + "(");
2370 for (int i = 0; i < methParams.size(); i++) {
2371 // Check for params with driver class types and exchange it
2372 // with its remote interface
2373 String paramType = checkAndGetParamClass(methPrmTypes.get(i));
2374 paramType = checkAndGetCplusType(paramType);
2375 // Check for arrays - translate into vector in C++
2376 String paramComplete = checkAndGetCplusArray(paramType, methParams.get(i));
2377 print(paramComplete);
2378 // Check if this is the last element (don't print a comma)
2379 if (i != methParams.size() - 1) {
2389 * HELPER: writeMethodCplusInterface() writes the method of the interface
2391 private void writeMethodCplusInterface(Collection<String> methods, InterfaceDecl intDecl) {
2393 for (String method : methods) {
2395 List<String> methParams = intDecl.getMethodParams(method);
2396 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2397 print("virtual " + checkAndGetCplusType(intDecl.getMethodType(method)) + " " +
2398 intDecl.getMethodId(method) + "(");
2399 for (int i = 0; i < methParams.size(); i++) {
2400 // Check for params with driver class types and exchange it
2401 // with its remote interface
2402 String paramType = methPrmTypes.get(i);
2403 paramType = checkAndGetCplusType(paramType);
2404 // Check for arrays - translate into vector in C++
2405 String paramComplete = checkAndGetCplusArray(paramType, methParams.get(i));
2406 print(paramComplete);
2407 // Check if this is the last element (don't print a comma)
2408 if (i != methParams.size() - 1) {
2418 * HELPER: generateEnumCplus() writes the enumeration declaration
2420 public void generateEnumCplus() throws IOException {
2422 // Create a new directory
2423 createDirectory(dir);
2424 String path = createDirectories(dir, VIRTUALS_DIRECTORY);
2425 for (String intface : mapIntfacePTH.keySet()) {
2426 // Get the right StructDecl
2427 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2428 EnumDecl enumDecl = (EnumDecl) decHandler.getEnumDecl(intface);
2429 Set<String> enumTypes = enumDecl.getEnumDeclarations();
2430 // Iterate over enum declarations
2431 for (String enType : enumTypes) {
2432 // Open a new file to write into
2433 FileWriter fw = new FileWriter(path + "/" + enType + ".hpp");
2434 pw = new PrintWriter(new BufferedWriter(fw));
2435 // Write file headers
2436 println("#ifndef _" + enType.toUpperCase() + "_HPP__");
2437 println("#define _" + enType.toUpperCase() + "_HPP__");
2438 println("enum " + enType + " {");
2439 List<String> enumMembers = enumDecl.getMembers(enType);
2440 for (int i = 0; i < enumMembers.size(); i++) {
2442 String member = enumMembers.get(i);
2444 // Check if this is the last element (don't print a comma)
2445 if (i != enumMembers.size() - 1)
2453 System.out.println("IoTCompiler: Generated enum " + enType + ".hpp...");
2460 * HELPER: generateStructCplus() writes the struct declaration
2462 public void generateStructCplus() throws IOException {
2464 // Create a new directory
2465 createDirectory(dir);
2466 String path = createDirectories(dir, VIRTUALS_DIRECTORY);
2467 for (String intface : mapIntfacePTH.keySet()) {
2468 // Get the right StructDecl
2469 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2470 StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
2471 List<String> structTypes = structDecl.getStructTypes();
2472 // Iterate over enum declarations
2473 for (String stType : structTypes) {
2474 // Open a new file to write into
2475 FileWriter fw = new FileWriter(path + "/" + stType + ".hpp");
2476 pw = new PrintWriter(new BufferedWriter(fw));
2477 // Write file headers
2478 println("#ifndef _" + stType.toUpperCase() + "_HPP__");
2479 println("#define _" + stType.toUpperCase() + "_HPP__");
2480 println("using namespace std;");
2481 println("struct " + stType + " {");
2482 List<String> structMemberTypes = structDecl.getMemberTypes(stType);
2483 List<String> structMembers = structDecl.getMembers(stType);
2484 for (int i = 0; i < structMembers.size(); i++) {
2486 String memberType = structMemberTypes.get(i);
2487 String member = structMembers.get(i);
2488 String structTypeC = checkAndGetCplusType(memberType);
2489 String structComplete = checkAndGetCplusArray(structTypeC, member);
2490 println(structComplete + ";");
2495 System.out.println("IoTCompiler: Generated struct " + stType + ".hpp...");
2502 * generateCplusLocalInterfaces() writes the local interfaces and provides type-checking.
2504 * It needs to rewrite and exchange USERDEFINED types in input parameters of stub
2505 * and original interfaces, e.g. exchange Camera and CameraWithVideoAndRecording.
2506 * The local interface has to be the input parameter for the stub and the stub
2507 * interface has to be the input parameter for the local class.
2509 public void generateCplusLocalInterfaces() throws IOException {
2511 // Create a new directory
2512 createDirectory(dir);
2513 String path = createDirectories(dir, VIRTUALS_DIRECTORY);
2514 for (String intface : mapIntfacePTH.keySet()) {
2515 // Open a new file to write into
2516 FileWriter fw = new FileWriter(path + "/" + intface + ".hpp");
2517 pw = new PrintWriter(new BufferedWriter(fw));
2518 // Write file headers
2519 println("#ifndef _" + intface.toUpperCase() + "_HPP__");
2520 println("#define _" + intface.toUpperCase() + "_HPP__");
2521 println("#include <iostream>");
2522 // Pass in set of methods and get include classes
2523 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2524 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
2525 List<String> methods = intDecl.getMethods();
2526 Set<String> includeClasses = getIncludeClasses(methods, intDecl, intface, true);
2527 printIncludeStatements(includeClasses); println("");
2528 println("using namespace std;\n");
2529 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
2530 if (!intface.equals(mainClass)) // Forward declare if not main class
2531 writeMethodCplusInterfaceForwardDecl(methods, intDecl, callbackClasses, true);
2532 println("class " + intface); println("{");
2535 writeMethodCplusLocalInterface(methods, intDecl);
2539 System.out.println("IoTCompiler: Generated local interface " + intface + ".hpp...");
2545 * HELPER: writeMethodCplusInterfaceForwardDecl() writes the forward declaration of the interface
2547 private void writeMethodCplusInterfaceForwardDecl(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses, boolean needNewIntface) {
2549 Set<String> isDefined = new HashSet<String>();
2550 for (String method : methods) {
2552 List<String> methParams = intDecl.getMethodParams(method);
2553 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2554 for (int i = 0; i < methParams.size(); i++) {
2555 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
2556 // Check if this has callback object
2557 if (callbackClasses.contains(paramType)) {
2558 if (!isDefined.contains(paramType)) {
2560 println("class " + getStubInterface(paramType) + ";\n");
2562 println("class " + paramType + ";\n");
2563 isDefined.add(paramType);
2572 * generateCPlusInterfaces() generate stub interfaces based on the methods list in C++
2574 * For C++ we use virtual classe as interface
2576 public void generateCPlusInterfaces() throws IOException {
2578 // Create a new directory
2579 String path = createDirectories(dir, subdir);
2580 path = createDirectories(dir + "/" + subdir, VIRTUALS_DIRECTORY);
2581 for (String intface : mapIntfacePTH.keySet()) {
2583 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
2584 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
2586 // Open a new file to write into
2587 String newIntface = intMeth.getKey();
2588 FileWriter fw = new FileWriter(path + "/" + newIntface + ".hpp");
2589 pw = new PrintWriter(new BufferedWriter(fw));
2590 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2591 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
2592 // Write file headers
2593 println("#ifndef _" + newIntface.toUpperCase() + "_HPP__");
2594 println("#define _" + newIntface.toUpperCase() + "_HPP__");
2595 println("#include <iostream>");
2596 updateIntfaceObjIdMap(intface, newIntface);
2597 // Pass in set of methods and get import classes
2598 Set<String> methods = intMeth.getValue();
2599 Set<String> includeClasses = getIncludeClasses(methods, intDecl, intface, false);
2600 printIncludeStatements(includeClasses); println("");
2601 println("using namespace std;\n");
2602 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
2603 writeMethodCplusInterfaceForwardDecl(methods, intDecl, callbackClasses, false);
2604 println("class " + newIntface);
2608 writeMethodCplusInterface(methods, intDecl);
2612 System.out.println("IoTCompiler: Generated interface " + newIntface + ".hpp...");
2619 * HELPER: writeMethodDeclCplusStub() writes the method declarations of the stub
2621 private void writeMethodDeclCplusStub(Collection<String> methods, InterfaceDecl intDecl) {
2623 for (String method : methods) {
2625 List<String> methParams = intDecl.getMethodParams(method);
2626 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2627 print(checkAndGetCplusType(intDecl.getMethodType(method)) + " " +
2628 intDecl.getMethodId(method) + "(");
2629 for (int i = 0; i < methParams.size(); i++) {
2631 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
2632 String methPrmType = checkAndGetCplusType(methPrmTypes.get(i));
2633 String methParamComplete = checkAndGetCplusArray(methPrmType, methParams.get(i));
2634 print(methParamComplete);
2635 // Check if this is the last element (don't print a comma)
2636 if (i != methParams.size() - 1) {
2646 * HELPER: writeMethodCplusStub() writes the methods of the stub
2648 private void writeMethodCplusStub(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses, String newStubClass) {
2650 for (String method : methods) {
2652 List<String> methParams = intDecl.getMethodParams(method);
2653 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2654 // Print the mutex lock first
2655 int methodNumId = intDecl.getMethodNumId(method);
2656 String mutexVar = "mtx" + newStubClass + "MethodExec" + methodNumId;
2657 println("mutex " + mutexVar + ";");
2658 print(checkAndGetCplusType(intDecl.getMethodType(method)) + " " + newStubClass + "::" +
2659 intDecl.getMethodId(method) + "(");
2660 boolean isCallbackMethod = false;
2661 Set<String> callbackType = new HashSet<String>();
2662 for (int i = 0; i < methParams.size(); i++) {
2664 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
2665 // Check if this has callback object
2666 if (callbackClasses.contains(paramType)) {
2667 isCallbackMethod = true;
2668 //callbackType = paramType;
2669 callbackType.add(paramType);
2670 // Even if there're 2 callback arguments, we expect them to be of the same interface
2672 String methPrmType = checkAndGetCplusType(methPrmTypes.get(i));
2673 String methParamComplete = checkAndGetCplusArray(methPrmType, methParams.get(i));
2674 print(methParamComplete);
2675 // Check if this is the last element (don't print a comma)
2676 if (i != methParams.size() - 1) {
2681 println("lock_guard<mutex> guard(" + mutexVar + ");");
2682 if (isCallbackMethod)
2683 writeCallbackMethodBodyCplusStub(intDecl, methParams, methPrmTypes, method, callbackType);
2684 writeStdMethodBodyCplusStub(intDecl, methParams, methPrmTypes, method, callbackType, isCallbackMethod);
2692 * HELPER: writeCallbackInstantiationMethodBodyCplusStub() writes the callback object instantiation in the method of the stub class
2694 private void writeCallbackInstantiationMethodBodyCplusStub(String paramIdent, String callbackType, int counter) {
2696 println("auto it" + counter + " = IoTRMIUtil::mapSkel->find(" + paramIdent + ");");
2697 println("if (it" + counter + " == IoTRMIUtil::mapSkel->end()) {");
2698 println("int newObjIdSent = rmiComm->getObjectIdCounter();");
2699 println("objIdSent" + counter + ".push_back(newObjIdSent);");
2700 println("rmiComm->decrementObjectIdCounter();");
2701 println(callbackType + "_Skeleton* skel" + counter + " = new " + callbackType + "_Skeleton(" + paramIdent + ", rmiComm, newObjIdSent);");
2702 println("IoTRMIUtil::mapSkel->insert(make_pair(" + paramIdent + ", skel" + counter + "));");
2703 println("IoTRMIUtil::mapSkelId->insert(make_pair(" + paramIdent + ", newObjIdSent));");
2704 println("thread th" + counter + " (&" + callbackType + "_Skeleton::___waitRequestInvokeMethod, skel" + counter +
2705 ", skel" + counter +");");
2706 println("th" + counter + ".detach();");
2707 println("while(!skel" + counter + "->didInitWaitInvoke());");
2711 println("auto itId = IoTRMIUtil::mapSkelId->find(" + paramIdent + ");");
2712 println("objIdSent" + counter + ".push_back(itId->second);");
2718 * HELPER: writeCallbackMethodBodyCplusStub() writes the callback method of the stub class
2720 private void writeCallbackMethodBodyCplusStub(InterfaceDecl intDecl, List<String> methParams,
2721 List<String> methPrmTypes, String method, Set<String> callbackType) {
2723 // Check if this is single object, array, or list of objects
2724 boolean isArrayOrList = false;
2725 String callbackParam = null;
2726 for (int i = 0; i < methParams.size(); i++) {
2727 String paramType = methPrmTypes.get(i);
2728 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
2729 println("vector<int> objIdSent" + i + ";");
2730 String param = methParams.get(i);
2731 if (isArrayOrList(paramType, param)) { // Generate loop
2732 println("for (" + getGenericType(paramType) + "* cb : " + getSimpleIdentifier(param) + ") {");
2733 writeCallbackInstantiationMethodBodyCplusStub("cb", returnGenericCallbackType(paramType), i);
2734 isArrayOrList = true;
2735 callbackParam = getSimpleIdentifier(param);
2737 writeCallbackInstantiationMethodBodyCplusStub(getSimpleIdentifier(param), returnGenericCallbackType(paramType), i);
2741 println("vector<int> ___paramCB" + i + " = objIdSent" + i + ";");
2748 * HELPER: checkAndWriteEnumTypeCplusStub() writes the enum type (convert from enum to int)
2750 private void checkAndWriteEnumTypeCplusStub(List<String> methParams, List<String> methPrmTypes) {
2752 // Iterate and find enum declarations
2753 for (int i = 0; i < methParams.size(); i++) {
2754 String paramType = methPrmTypes.get(i);
2755 String param = methParams.get(i);
2756 if (isEnumClass(getGenericType(paramType))) {
2757 // Check if this is enum type
2758 if (isArrayOrList(paramType, param)) { // An array or vector
2759 println("int len" + i + " = " + getSimpleIdentifier(param) + ".size();");
2760 println("vector<int> paramEnum" + i + "(len" + i + ");");
2761 println("for (int i = 0; i < len" + i + "; i++) {");
2762 println("paramEnum" + i + "[i] = (int) " + getSimpleIdentifier(param) + "[i];");
2764 } else { // Just one element
2765 println("vector<int> paramEnum" + i + "(1);");
2766 println("paramEnum" + i + "[0] = (int) " + param + ";");
2774 * HELPER: checkAndWriteEnumRetTypeCplusStub() writes the enum return type (convert from enum to int)
2776 private void checkAndWriteEnumRetTypeCplusStub(String retType, String method, InterfaceDecl intDecl) {
2778 // Strips off array "[]" for return type
2779 String pureType = getSimpleArrayType(getGenericType(retType));
2780 // Take the inner type of generic
2781 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
2782 pureType = getGenericType(retType);
2783 if (isEnumClass(pureType)) {
2784 // Check if this is enum type
2785 println("vector<int> retEnumInt;");
2786 println("void* retObj = &retEnumInt;");
2787 println("rmiComm->remoteCall(objectId, methodId, paramCls, paramObj, numParam);");
2788 writeWaitForReturnValueCplus(method, intDecl, "rmiComm->getReturnValue(retType, retObj);");
2789 if (isArrayOrList(retType, retType)) { // An array or vector
2790 println("int retLen = retEnumInt.size();");
2791 println("vector<" + pureType + "> retVal(retLen);");
2792 println("for (int i = 0; i < retLen; i++) {");
2793 println("retVal[i] = (" + pureType + ") retEnumInt[i];");
2795 } else { // Just one element
2796 println(pureType + " retVal = (" + pureType + ") retEnumInt[0];");
2798 println("return retVal;");
2804 * HELPER: checkAndWriteStructSetupCplusStub() writes the struct type setup
2806 private void checkAndWriteStructSetupCplusStub(List<String> methParams, List<String> methPrmTypes,
2807 InterfaceDecl intDecl, String method) {
2809 // Iterate and find struct declarations
2810 for (int i = 0; i < methParams.size(); i++) {
2811 String paramType = methPrmTypes.get(i);
2812 String param = methParams.get(i);
2813 String simpleType = getGenericType(paramType);
2814 if (isStructClass(simpleType)) {
2815 // Check if this is enum type
2816 println("int numParam" + i + " = 1;");
2817 int methodNumId = intDecl.getMethodNumId(method);
2818 String helperMethod = methodNumId + "struct" + i;
2819 println("int methodIdStruct" + i + " = " + intDecl.getHelperMethodNumId(helperMethod) + ";");
2820 //println("string retTypeStruct" + i + " = \"void\";");
2821 println("string paramClsStruct" + i + "[] = { \"int\" };");
2822 print("int structLen" + i + " = ");
2823 if (isArrayOrList(paramType, param)) { // An array
2824 println(getSimpleArrayType(param) + ".size();");
2825 } else { // Just one element
2828 println("void* paramObjStruct" + i + "[] = { &structLen" + i + " };");
2829 println("rmiComm->remoteCall(objectId, methodIdStruct" + i +
2830 ", paramClsStruct" + i + ", paramObjStruct" + i +
2831 ", numParam" + i + ");\n");
2838 * HELPER: writeLengthStructParamClassCplusStub() writes lengths of params
2840 private void writeLengthStructParamClassCplusStub(List<String> methParams, List<String> methPrmTypes) {
2842 // Iterate and find struct declarations - count number of params
2843 for (int i = 0; i < methParams.size(); i++) {
2844 String paramType = methPrmTypes.get(i);
2845 String param = methParams.get(i);
2846 String simpleType = getGenericType(paramType);
2847 if (isStructClass(simpleType)) {
2848 int members = getNumOfMembers(simpleType);
2849 if (isArrayOrList(paramType, param)) { // An array or list
2850 String structLen = getSimpleIdentifier(param) + ".size()";
2851 print(members + "*" + structLen);
2853 print(Integer.toString(members));
2856 if (i != methParams.size() - 1) {
2864 * HELPER: writeStructMembersCplusStub() writes member parameters of struct