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
2866 private void writeStructMembersCplusStub(String simpleType, String paramType, String param) {
2868 // Get the struct declaration for this struct and generate initialization code
2869 StructDecl structDecl = getStructDecl(simpleType);
2870 List<String> memTypes = structDecl.getMemberTypes(simpleType);
2871 List<String> members = structDecl.getMembers(simpleType);
2872 if (isArrayOrList(paramType, param)) { // An array or list
2873 println("for(int i = 0; i < " + getSimpleIdentifier(param) + ".size(); i++) {");
2875 if (isArrayOrList(paramType, param)) { // An array or list
2876 for (int i = 0; i < members.size(); i++) {
2877 String prmTypeC = checkAndGetCplusArgClsType(memTypes.get(i), members.get(i));
2878 println("paramCls[pos] = \"" + prmTypeC + "\";");
2879 print("paramObj[pos++] = &" + getSimpleIdentifier(param) + "[i].");
2880 print(getSimpleIdentifier(members.get(i)));
2884 } else { // Just one struct element
2885 for (int i = 0; i < members.size(); i++) {
2886 String prmTypeC = checkAndGetCplusArgClsType(memTypes.get(i), members.get(i));
2887 println("paramCls[pos] = \"" + prmTypeC + "\";");
2888 print("paramObj[pos++] = &" + param + ".");
2889 print(getSimpleIdentifier(members.get(i)));
2897 * HELPER: writeStructParamClassCplusStub() writes member parameters of struct
2899 private void writeStructParamClassCplusStub(List<String> methParams, List<String> methPrmTypes, Set<String> callbackType) {
2901 print("int numParam = ");
2902 writeLengthStructParamClassCplusStub(methParams, methPrmTypes);
2904 println("void* paramObj[numParam];");
2905 println("string paramCls[numParam];");
2906 println("int pos = 0;");
2907 // Iterate again over the parameters
2908 for (int i = 0; i < methParams.size(); i++) {
2909 String paramType = methPrmTypes.get(i);
2910 String param = methParams.get(i);
2911 String simpleType = getGenericType(paramType);
2912 if (isStructClass(simpleType)) {
2913 writeStructMembersCplusStub(simpleType, paramType, param);
2914 } else if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
2915 println("paramCls[pos] = \"int\";");
2916 println("paramObj[pos++] = &___paramCB" + i + ";");
2918 String prmTypeC = checkAndGetCplusArgClsType(methPrmTypes.get(i), methParams.get(i));
2919 println("paramCls[pos] = \"" + prmTypeC + "\";");
2920 print("paramObj[pos++] = &");
2921 print(getEnumParam(methPrmTypes.get(i), getSimpleIdentifier(methParams.get(i)), i));
2930 * HELPER: writeStructRetMembersCplusStub() writes member parameters of struct for return statement
2932 private void writeStructRetMembersCplusStub(String simpleType, String retType) {
2934 // Get the struct declaration for this struct and generate initialization code
2935 StructDecl structDecl = getStructDecl(simpleType);
2936 List<String> memTypes = structDecl.getMemberTypes(simpleType);
2937 List<String> members = structDecl.getMembers(simpleType);
2938 if (isArrayOrList(retType, retType)) { // An array or list
2939 println("for(int i = 0; i < retLen; i++) {");
2941 if (isArrayOrList(retType, retType)) { // An array or list
2942 for (int i = 0; i < members.size(); i++) {
2943 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
2944 print("structRet[i]." + getSimpleIdentifier(members.get(i)));
2945 println(" = retParam" + i + "[i];");
2948 } else { // Just one struct element
2949 for (int i = 0; i < members.size(); i++) {
2950 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
2951 print("structRet." + getSimpleIdentifier(members.get(i)));
2952 println(" = retParam" + i + ";");
2955 println("return structRet;");
2960 * HELPER: writeStructReturnCplusStub() writes member parameters of struct for return statement
2962 private void writeStructReturnCplusStub(String simpleType, String retType, String method, InterfaceDecl intDecl) {
2964 // Minimum retLen is 1 if this is a single struct object
2965 println("int retLen = 0;");
2966 println("void* retLenObj = { &retLen };");
2967 // Handle the returned struct!!!
2968 println("rmiComm->remoteCall(objectId, methodId, paramCls, paramObj, numParam);");
2969 writeWaitForReturnValueCplus(method, intDecl, "rmiComm->getReturnValue(retType, retLenObj);");
2970 int numMem = getNumOfMembers(simpleType);
2971 println("int numRet = " + numMem + "*retLen;");
2972 println("string retCls[numRet];");
2973 println("void* retObj[numRet];");
2974 StructDecl structDecl = getStructDecl(simpleType);
2975 List<String> memTypes = structDecl.getMemberTypes(simpleType);
2976 List<String> members = structDecl.getMembers(simpleType);
2978 if (isArrayOrList(retType, retType)) { // An array or list
2979 for (int i = 0; i < members.size(); i++) {
2980 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
2981 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
2982 println(getSimpleType(getEnumType(prmType)) + " retParam" + i + "[retLen];");
2984 } else { // Just one struct element
2985 for (int i = 0; i < members.size(); i++) {
2986 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
2987 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
2988 println(getSimpleType(getEnumType(prmType)) + " retParam" + i + ";");
2991 println("int retPos = 0;");
2992 // Get the struct declaration for this struct and generate initialization code
2993 if (isArrayOrList(retType, retType)) { // An array or list
2994 println("for(int i = 0; i < retLen; i++) {");
2995 for (int i = 0; i < members.size(); i++) {
2996 String prmTypeC = checkAndGetCplusArgClsType(memTypes.get(i), members.get(i));
2997 println("retCls[retPos] = \"" + prmTypeC + "\";");
2998 println("retObj[retPos++] = &retParam" + i + "[i];");
3001 } else { // Just one struct element
3002 for (int i = 0; i < members.size(); i++) {
3003 String prmTypeC = checkAndGetCplusArgClsType(memTypes.get(i), members.get(i));
3004 println("retCls[retPos] = \"" + prmTypeC + "\";");
3005 println("retObj[retPos++] = &retParam" + i + ";");
3008 writeWaitForReturnValueCplus(method, intDecl, "rmiComm->getStructObjects(retCls, numRet, retObj);");
3009 if (isArrayOrList(retType, retType)) { // An array or list
3010 println("vector<" + simpleType + "> structRet(retLen);");
3012 println(simpleType + " structRet;");
3013 writeStructRetMembersCplusStub(simpleType, retType);
3018 * HELPER: writeWaitForReturnValueCplus() writes the synchronization part for return values
3020 private void writeWaitForReturnValueCplus(String method, InterfaceDecl intDecl, String getReturnValue) {
3022 println("// Waiting for return value");
3023 int methodNumId = intDecl.getMethodNumId(method);
3024 println("while (!retValueReceived" + methodNumId + ");");
3025 println(getReturnValue);
3026 println("retValueReceived" + methodNumId + " = false;");
3027 println("didGetReturnBytes.exchange(true);\n");
3032 * HELPER: writeStdMethodBodyCplusStub() writes the standard method body in the stub class
3034 private void writeStdMethodBodyCplusStub(InterfaceDecl intDecl, List<String> methParams,
3035 List<String> methPrmTypes, String method, Set<String> callbackType, boolean isCallbackMethod) {
3037 checkAndWriteStructSetupCplusStub(methParams, methPrmTypes, intDecl, method);
3038 println("int methodId = " + intDecl.getMethodNumId(method) + ";");
3039 String retType = intDecl.getMethodType(method);
3040 println("string retType = \"" + checkAndGetCplusRetClsType(getStructType(getEnumType(retType))) + "\";");
3041 checkAndWriteEnumTypeCplusStub(methParams, methPrmTypes);
3042 // Generate array of parameter types
3043 if (isStructPresent(methParams, methPrmTypes)) {
3044 writeStructParamClassCplusStub(methParams, methPrmTypes, callbackType);
3046 println("int numParam = " + methParams.size() + ";");
3047 print("string paramCls[] = { ");
3048 for (int i = 0; i < methParams.size(); i++) {
3049 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
3050 if (checkCallbackType(paramType, callbackType)) {
3053 String paramTypeC = checkAndGetCplusArgClsType(methPrmTypes.get(i), methParams.get(i));
3054 print("\"" + paramTypeC + "\"");
3056 // Check if this is the last element (don't print a comma)
3057 if (i != methParams.size() - 1) {
3062 // Generate array of parameter objects
3063 print("void* paramObj[] = { ");
3064 for (int i = 0; i < methParams.size(); i++) {
3065 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
3066 if (checkCallbackType(paramType, callbackType)) // Check if this has callback object
3067 print("&___paramCB" + i);
3069 print("&" + getEnumParam(methPrmTypes.get(i), getSimpleIdentifier(methParams.get(i)), i));
3070 // Check if this is the last element (don't print a comma)
3071 if (i != methParams.size() - 1) {
3077 // Check if this is "void"
3078 if (retType.equals("void")) {
3079 println("rmiComm->remoteCall(objectId, methodId, paramCls, paramObj, numParam);");
3080 } else { // We do have a return value
3081 // Generate array of parameter types
3082 if (isStructClass(getGenericType(getSimpleArrayType(retType)))) {
3083 writeStructReturnCplusStub(getGenericType(getSimpleArrayType(retType)), retType, method, intDecl);
3085 // Check if the return value NONPRIMITIVES
3086 if (isEnumClass(getSimpleArrayType(getGenericType(retType)))) {
3087 checkAndWriteEnumRetTypeCplusStub(retType, method, intDecl);
3089 //if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
3090 if (isArrayOrList(retType,retType))
3091 println(checkAndGetCplusType(retType) + " retVal;");
3093 println(checkAndGetCplusType(retType) + " retVal = " + generateCplusInitializer(retType) + ";");
3095 println("void* retObj = &retVal;");
3096 println("rmiComm->remoteCall(objectId, methodId, paramCls, paramObj, numParam);");
3097 writeWaitForReturnValueCplus(method, intDecl, "rmiComm->getReturnValue(retType, retObj);");
3098 println("return retVal;");
3106 * HELPER: writePropertiesCplusPermission() writes the properties of the stub class
3108 private void writePropertiesCplusPermission(String intface) {
3110 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3111 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3112 String newIntface = intMeth.getKey();
3113 int newObjectId = getNewIntfaceObjectId(newIntface);
3114 println("static set<int> set" + newObjectId + "Allowed;");
3119 * HELPER: writePropertiesCplusStub() writes the properties of the stub class
3121 private void writePropertiesCplusStub(String intface, String newIntface, boolean callbackExist,
3122 Set<String> callbackClasses, Set<String> methods, InterfaceDecl intDecl) {
3124 println("IoTRMIComm *rmiComm;");
3125 // Get the object Id
3126 Integer objId = mapIntfaceObjId.get(intface);
3127 println("int objectId = " + objId + ";");
3128 println("// Synchronization variables");
3129 for (String method : methods) {
3130 // Generate AtomicBooleans for methods that have return values
3131 String returnType = intDecl.getMethodType(method);
3132 int methodNumId = intDecl.getMethodNumId(method);
3133 if (!returnType.equals("void")) {
3134 println("bool retValueReceived" + methodNumId + " = false;");
3142 * HELPER: writeConstructorCplusStub() writes the constructor of the stub class
3144 private void writeConstructorCplusStub(String newStubClass, boolean callbackExist,
3145 Set<String> callbackClasses, Set<String> methods, InterfaceDecl intDecl) {
3147 println(newStubClass + "::" + newStubClass +
3148 "(int _portSend, int _portRecv, const char* _skeletonAddress, int _rev, bool* _bResult) {");
3149 println("rmiComm = new IoTRMICommClient(_portSend, _portRecv, _skeletonAddress, _rev, _bResult);");
3150 // Register the AtomicBoolean variables
3151 for (String method : methods) {
3152 // Generate AtomicBooleans for methods that have return values
3153 String returnType = intDecl.getMethodType(method);
3154 int methodNumId = intDecl.getMethodNumId(method);
3155 if (!returnType.equals("void")) {
3156 println("rmiComm->registerStub(objectId, " + methodNumId + ", &retValueReceived" + methodNumId + ");");
3159 println("IoTRMIUtil::mapStub->insert(make_pair(objectId, this));");
3165 * HELPER: writeCallbackConstructorCplusStub() writes the callback constructor of the stub class
3167 private void writeCallbackConstructorCplusStub(String newStubClass, boolean callbackExist,
3168 Set<String> callbackClasses, Set<String> methods, InterfaceDecl intDecl) {
3170 println(newStubClass + "::" + newStubClass + "(IoTRMIComm* _rmiComm, int _objectId) {");
3171 println("rmiComm = _rmiComm;");
3172 println("objectId = _objectId;");
3173 // Register the AtomicBoolean variables
3174 for (String method : methods) {
3175 // Generate AtomicBooleans for methods that have return values
3176 String returnType = intDecl.getMethodType(method);
3177 int methodNumId = intDecl.getMethodNumId(method);
3178 if (!returnType.equals("void")) {
3179 println("rmiComm->registerStub(objectId, " + methodNumId + ", &retValueReceived" + methodNumId + ");");
3187 * HELPER: writeDeconstructorCplusStub() writes the deconstructor of the stub class
3189 private void writeDeconstructorCplusStub(String newStubClass, boolean callbackExist, Set<String> callbackClasses) {
3191 println(newStubClass + "::~" + newStubClass + "() {");
3192 println("if (rmiComm != NULL) {");
3193 println("delete rmiComm;");
3194 println("rmiComm = NULL;");
3202 * generateCPlusStubClassesHpp() generate stubs based on the methods list in C++ (.hpp file)
3204 public void generateCPlusStubClassesHpp() throws IOException {
3206 // Create a new directory
3207 String path = createDirectories(dir, subdir);
3208 for (String intface : mapIntfacePTH.keySet()) {
3210 // Check if there is more than 1 class that uses the same interface
3211 List<String> drvList = mapInt2Drv.get(intface);
3212 for(int i = 0; i < drvList.size(); i++) {
3214 String driverClass = drvList.get(i);
3215 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3216 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3217 // Open a new file to write into
3218 String newIntface = intMeth.getKey();
3219 String newStubClass = newIntface + "_Stub";
3220 // Check if this interface is a callback class
3221 if(isCallbackClass(intface))
3222 path = createDirectories(dir + "/" + subdir + "/" + DRIVERS_DIRECTORY, driverClass);
3224 path = createDirectories(dir + "/" + subdir + "/" + CONTROLLER_DIRECTORY, controllerClass);
3225 FileWriter fw = new FileWriter(path + "/" + newStubClass + ".hpp");
3226 pw = new PrintWriter(new BufferedWriter(fw));
3227 // Write file headers
3228 println("#ifndef _" + newStubClass.toUpperCase() + "_HPP__");
3229 println("#define _" + newStubClass.toUpperCase() + "_HPP__");
3230 println("#include <iostream>");
3231 // Find out if there are callback objects
3232 Set<String> methods = intMeth.getValue();
3233 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
3234 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
3235 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
3236 boolean callbackExist = !callbackClasses.isEmpty();
3237 println("#include <thread>");
3238 println("#include <mutex>");
3239 List<String> stdIncludeClasses = getStandardCplusIncludeClasses();
3240 printIncludeStatements(stdIncludeClasses); println("");
3241 println("#include \"" + newIntface + ".hpp\""); println("");
3242 println("using namespace std;"); println("");
3243 println("class " + newStubClass + " : public " + newIntface); println("{");
3244 println("private:\n");
3245 writePropertiesCplusStub(intface, newIntface, callbackExist, callbackClasses, methods, intDecl);
3246 println("public:\n");
3247 // Add default constructor and destructor
3248 println(newStubClass + "();");
3250 println(newStubClass + "(int _portSend, int _portRecv, const char* _skeletonAddress, int _rev, bool* _bResult);");
3251 println(newStubClass + "(IoTRMIComm* _rmiComm, int _objectId);");
3252 println("~" + newStubClass + "();");
3254 writeMethodDeclCplusStub(methods, intDecl);
3255 print("}"); println(";");
3258 System.out.println("IoTCompiler: Generated stub class " + newStubClass + ".hpp...");
3266 * writeStubExternalCFunctions() generate external functions for .so file
3268 public void writeStubExternalCFunctions(String newStubClass) throws IOException {
3270 println("extern \"C\" void* create" + newStubClass + "(void** params) {");
3271 println("// Args: int _portSend, int _portRecv, const char* _skeletonAddress, int _rev, bool* _bResult");
3272 println("return new " + newStubClass + "(*((int*) params[0]), *((int*) params[1]), ((string*) params[2])->c_str(), " +
3273 "*((int*) params[3]), (bool*) params[4]);");
3275 println("extern \"C\" void destroy" + newStubClass + "(void* t) {");
3276 println(newStubClass + "* obj = (" + newStubClass + "*) t;");
3277 println("delete obj;");
3279 println("extern \"C\" void init" + newStubClass + "(void* t) {");
3285 * generateCPlusStubClassesCpp() generate stubs based on the methods list in C++ (.cpp file)
3287 public void generateCPlusStubClassesCpp() throws IOException {
3289 // Create a new directory
3290 String path = createDirectories(dir, subdir);
3291 for (String intface : mapIntfacePTH.keySet()) {
3293 // Check if there is more than 1 class that uses the same interface
3294 List<String> drvList = mapInt2Drv.get(intface);
3295 for(int i = 0; i < drvList.size(); i++) {
3297 String driverClass = drvList.get(i);
3298 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3299 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3300 // Open a new file to write into
3301 String newIntface = intMeth.getKey();
3302 String newStubClass = newIntface + "_Stub";
3303 // Check if this interface is a callback class
3304 if(isCallbackClass(intface))
3305 path = createDirectories(dir + "/" + subdir + "/" + DRIVERS_DIRECTORY, driverClass);
3307 path = createDirectories(dir + "/" + subdir + "/" + CONTROLLER_DIRECTORY, controllerClass);
3308 FileWriter fw = new FileWriter(path + "/" + newStubClass + ".cpp");
3309 pw = new PrintWriter(new BufferedWriter(fw));
3310 // Write file headers
3311 println("#include <iostream>");
3312 // Find out if there are callback objects
3313 Set<String> methods = intMeth.getValue();
3314 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
3315 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
3316 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
3317 boolean callbackExist = !callbackClasses.isEmpty();
3318 println("#include \"" + newStubClass + ".hpp\""); println("");
3319 for(String str: callbackClasses) {
3320 if (intface.equals(mainClass))
3321 println("#include \"" + str + "_Skeleton.cpp\"\n");
3323 println("#include \"" + str + "_Skeleton.hpp\"\n");
3325 println("using namespace std;"); println("");
3326 // Add default constructor and destructor
3327 writeConstructorCplusStub(newStubClass, callbackExist, callbackClasses, methods, intDecl);
3328 writeCallbackConstructorCplusStub(newStubClass, callbackExist, callbackClasses, methods, intDecl);
3329 writeDeconstructorCplusStub(newStubClass, callbackExist, callbackClasses);
3331 writeMethodCplusStub(methods, intDecl, callbackClasses, newStubClass);
3332 // Write external functions for .so file
3333 writeStubExternalCFunctions(newStubClass);
3334 // TODO: Remove this later
3335 if (intface.equals(mainClass)) {
3336 println("int main() {");
3337 println("return 0;");
3341 System.out.println("IoTCompiler: Generated stub class " + newStubClass + ".cpp...");
3349 * HELPER: writePropertiesCplusSkeleton() writes the properties of the skeleton class
3351 private void writePropertiesCplusSkeleton(String intface, boolean callbackExist, Set<String> callbackClasses) {
3353 println(intface + " *mainObj;");
3354 println("IoTRMIComm *rmiComm;");
3355 println("char* methodBytes;");
3356 println("int methodLen;");
3357 Integer objId = mapIntfaceObjId.get(intface);
3358 println("int objectId = " + objId + ";");
3359 // Keep track of object Ids of all stubs registered to this interface
3360 writePropertiesCplusPermission(intface);
3361 println("// Synchronization variables");
3362 println("bool methodReceived = false;");
3363 println("bool didAlreadyInitWaitInvoke = false;");
3369 * HELPER: writeObjectIdCountInitializationCplus() writes the initialization of objIdCnt variable
3371 private void writeObjectIdCountInitializationCplus(String newSkelClass, boolean callbackExist) {
3374 println("int " + newSkelClass + "::objIdCnt = 0;");
3379 * HELPER: writePermissionInitializationCplus() writes the initialization of permission set
3381 private void writePermissionInitializationCplus(String intface, String newSkelClass, InterfaceDecl intDecl) {
3383 // Keep track of object Ids of all stubs registered to this interface
3384 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3385 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3386 String newIntface = intMeth.getKey();
3387 int newObjectId = getNewIntfaceObjectId(newIntface);
3388 print("set<int> " + newSkelClass + "::set" + newObjectId + "Allowed { ");
3389 Set<String> methodIds = intMeth.getValue();
3391 for (String methodId : methodIds) {
3392 int methodNumId = intDecl.getMethodNumId(methodId);
3393 print(Integer.toString(methodNumId));
3394 // Check if this is the last element (don't print a comma)
3395 if (i != methodIds.size() - 1) {
3406 * HELPER: writeStructPermissionCplusSkeleton() writes permission for struct helper
3408 private void writeStructPermissionCplusSkeleton(Collection<String> methods, InterfaceDecl intDecl, String intface) {
3410 // Use this set to handle two same methodIds
3411 for (String method : methods) {
3412 List<String> methParams = intDecl.getMethodParams(method);
3413 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
3414 // Check for params with structs
3415 for (int i = 0; i < methParams.size(); i++) {
3416 String paramType = methPrmTypes.get(i);
3417 String param = methParams.get(i);
3418 String simpleType = getGenericType(paramType);
3419 if (isStructClass(simpleType)) {
3420 int methodNumId = intDecl.getMethodNumId(method);
3421 String helperMethod = methodNumId + "struct" + i;
3422 int helperMethodNumId = intDecl.getHelperMethodNumId(helperMethod);
3423 // Iterate over interfaces to give permissions to
3424 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3425 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3426 String newIntface = intMeth.getKey();
3427 int newObjectId = getNewIntfaceObjectId(newIntface);
3428 println("set" + newObjectId + "Allowed.insert(" + helperMethodNumId + ");");
3437 * HELPER: writeConstructorCplusSkeleton() writes the constructor of the skeleton class
3439 private void writeConstructorCplusSkeleton(String newSkelClass, String intface, boolean callbackExist, InterfaceDecl intDecl, Collection<String> methods) {
3441 println(newSkelClass + "::" + newSkelClass + "(" + intface + " *_mainObj, int _portSend, int _portRecv) {");
3442 println("bool _bResult = false;");
3443 println("mainObj = _mainObj;");
3444 println("rmiComm = new IoTRMICommServer(_portSend, _portRecv, &_bResult);");
3445 println("IoTRMIUtil::mapSkel->insert(make_pair(_mainObj, this));");
3446 println("IoTRMIUtil::mapSkelId->insert(make_pair(_mainObj, objectId));");
3447 println("rmiComm->registerSkeleton(objectId, &methodReceived);");
3448 writeStructPermissionCplusSkeleton(methods, intDecl, intface);
3449 println("thread th1 (&" + newSkelClass + "::___waitRequestInvokeMethod, this, this);");
3450 println("th1.join();");
3456 * HELPER: writeCallbackConstructorCplusSkeleton() writes the callback constructor of the skeleton class
3458 private void writeCallbackConstructorCplusSkeleton(String newSkelClass, String intface, boolean callbackExist, InterfaceDecl intDecl, Collection<String> methods) {
3460 println(newSkelClass + "::" + newSkelClass + "(" + intface + " *_mainObj, IoTRMIComm *_rmiComm, int _objectId) {");
3461 println("bool _bResult = false;");
3462 println("mainObj = _mainObj;");
3463 println("rmiComm = _rmiComm;");
3464 println("objectId = _objectId;");
3465 println("rmiComm->registerSkeleton(objectId, &methodReceived);");
3466 writeStructPermissionCplusSkeleton(methods, intDecl, intface);
3472 * HELPER: writeDeconstructorCplusSkeleton() writes the deconstructor of the skeleton class
3474 private void writeDeconstructorCplusSkeleton(String newSkelClass, boolean callbackExist, Set<String> callbackClasses) {
3476 println(newSkelClass + "::~" + newSkelClass + "() {");
3477 println("if (rmiComm != NULL) {");
3478 println("delete rmiComm;");
3479 println("rmiComm = NULL;");
3487 * HELPER: writeStdMethodBodyCplusSkeleton() writes the standard method body in the skeleton class
3489 private void writeStdMethodBodyCplusSkeleton(List<String> methParams, String methodId, String methodType) {
3491 if (methodType.equals("void"))
3492 print("mainObj->" + methodId + "(");
3494 print("return mainObj->" + methodId + "(");
3495 for (int i = 0; i < methParams.size(); i++) {
3497 print(getSimpleIdentifier(methParams.get(i)));
3498 // Check if this is the last element (don't print a comma)
3499 if (i != methParams.size() - 1) {
3508 * HELPER: writeMethodDeclCplusSkeleton() writes the method declaration of the skeleton class
3510 private void writeMethodDeclCplusSkeleton(Collection<String> methods, InterfaceDecl intDecl,
3511 Set<String> callbackClasses) {
3513 for (String method : methods) {
3515 List<String> methParams = intDecl.getMethodParams(method);
3516 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
3517 String methodId = intDecl.getMethodId(method);
3518 String methodType = checkAndGetCplusType(intDecl.getMethodType(method));
3519 print(methodType + " " + methodId + "(");
3520 boolean isCallbackMethod = false;
3521 String callbackType = null;
3522 for (int i = 0; i < methParams.size(); i++) {
3524 String origParamType = methPrmTypes.get(i);
3525 if (callbackClasses.contains(origParamType)) { // Check if this has callback object
3526 isCallbackMethod = true;
3527 callbackType = origParamType;
3529 String paramType = checkAndGetParamClass(methPrmTypes.get(i));
3530 String methPrmType = checkAndGetCplusType(paramType);
3531 String methParamComplete = checkAndGetCplusArray(methPrmType, methParams.get(i));
3532 print(methParamComplete);
3533 // Check if this is the last element (don't print a comma)
3534 if (i != methParams.size() - 1) {
3544 * HELPER: writeMethodCplusSkeleton() writes the method of the skeleton class
3546 private void writeMethodCplusSkeleton(Collection<String> methods, InterfaceDecl intDecl, String newSkelClass) {
3548 for (String method : methods) {
3550 List<String> methParams = intDecl.getMethodParams(method);
3551 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
3552 String methodId = intDecl.getMethodId(method);
3553 String methodType = checkAndGetCplusType(intDecl.getMethodType(method));
3554 print(methodType + " " + newSkelClass + "::" + methodId + "(");
3555 for (int i = 0; i < methParams.size(); i++) {
3557 String origParamType = methPrmTypes.get(i);
3558 String paramType = checkAndGetParamClass(methPrmTypes.get(i));
3559 String methPrmType = checkAndGetCplusType(paramType);
3560 String methParamComplete = checkAndGetCplusArray(methPrmType, methParams.get(i));
3561 print(methParamComplete);
3562 // Check if this is the last element (don't print a comma)
3563 if (i != methParams.size() - 1) {
3568 // Now, write the body of skeleton!
3569 writeStdMethodBodyCplusSkeleton(methParams, methodId, intDecl.getMethodType(method));
3576 * HELPER: writeCallbackCplusNumStubs() writes the numStubs variable
3578 private void writeCallbackCplusNumStubs(List<String> methParams, List<String> methPrmTypes, Set<String> callbackType) {
3580 for (int i = 0; i < methParams.size(); i++) {
3581 String paramType = methPrmTypes.get(i);
3582 String param = methParams.get(i);
3583 if (checkCallbackType(paramType, callbackType)) // Check if this has callback object
3584 println("vector<int> numStubIdArray" + i + ";");
3590 * HELPER: writeCallbackInstantiationCplusStubGeneration() writes the instantiation of callback stubs
3592 private void writeCallbackInstantiationCplusStubGeneration(String exchParamType, int counter) {
3594 println(exchParamType + "* newStub" + counter + " = NULL;");
3595 println("auto it" + counter + " = IoTRMIUtil::mapStub->find(objIdRecv" + counter + ");");
3596 println("if (it" + counter + " == IoTRMIUtil::mapStub->end()) {");
3597 println("newStub" + counter + " = new " + exchParamType + "_Stub(rmiComm, objIdRecv" + counter + ");");
3598 println("IoTRMIUtil::mapStub->insert(make_pair(objIdRecv" + counter + ", newStub" + counter + "));");
3599 println("rmiComm->setObjectIdCounter(objIdRecv" + counter + ");");
3600 println("rmiComm->decrementObjectIdCounter();");
3603 println("newStub" + counter + " = (" + exchParamType + "_Stub*) it" + counter + "->second;");
3609 * HELPER: writeCallbackCplusStubGeneration() writes the callback stub generation part
3611 private void writeCallbackCplusStubGeneration(List<String> methParams, List<String> methPrmTypes, Set<String> callbackType) {
3613 // Iterate over callback objects
3614 for (int i = 0; i < methParams.size(); i++) {
3615 String paramType = methPrmTypes.get(i);
3616 String param = methParams.get(i);
3617 // Generate a loop if needed
3618 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
3619 String exchParamType = checkAndGetParamClass(getGenericType(paramType));
3620 if (isArrayOrList(paramType, param)) {
3621 println("vector<" + exchParamType + "*> stub" + i + ";");
3622 println("for (int i = 0; i < numStubIdArray" + i + ".size(); i++) {");
3623 println("int objIdRecv" + i + " = numStubIdArray" + i + "[i];");
3624 writeCallbackInstantiationCplusStubGeneration(exchParamType, i);
3625 println("stub" + i + ".push_back(newStub" + i + ");");
3628 println("int objIdRecv" + i + " = numStubIdArray" + i + "[0];");
3629 writeCallbackInstantiationCplusStubGeneration(exchParamType, i);
3630 println(exchParamType + "* stub" + i + " = newStub" + i + ";");
3638 * HELPER: checkAndWriteEnumTypeCplusSkeleton() writes the enum type (convert from enum to int)
3640 private void checkAndWriteEnumTypeCplusSkeleton(List<String> methParams, List<String> methPrmTypes) {
3642 // Iterate and find enum declarations
3643 for (int i = 0; i < methParams.size(); i++) {
3644 String paramType = methPrmTypes.get(i);
3645 String param = methParams.get(i);
3646 String simpleType = getGenericType(paramType);
3647 if (isEnumClass(simpleType)) {
3648 // Check if this is enum type
3649 if (isArrayOrList(paramType, param)) { // An array
3650 println("int len" + i + " = paramEnumInt" + i + ".size();");
3651 println("vector<" + simpleType + "> paramEnum" + i + "(len" + i + ");");
3652 println("for (int i=0; i < len" + i + "; i++) {");
3653 println("paramEnum" + i + "[i] = (" + simpleType + ") paramEnumInt" + i + "[i];");
3655 } else { // Just one element
3656 println(simpleType + " paramEnum" + i + ";");
3657 println("paramEnum" + i + " = (" + simpleType + ") paramEnumInt" + i + "[0];");
3665 * HELPER: checkAndWriteEnumRetTypeCplusSkeleton() writes the enum return type (convert from enum to int)
3667 private void checkAndWriteEnumRetTypeCplusSkeleton(String retType) {
3669 // Strips off array "[]" for return type
3670 String pureType = getSimpleArrayType(getGenericType(retType));
3671 // Take the inner type of generic
3672 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
3673 pureType = getGenericType(retType);
3674 if (isEnumClass(pureType)) {
3675 // Check if this is enum type
3677 if (isArrayOrList(retType, retType)) { // An array
3678 println("int retLen = retEnum.size();");
3679 println("vector<int> retEnumInt(retLen);");
3680 println("for (int i=0; i < retLen; i++) {");
3681 println("retEnumInt[i] = (int) retEnum[i];");
3683 } else { // Just one element
3684 println("vector<int> retEnumInt(1);");
3685 println("retEnumInt[0] = (int) retEnum;");
3692 * HELPER: writeMethodInputParameters() writes the parameter variables for C++ skeleton
3694 private void writeMethodInputParameters(List<String> methParams, List<String> methPrmTypes,
3695 Set<String> callbackClasses, String methodId) {
3697 print(methodId + "(");
3698 for (int i = 0; i < methParams.size(); i++) {
3699 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
3700 if (callbackClasses.contains(paramType))
3702 else if (isEnumClass(getGenericType(paramType))) // Check if this is enum type
3703 print("paramEnum" + i);
3704 else if (isStructClass(getGenericType(paramType))) // Struct type
3705 print("paramStruct" + i);
3707 print(getSimpleIdentifier(methParams.get(i)));
3708 if (i != methParams.size() - 1) {
3717 * HELPER: writeMethodHelperReturnCplusSkeleton() writes the return statement part in skeleton
3719 private void writeMethodHelperReturnCplusSkeleton(InterfaceDecl intDecl, List<String> methParams,
3720 List<String> methPrmTypes, String method, boolean isCallbackMethod, Set<String> callbackType,
3721 String methodId, Set<String> callbackClasses) {
3723 println("rmiComm->getMethodParams(paramCls, numParam, paramObj, localMethodBytes);");
3724 if (isCallbackMethod)
3725 writeCallbackCplusStubGeneration(methParams, methPrmTypes, callbackType);
3726 checkAndWriteEnumTypeCplusSkeleton(methParams, methPrmTypes);
3727 writeStructMembersInitCplusSkeleton(intDecl, methParams, methPrmTypes, method);
3728 // Check if this is "void"
3729 String retType = intDecl.getMethodType(method);
3730 // Check if this is "void"
3731 if (retType.equals("void")) {
3732 writeMethodInputParameters(methParams, methPrmTypes, callbackClasses, methodId);
3733 } else { // We do have a return value
3734 if (isEnumClass(getSimpleArrayType(getGenericType(retType)))) // Enum type
3735 print(checkAndGetCplusType(retType) + " retEnum = ");
3736 else if (isStructClass(getSimpleArrayType(getGenericType(retType)))) // Struct type
3737 print(checkAndGetCplusType(retType) + " retStruct = ");
3739 print(checkAndGetCplusType(retType) + " retVal = ");
3740 writeMethodInputParameters(methParams, methPrmTypes, callbackClasses, methodId);
3741 checkAndWriteEnumRetTypeCplusSkeleton(retType);
3742 if (isStructClass(getSimpleArrayType(getGenericType(retType)))) // Struct type
3743 writeStructReturnCplusSkeleton(getSimpleArrayType(getGenericType(retType)), retType);
3744 if (isEnumClass(getSimpleArrayType(getGenericType(retType)))) // Enum type
3745 println("void* retObj = &retEnumInt;");
3747 if (!isStructClass(getSimpleArrayType(getGenericType(retType)))) // Struct type
3748 println("void* retObj = &retVal;");
3749 String retTypeC = checkAndGetCplusType(retType);
3750 if (isStructClass(getSimpleArrayType(getGenericType(retType)))) // Struct type
3751 println("rmiComm->sendReturnObj(retObj, retCls, numRetObj, localMethodBytes);");
3753 println("rmiComm->sendReturnObj(retObj, \"" + checkAndGetCplusRetClsType(getEnumType(retType)) + "\", localMethodBytes);");
3759 * HELPER: writeStdMethodHelperBodyCplusSkeleton() writes the standard method body helper in the skeleton class
3761 private void writeStdMethodHelperBodyCplusSkeleton(InterfaceDecl intDecl, List<String> methParams,
3762 List<String> methPrmTypes, String method, String methodId, Set<String> callbackClasses) {
3764 // Generate array of parameter types
3765 boolean isCallbackMethod = false;
3766 Set<String> callbackType = new HashSet<String>();
3767 print("string paramCls[] = { ");
3768 for (int i = 0; i < methParams.size(); i++) {
3769 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
3770 if (callbackClasses.contains(paramType)) {
3771 isCallbackMethod = true;
3772 callbackType.add(paramType);
3774 } else { // Generate normal classes if it's not a callback object
3775 String paramTypeC = checkAndGetCplusArgClsType(methPrmTypes.get(i), methParams.get(i));
3776 print("\"" + paramTypeC + "\"");
3778 if (i != methParams.size() - 1) {
3783 println("int numParam = " + methParams.size() + ";");
3784 if (isCallbackMethod)
3785 writeCallbackCplusNumStubs(methParams, methPrmTypes, callbackType);
3786 // Generate parameters
3787 for (int i = 0; i < methParams.size(); i++) {
3788 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
3789 if (!callbackClasses.contains(paramType)) {
3790 String methParamType = methPrmTypes.get(i);
3791 if (isEnumClass(getSimpleArrayType(getGenericType(methParamType)))) {
3792 // Check if this is enum type
3793 println("vector<int> paramEnumInt" + i + ";");
3795 String methPrmType = checkAndGetCplusType(methParamType);
3796 String methParamComplete = checkAndGetCplusArray(methPrmType, methParams.get(i));
3797 println(methParamComplete + ";");
3801 // Generate array of parameter objects
3802 print("void* paramObj[] = { ");
3803 for (int i = 0; i < methParams.size(); i++) {
3804 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
3805 if (callbackClasses.contains(paramType))
3806 print("&numStubIdArray" + i);
3807 else if (isEnumClass(getGenericType(paramType))) // Check if this is enum type
3808 print("¶mEnumInt" + i);
3810 print("&" + getSimpleIdentifier(methParams.get(i)));
3811 if (i != methParams.size() - 1) {
3816 // Write the return value part
3817 writeMethodHelperReturnCplusSkeleton(intDecl, methParams, methPrmTypes, method, isCallbackMethod,
3818 callbackType, methodId, callbackClasses);
3823 * HELPER: writeStructMembersCplusSkeleton() writes member parameters of struct
3825 private void writeStructMembersCplusSkeleton(String simpleType, String paramType,
3826 String param, String method, InterfaceDecl intDecl, int iVar) {
3828 // Get the struct declaration for this struct and generate initialization code
3829 StructDecl structDecl = getStructDecl(simpleType);
3830 List<String> memTypes = structDecl.getMemberTypes(simpleType);
3831 List<String> members = structDecl.getMembers(simpleType);
3832 int methodNumId = intDecl.getMethodNumId(method);
3833 String counter = "struct" + methodNumId + "Size" + iVar;
3835 if (isArrayOrList(paramType, param)) { // An array or list
3836 for (int i = 0; i < members.size(); i++) {
3837 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
3838 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
3839 println(getSimpleType(getEnumType(prmType)) + " param" + iVar + i + "[" + counter + "];");
3841 } else { // Just one struct element
3842 for (int i = 0; i < members.size(); i++) {
3843 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
3844 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
3845 println(getSimpleType(getEnumType(prmType)) + " param" + iVar + i + ";");
3848 if (isArrayOrList(paramType, param)) { // An array or list
3849 println("for(int i = 0; i < " + counter + "; i++) {");
3851 if (isArrayOrList(paramType, param)) { // An array or list
3852 for (int i = 0; i < members.size(); i++) {
3853 String prmTypeC = checkAndGetCplusArgClsType(memTypes.get(i), members.get(i));
3854 println("paramCls[pos] = \"" + prmTypeC + "\";");
3855 println("paramObj[pos++] = ¶m" + iVar + i + "[i];");
3858 } else { // Just one struct element
3859 for (int i = 0; i < members.size(); i++) {
3860 String prmTypeC = checkAndGetCplusArgClsType(memTypes.get(i), members.get(i));
3861 println("paramCls[pos] = \"" + prmTypeC + "\";");
3862 println("paramObj[pos++] = ¶m" + iVar + i + ";");
3869 * HELPER: writeStructMembersInitCplusSkeleton() writes member parameters initialization of struct
3871 private void writeStructMembersInitCplusSkeleton(InterfaceDecl intDecl, List<String> methParams,
3872 List<String> methPrmTypes, String method) {
3874 for (int i = 0; i < methParams.size(); i++) {
3875 String paramType = methPrmTypes.get(i);
3876 String param = methParams.get(i);
3877 String simpleType = getGenericType(paramType);
3878 if (isStructClass(simpleType)) {
3879 int methodNumId = intDecl.getMethodNumId(method);
3880 String counter = "struct" + methodNumId + "Size" + i;
3882 if (isArrayOrList(paramType, param)) { // An array or list
3883 println("vector<" + simpleType + "> paramStruct" + i + "(" + counter + ");");
3885 println(simpleType + " paramStruct" + i + ";");
3886 // Initialize members
3887 StructDecl structDecl = getStructDecl(simpleType);
3888 List<String> members = structDecl.getMembers(simpleType);
3889 List<String> memTypes = structDecl.getMemberTypes(simpleType);
3890 if (isArrayOrList(paramType, param)) { // An array or list
3891 println("for(int i = 0; i < " + counter + "; i++) {");
3892 for (int j = 0; j < members.size(); j++) {
3893 print("paramStruct" + i + "[i]." + getSimpleIdentifier(members.get(j)));
3894 println(" = param" + i + j + "[i];");
3897 } else { // Just one struct element
3898 for (int j = 0; j < members.size(); j++) {
3899 print("paramStruct" + i + "." + getSimpleIdentifier(members.get(j)));
3900 println(" = param" + i + j + ";");
3909 * HELPER: writeStructReturnCplusSkeleton() writes parameters of struct for return statement
3911 private void writeStructReturnCplusSkeleton(String simpleType, String retType) {
3913 // Minimum retLen is 1 if this is a single struct object
3914 if (isArrayOrList(retType, retType))
3915 println("int retLen = retStruct.size();");
3916 else // Just single struct object
3917 println("int retLen = 1;");
3918 println("void* retLenObj = &retLen;");
3919 println("rmiComm->sendReturnObj(retLenObj, \"int\", localMethodBytes);");
3920 int numMem = getNumOfMembers(simpleType);
3921 println("int numRetObj = " + numMem + "*retLen;");
3922 println("string retCls[numRetObj];");
3923 println("void* retObj[numRetObj];");
3924 println("int retPos = 0;");
3925 // Get the struct declaration for this struct and generate initialization code
3926 StructDecl structDecl = getStructDecl(simpleType);
3927 List<String> memTypes = structDecl.getMemberTypes(simpleType);
3928 List<String> members = structDecl.getMembers(simpleType);
3929 if (isArrayOrList(retType, retType)) { // An array or list
3930 println("for(int i = 0; i < retLen; i++) {");
3931 for (int i = 0; i < members.size(); i++) {
3932 String prmTypeC = checkAndGetCplusArgClsType(memTypes.get(i), members.get(i));
3933 println("retCls[retPos] = \"" + prmTypeC + "\";");
3934 print("retObj[retPos++] = &retStruct[i].");
3935 print(getEnumParam(memTypes.get(i), getSimpleIdentifier(members.get(i)), i));
3939 } else { // Just one struct element
3940 for (int i = 0; i < members.size(); i++) {
3941 String prmTypeC = checkAndGetCplusArgClsType(memTypes.get(i), members.get(i));
3942 println("retCls[retPos] = \"" + prmTypeC + "\";");
3943 print("retObj[retPos++] = &retStruct.");
3944 print(getEnumParam(memTypes.get(i), getSimpleIdentifier(members.get(i)), i));
3953 * HELPER: writeMethodHelperStructCplusSkeleton() writes the struct in skeleton
3955 private void writeMethodHelperStructCplusSkeleton(InterfaceDecl intDecl, List<String> methParams,
3956 List<String> methPrmTypes, String method, String methodId, Set<String> callbackClasses) {
3958 // Generate array of parameter objects
3959 boolean isCallbackMethod = false;
3960 Set<String> callbackType = new HashSet<String>();
3961 print("int numParam = ");
3962 writeLengthStructParamClassSkeleton(methParams, methPrmTypes, method, intDecl);
3964 println("string paramCls[numParam];");
3965 println("void* paramObj[numParam];");
3966 println("int pos = 0;");
3967 // Iterate again over the parameters
3968 for (int i = 0; i < methParams.size(); i++) {
3969 String paramType = methPrmTypes.get(i);
3970 String param = methParams.get(i);
3971 String simpleType = getGenericType(paramType);
3972 if (isStructClass(simpleType)) {
3973 writeStructMembersCplusSkeleton(simpleType, paramType, param, method, intDecl, i);
3975 String prmType = returnGenericCallbackType(methPrmTypes.get(i));
3976 if (callbackClasses.contains(prmType)) {
3977 isCallbackMethod = true;
3978 callbackType.add(prmType);
3979 println("vector<int> numStubIdArray" + i + ";");
3980 println("paramCls[pos] = \"int*\";");
3981 println("paramObj[pos++] = &numStubIdArray" + i + ";");
3982 } else { // Generate normal classes if it's not a callback object
3983 String paramTypeC = checkAndGetCplusType(methPrmTypes.get(i));
3984 if (isEnumClass(getGenericType(paramTypeC))) { // Check if this is enum type
3985 println("vector<int> paramEnumInt" + i + ";");
3987 String methParamComplete = checkAndGetCplusArray(paramTypeC, methParams.get(i));
3988 println(methParamComplete + ";");
3990 String prmTypeC = checkAndGetCplusArgClsType(methPrmTypes.get(i), methParams.get(i));
3991 println("paramCls[pos] = \"" + prmTypeC + "\";");
3992 if (isEnumClass(getGenericType(paramType))) // Check if this is enum type
3993 println("paramObj[pos++] = ¶mEnumInt" + i + ";");
3995 println("paramObj[pos++] = &" + getSimpleIdentifier(methParams.get(i)) + ";");
3999 // Write the return value part
4000 writeMethodHelperReturnCplusSkeleton(intDecl, methParams, methPrmTypes, method, isCallbackMethod,
4001 callbackType, methodId, callbackClasses);
4006 * HELPER: writeMethodHelperDeclCplusSkeleton() writes the method helper declarations of the skeleton class
4008 private void writeMethodHelperDeclCplusSkeleton(Collection<String> methods, InterfaceDecl intDecl, String newSkelClass) {
4010 // Use this set to handle two same methodIds
4011 Set<String> uniqueMethodIds = new HashSet<String>();
4012 for (String method : methods) {
4014 List<String> methParams = intDecl.getMethodParams(method);
4015 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4016 if (isStructPresent(methParams, methPrmTypes)) { // Treat struct differently
4017 String methodId = intDecl.getMethodId(method);
4019 String helperMethod = methodId;
4020 if (uniqueMethodIds.contains(methodId))
4021 helperMethod = helperMethod + intDecl.getMethodNumId(method);
4023 uniqueMethodIds.add(methodId);
4024 String retType = intDecl.getMethodType(method);
4025 print(helperMethod + "(");
4026 boolean begin = true;
4027 for (int i = 0; i < methParams.size(); i++) { // Print size variables
4028 String paramType = methPrmTypes.get(i);
4029 String param = methParams.get(i);
4030 String simpleType = getGenericType(paramType);
4031 if (isStructClass(simpleType)) {
4032 if (!begin) // Generate comma for not the beginning variable
4036 int methodNumId = intDecl.getMethodNumId(method);
4037 print("int struct" + methodNumId + "Size" + i);
4040 println(", " + newSkelClass + "* skel);");
4042 String methodId = intDecl.getMethodId(method);
4044 String helperMethod = methodId;
4045 if (uniqueMethodIds.contains(methodId))
4046 helperMethod = helperMethod + intDecl.getMethodNumId(method);
4048 uniqueMethodIds.add(methodId);
4049 // Check if this is "void"
4050 String retType = intDecl.getMethodType(method);
4051 println(helperMethod + "(" + newSkelClass + "* skel);");
4054 // Write method helper for structs
4055 writeMethodHelperStructDeclSetupCplusSkeleton(methods, intDecl, newSkelClass);
4060 * HELPER: writeMethodHelperStructDeclSetupCplusSkeleton() writes the struct method helper declaration in skeleton class
4062 private void writeMethodHelperStructDeclSetupCplusSkeleton(Collection<String> methods,
4063 InterfaceDecl intDecl, String newSkelClass) {
4065 // Use this set to handle two same methodIds
4066 for (String method : methods) {
4068 List<String> methParams = intDecl.getMethodParams(method);
4069 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4070 // Check for params with structs
4071 for (int i = 0; i < methParams.size(); i++) {
4072 String paramType = methPrmTypes.get(i);
4073 String param = methParams.get(i);
4074 String simpleType = getGenericType(paramType);
4075 if (isStructClass(simpleType)) {
4076 int methodNumId = intDecl.getMethodNumId(method);
4078 String helperMethod = methodNumId + "struct" + i;
4079 println(helperMethod + "(" + newSkelClass + "* skel);");
4087 * HELPER: writeMethodBytesCopy() writes the methodBytes copy part in C++ skeleton
4089 private void writeMethodBytesCopy() {
4091 println("char* localMethodBytes = new char[methodLen];");
4092 println("memcpy(localMethodBytes, skel->methodBytes, methodLen);");
4093 println("didGetMethodBytes.exchange(true);");
4098 * HELPER: writeMethodHelperCplusSkeleton() writes the method helper of the skeleton class
4100 private void writeMethodHelperCplusSkeleton(Collection<String> methods, InterfaceDecl intDecl,
4101 Set<String> callbackClasses, String newSkelClass) {
4103 // Use this set to handle two same methodIds
4104 Set<String> uniqueMethodIds = new HashSet<String>();
4105 for (String method : methods) {
4107 List<String> methParams = intDecl.getMethodParams(method);
4108 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4109 if (isStructPresent(methParams, methPrmTypes)) { // Treat struct differently
4110 String methodId = intDecl.getMethodId(method);
4111 print("void " + newSkelClass + "::___");
4112 String helperMethod = methodId;
4113 if (uniqueMethodIds.contains(methodId))
4114 helperMethod = helperMethod + intDecl.getMethodNumId(method);
4116 uniqueMethodIds.add(methodId);
4117 String retType = intDecl.getMethodType(method);
4118 print(helperMethod + "(");
4119 boolean begin = true;
4120 for (int i = 0; i < methParams.size(); i++) { // Print size variables
4121 String paramType = methPrmTypes.get(i);
4122 String param = methParams.get(i);
4123 String simpleType = getGenericType(paramType);
4124 if (isStructClass(simpleType)) {
4125 if (!begin) // Generate comma for not the beginning variable
4129 int methodNumId = intDecl.getMethodNumId(method);
4130 print("int struct" + methodNumId + "Size" + i);
4133 println(", " + newSkelClass + "* skel) {");
4134 writeMethodBytesCopy();
4135 writeMethodHelperStructCplusSkeleton(intDecl, methParams, methPrmTypes, method, methodId, callbackClasses);
4136 println("delete[] localMethodBytes;");
4139 String methodId = intDecl.getMethodId(method);
4140 print("void " + newSkelClass + "::___");
4141 String helperMethod = methodId;
4142 if (uniqueMethodIds.contains(methodId))
4143 helperMethod = helperMethod + intDecl.getMethodNumId(method);
4145 uniqueMethodIds.add(methodId);
4146 // Check if this is "void"
4147 String retType = intDecl.getMethodType(method);
4148 println(helperMethod + "(" + newSkelClass + "* skel) {");
4149 writeMethodBytesCopy();
4150 // Now, write the helper body of skeleton!
4151 writeStdMethodHelperBodyCplusSkeleton(intDecl, methParams, methPrmTypes, method, methodId, callbackClasses);
4152 println("delete[] localMethodBytes;");
4156 // Write method helper for structs
4157 writeMethodHelperStructSetupCplusSkeleton(methods, intDecl, newSkelClass);
4162 * HELPER: writeMethodHelperStructSetupCplusSkeleton() writes the method helper of struct in skeleton class
4164 private void writeMethodHelperStructSetupCplusSkeleton(Collection<String> methods,
4165 InterfaceDecl intDecl, String newSkelClass) {
4167 // Use this set to handle two same methodIds
4168 for (String method : methods) {
4170 List<String> methParams = intDecl.getMethodParams(method);
4171 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4172 // Check for params with structs
4173 for (int i = 0; i < methParams.size(); i++) {
4174 String paramType = methPrmTypes.get(i);
4175 String param = methParams.get(i);
4176 String simpleType = getGenericType(paramType);
4177 if (isStructClass(simpleType)) {
4178 int methodNumId = intDecl.getMethodNumId(method);
4179 print("int " + newSkelClass + "::___");
4180 String helperMethod = methodNumId + "struct" + i;
4181 println(helperMethod + "(" + newSkelClass + "* skel) {");
4182 // Now, write the helper body of skeleton!
4183 writeMethodBytesCopy();
4184 println("string paramCls[] = { \"int\" };");
4185 println("int numParam = 1;");
4186 println("int param0 = 0;");
4187 println("void* paramObj[] = { ¶m0 };");
4188 println("rmiComm->getMethodParams(paramCls, numParam, paramObj, localMethodBytes);");
4189 println("return param0;");
4190 println("delete[] localMethodBytes;");
4199 * HELPER: writeMethodHelperStructSetupCplusCallbackSkeleton() writes the method helper of struct in skeleton class
4201 private void writeMethodHelperStructSetupCplusCallbackSkeleton(Collection<String> methods,
4202 InterfaceDecl intDecl) {
4204 // Use this set to handle two same methodIds
4205 for (String method : methods) {
4207 List<String> methParams = intDecl.getMethodParams(method);
4208 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4209 // Check for params with structs
4210 for (int i = 0; i < methParams.size(); i++) {
4211 String paramType = methPrmTypes.get(i);
4212 String param = methParams.get(i);
4213 String simpleType = getGenericType(paramType);
4214 if (isStructClass(simpleType)) {
4215 int methodNumId = intDecl.getMethodNumId(method);
4217 String helperMethod = methodNumId + "struct" + i;
4218 println(helperMethod + "(IoTRMIObject* rmiObj) {");
4219 // Now, write the helper body of skeleton!
4220 println("string paramCls[] = { \"int\" };");
4221 println("int numParam = 1;");
4222 println("int param0 = 0;");
4223 println("void* paramObj[] = { ¶m0 };");
4224 println("rmiComm->getMethodParams(paramCls, numParam, paramObj, localMethodBytes);");
4225 println("return param0;");
4234 * HELPER: writeCplusMethodPermission() writes permission checks in skeleton
4236 private void writeCplusMethodPermission(String intface) {
4238 // Get all the different stubs
4239 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
4240 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
4241 String newIntface = intMeth.getKey();
4242 int newObjectId = getNewIntfaceObjectId(newIntface);
4243 println("if (_objectId == objectId) {");
4244 println("if (set" + newObjectId + "Allowed.find(methodId) == set" + newObjectId + "Allowed.end()) {");
4245 println("cerr << \"Object with object Id: \" << _objectId << \" is not allowed to access method: \" << methodId << endl;");
4250 println("continue;");
4257 * HELPER: writeCplusWaitRequestInvokeMethod() writes the main loop of the skeleton class
4259 private void writeCplusWaitRequestInvokeMethod(Collection<String> methods, InterfaceDecl intDecl,
4260 boolean callbackExist, String intface, String newSkelClass) {
4262 // Use this set to handle two same methodIds
4263 Set<String> uniqueMethodIds = new HashSet<String>();
4264 println("void " + newSkelClass + "::___waitRequestInvokeMethod(" + newSkelClass + "* skel) {");
4265 // Write variables here if we have callbacks or enums or structs
4266 writeCountVarStructSkeleton(methods, intDecl);
4267 println("skel->didAlreadyInitWaitInvoke = true;");
4268 println("while (true) {");
4269 println("if (!methodReceived) {");
4270 println("continue;");
4272 println("skel->methodBytes = skel->rmiComm->getMethodBytes();");
4273 println("skel->methodLen = skel->rmiComm->getMethodLength();");
4274 println("methodReceived = false;");
4275 println("int _objectId = skel->rmiComm->getObjectId(skel->methodBytes);");
4276 println("int methodId = skel->rmiComm->getMethodId(skel->methodBytes);");
4277 // Generate permission check
4278 writeCplusMethodPermission(intface);
4279 println("switch (methodId) {");
4280 // Print methods and method Ids
4281 for (String method : methods) {
4282 String methodId = intDecl.getMethodId(method);
4283 int methodNumId = intDecl.getMethodNumId(method);
4284 println("case " + methodNumId + ": {");
4285 print("thread th" + methodNumId + " (&" + newSkelClass + "::___");
4286 String helperMethod = methodId;
4287 if (uniqueMethodIds.contains(methodId))
4288 helperMethod = helperMethod + methodNumId;
4290 uniqueMethodIds.add(methodId);
4291 print(helperMethod + ", skel, ");
4292 boolean structExists = writeInputCountVarStructCplusSkeleton(method, intDecl);
4296 println("th" + methodNumId + ".detach(); break;");
4299 writeMethodCallStructCplusSkeleton(methods, intDecl);
4300 println("default: ");
4301 println("cerr << \"Method Id \" << methodId << \" not recognized!\" << endl;");
4310 * generateCplusSkeletonClassHpp() generate skeletons based on the methods list in C++ (.hpp file)
4312 public void generateCplusSkeletonClassHpp() throws IOException {
4314 // Create a new directory
4315 String path = createDirectories(dir, subdir);
4316 for (String intface : mapIntfacePTH.keySet()) {
4318 // Check if there is more than 1 class that uses the same interface
4319 List<String> drvList = mapInt2Drv.get(intface);
4320 for(int i = 0; i < drvList.size(); i++) {
4322 // Open a new file to write into
4323 String newSkelClass = intface + "_Skeleton";
4325 String driverClass = drvList.get(i);
4326 // Check if this interface is a callback class
4327 if(isCallbackClass(intface))
4328 path = createDirectories(dir + "/" + subdir + "/" + CONTROLLER_DIRECTORY, controllerClass);
4330 path = createDirectories(dir + "/" + subdir + "/" + DRIVERS_DIRECTORY, driverClass);
4331 FileWriter fw = new FileWriter(path + "/" + newSkelClass + ".hpp");
4332 pw = new PrintWriter(new BufferedWriter(fw));
4333 // Write file headers
4334 println("#ifndef _" + newSkelClass.toUpperCase() + "_HPP__");
4335 println("#define _" + newSkelClass.toUpperCase() + "_HPP__");
4336 println("#include <iostream>");
4337 println("#include \"" + intface + ".hpp\"\n");
4338 // Pass in set of methods and get import classes
4339 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4340 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
4341 List<String> methods = intDecl.getMethods();
4342 List<String> stdIncludeClasses = getStandardCplusIncludeClasses();
4343 printIncludeStatements(stdIncludeClasses); println("");
4344 println("using namespace std;\n");
4345 // Find out if there are callback objects
4346 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
4347 boolean callbackExist = !callbackClasses.isEmpty();
4348 // Write class header
4349 println("class " + newSkelClass + " : public " + intface); println("{");
4350 println("private:\n");
4352 writePropertiesCplusSkeleton(intface, callbackExist, callbackClasses);
4353 println("public:\n");
4354 // Write constructors
4355 println(newSkelClass + "();");
4356 println(newSkelClass + "(" + intface + "*_mainObj, int _portSend, int _portRecv);");
4357 println(newSkelClass + "(" + intface + "*_mainObj, IoTRMIComm *rmiComm, int _objectId);");
4358 // Write deconstructor
4359 println("~" + newSkelClass + "();");
4360 // Write method declarations
4361 println("bool didInitWaitInvoke();");
4362 writeMethodDeclCplusSkeleton(methods, intDecl, callbackClasses);
4363 // Write method helper declarations
4364 writeMethodHelperDeclCplusSkeleton(methods, intDecl, newSkelClass);
4365 // Write waitRequestInvokeMethod() declaration - main loop
4366 println("void ___waitRequestInvokeMethod(" + newSkelClass + "* skel);");
4368 writePermissionInitializationCplus(intface, newSkelClass, intDecl);
4371 System.out.println("IoTCompiler: Generated skeleton class " + newSkelClass + ".hpp...");
4377 * HELPER: writeReturnDidAlreadyInitWaitInvoke() writes the function to return didAlreadyInitWaitInvoke
4379 private void writeReturnDidAlreadyInitWaitInvoke(String newSkelClass) {
4381 println("bool " + newSkelClass + "::didInitWaitInvoke() {");
4382 println("return didAlreadyInitWaitInvoke;");
4388 * writeSkelExternalCFunctions() generate external functions for .so file
4390 public void writeSkelExternalCFunctions(String newSkelClass, String intface) throws IOException {
4392 println("extern \"C\" void* create" + newSkelClass + "(void** params) {");
4393 println("// Args: *_mainObj, int _portSend, int _portRecv");
4394 println("return new " + newSkelClass + "((" + intface + "*) params[0], *((int*) params[1]), *((int*) params[2]));");
4396 println("extern \"C\" void destroy" + newSkelClass + "(void* t) {");
4397 println(newSkelClass + "* obj = (" + newSkelClass + "*) t;");
4398 println("delete obj;");
4400 println("extern \"C\" void init" + newSkelClass + "(void* t) {");
4406 * generateCplusSkeletonClassCpp() generate skeletons based on the methods list in C++ (.cpp file)
4408 public void generateCplusSkeletonClassCpp() throws IOException {
4410 // Create a new directory
4411 String path = createDirectories(dir, subdir);
4412 for (String intface : mapIntfacePTH.keySet()) {
4414 // Check if there is more than 1 class that uses the same interface
4415 List<String> drvList = mapInt2Drv.get(intface);
4416 for(int i = 0; i < drvList.size(); i++) {
4418 // Open a new file to write into
4419 String newSkelClass = intface + "_Skeleton";
4421 String driverClass = drvList.get(i);
4422 // Check if this interface is a callback class
4423 if(isCallbackClass(intface))
4424 path = createDirectories(dir + "/" + subdir + "/" + CONTROLLER_DIRECTORY, controllerClass);
4426 path = createDirectories(dir + "/" + subdir + "/" + DRIVERS_DIRECTORY, driverClass);
4427 FileWriter fw = new FileWriter(path + "/" + newSkelClass + ".cpp");
4428 pw = new PrintWriter(new BufferedWriter(fw));
4429 // Write file headers
4430 println("#include <iostream>");
4431 println("#include \"" + newSkelClass + ".hpp\"\n");
4432 // Pass in set of methods and get import classes
4433 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4434 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
4435 List<String> methods = intDecl.getMethods();
4436 // Find out if there are callback objects
4437 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
4438 boolean callbackExist = !callbackClasses.isEmpty();
4439 for(String str: callbackClasses) {
4440 if (intface.equals(mainClass))
4441 println("#include \"" + getStubInterface(str) + "_Stub.cpp\"\n");
4443 println("#include \"" + getStubInterface(str) + "_Stub.hpp\"\n");
4445 println("using namespace std;\n");
4446 // Write constructor
4447 writeConstructorCplusSkeleton(newSkelClass, intface, callbackExist, intDecl, methods);
4448 // Write callback constructor
4449 writeCallbackConstructorCplusSkeleton(newSkelClass, intface, callbackExist, intDecl, methods);
4450 // Write deconstructor
4451 writeDeconstructorCplusSkeleton(newSkelClass, callbackExist, callbackClasses);
4452 // Write didInitWaitInvoke() to return bool
4453 writeReturnDidAlreadyInitWaitInvoke(newSkelClass);
4455 writeMethodCplusSkeleton(methods, intDecl, newSkelClass);
4456 // Write method helper
4457 writeMethodHelperCplusSkeleton(methods, intDecl, callbackClasses, newSkelClass);
4458 // Write waitRequestInvokeMethod() - main loop
4459 writeCplusWaitRequestInvokeMethod(methods, intDecl, callbackExist, intface, newSkelClass);
4460 // Write external functions for .so file
4461 writeSkelExternalCFunctions(newSkelClass, intface);
4462 // TODO: Remove this later
4463 if (intface.equals(mainClass)) {
4464 println("int main() {");
4465 println("return 0;");
4469 System.out.println("IoTCompiler: Generated skeleton class " + newSkelClass + ".cpp...");
4476 * generateInitializer() generate initializer based on type
4478 public String generateCplusInitializer(String type) {
4480 // Generate dummy returns for now
4481 if (type.equals("short")||
4482 type.equals("int") ||
4483 type.equals("long") ||
4484 type.equals("float")||
4485 type.equals("double")) {
4488 } else if ( type.equals("String") ||
4489 type.equals("string")) {
4492 } else if ( type.equals("char") ||
4493 type.equals("byte")) {
4496 } else if ( type.equals("boolean")) {
4506 * setDirectory() sets a new directory for stub files
4508 public void setDirectory(String _subdir) {
4515 * printUsage() prints the usage of this compiler
4517 public static void printUsage() {
4519 System.out.println();
4520 System.out.println("Vigilia interface and stub compiler version 1.0");
4521 System.out.println("Copyright (c) 2015-2016 University of California, Irvine - Programming Language Group.");
4522 System.out.println("All rights reserved.");
4523 System.out.println("Usage:");
4524 System.out.println("\tjava IoTCompiler -help / --help / -h\n");
4525 System.out.println("\t\tDisplay this help texts\n\n");
4526 System.out.println("\tjava IoTCompiler [<main-policy-file> <req-policy-file>]");
4527 System.out.println("\tjava IoTCompiler [<main-policy-file> <req-policy-file>] [options]\n");
4528 System.out.println("\t\tTake one or more pairs of main-req policy files, and generate Java and/or C++ files\n");
4529 System.out.println("Options:");
4530 System.out.println("\t-cont\t<controller-class>\tSpecify controller class name");
4531 System.out.println("\t-drv\t<driver-class>\t\tSpecify driver class name");
4532 System.out.println("\t\t(place this option right after a pair of .pol and .req files)");
4533 System.out.println("\t-objid\t<object-id>\t\tSpecify object Id for stub/skeleton used in multiple apps");
4534 System.out.println("\t\t(place this option right after -drv option)");
4535 System.out.println("\t-cplus\t<directory>\t\tGenerate C++ stub files");
4536 System.out.println("\t-java\t<directory>\t\tGenerate Java stub files\n");
4537 System.out.println("\t\tNote: The options -cont and -drv have to be defined before -cplus and -java");
4538 System.out.println();
4543 * parseFile() prepares Lexer and Parser objects, then parses the file
4545 public static ParseNode parseFile(String file) {
4547 ParseNode pn = null;
4549 ComplexSymbolFactory csf = new ComplexSymbolFactory();
4550 ScannerBuffer lexer =
4551 new ScannerBuffer(new Lexer(new BufferedReader(new FileReader(file)),csf));
4552 Parser parse = new Parser(lexer,csf);
4553 pn = (ParseNode) parse.parse().value;
4554 } catch (Exception e) {
4555 e.printStackTrace();
4556 throw new Error("IoTCompiler: ERROR parsing policy file or wrong command line option: " + file + "\n");
4564 * Basic helper functions
4567 boolean newline=true;
4570 private void print(String str) {
4573 if (str.equals("}"))
4575 for(int i=0; i<tab; i++)
4585 * This function converts Java to C++ type for compilation
4587 private String convertType(String type) {
4589 if (mapPrimitives.containsKey(type))
4590 return mapPrimitives.get(type);
4597 * A collection of methods with print-to-file functionality
4599 private void println(String str) {
4602 if (str.contains("}") && !str.contains("{"))
4604 for(int i=0; i<tab; i++)
4613 private void updatetabbing(String str) {
4615 tablevel+=count(str,'{')-count(str,'}');
4619 private int count(String str, char key) {
4620 char[] array = str.toCharArray();
4622 for(int i=0; i<array.length; i++) {
4623 if (array[i] == key)
4630 private void createDirectory(String dirName) {
4632 File file = new File(dirName);
4633 if (!file.exists()) {
4635 System.out.println("IoTCompiler: Directory " + dirName + " has been created!");
4637 System.out.println("IoTCompiler: Failed to create directory " + dirName + "!");
4640 System.out.println("IoTCompiler: Directory " + dirName + " exists...");
4645 // Create a directory and possibly a sub directory
4646 private String createDirectories(String dir, String subdir) {
4649 createDirectory(path);
4650 if (subdir != null) {
4651 path = path + "/" + subdir;
4652 createDirectory(path);
4658 // Inserting array members into a Map object
4659 // that maps arrKey to arrVal objects
4660 private void arraysToMap(Map map, Object[] arrKey, Object[] arrVal) {
4662 for(int i = 0; i < arrKey.length; i++) {
4664 map.put(arrKey[i], arrVal[i]);
4669 // Check and find object Id for new interface in mapNewIntfaceObjId (callbacks)
4670 // Throw an error if the new interface is not found!
4671 // Basically the compiler needs to parse the policy (and requires) files for callback class first
4672 private int getNewIntfaceObjectId(String newIntface) {
4674 int retObjId = mapNewIntfaceObjId.get(newIntface);
4679 // Return parameter category, i.e. PRIMITIVES, NONPRIMITIVES, USERDEFINED, ENUM, or STRUCT
4680 private ParamCategory getParamCategory(String paramType) {
4682 if (mapPrimitives.containsKey(paramType)) {
4683 return ParamCategory.PRIMITIVES;
4684 // We can either use mapNonPrimitivesJava or mapNonPrimitivesCplus here
4685 } else if (mapNonPrimitivesJava.containsKey(getSimpleType(paramType))) {
4686 return ParamCategory.NONPRIMITIVES;
4687 } else if (isEnumClass(paramType)) {
4688 return ParamCategory.ENUM;
4689 } else if (isStructClass(paramType)) {
4690 return ParamCategory.STRUCT;
4692 return ParamCategory.USERDEFINED;
4696 // Return full class name for non-primitives to generate Java import statements
4697 // e.g. java.util.Set for Set
4698 private String getNonPrimitiveJavaClass(String paramNonPrimitives) {
4700 return mapNonPrimitivesJava.get(paramNonPrimitives);
4704 // Return full class name for non-primitives to generate Cplus include statements
4705 // e.g. #include <set> for Set
4706 private String getNonPrimitiveCplusClass(String paramNonPrimitives) {
4708 return mapNonPrimitivesCplus.get(paramNonPrimitives);
4712 // Get simple types, e.g. HashSet for HashSet<...>
4713 // Basically strip off the "<...>"
4714 private String getSimpleType(String paramType) {
4716 // Check if this is generics
4717 if(paramType.contains("<")) {
4718 String[] type = paramType.split("<");
4725 // Generate a set of standard classes for import statements
4726 private List<String> getStandardJavaIntfaceImportClasses() {
4728 List<String> importClasses = new ArrayList<String>();
4729 // Add the standard list first
4730 importClasses.add("java.util.List");
4731 importClasses.add("java.util.ArrayList");
4733 return importClasses;
4737 // Generate a set of standard classes for import statements
4738 private List<String> getStandardJavaImportClasses() {
4740 List<String> importClasses = new ArrayList<String>();
4741 // Add the standard list first
4742 importClasses.add("java.io.IOException");
4743 importClasses.add("java.util.List");
4744 importClasses.add("java.util.ArrayList");
4745 importClasses.add("java.util.Arrays");
4746 importClasses.add("java.util.Map");
4747 importClasses.add("java.util.HashMap");
4748 importClasses.add("java.util.concurrent.atomic.AtomicBoolean");
4749 importClasses.add("iotrmi.Java.IoTRMIComm");
4750 importClasses.add("iotrmi.Java.IoTRMICommClient");
4751 importClasses.add("iotrmi.Java.IoTRMICommServer");
4752 importClasses.add("iotrmi.Java.IoTRMIUtil");
4754 return importClasses;
4758 // Generate a set of standard classes for import statements
4759 private List<String> getStandardCplusIncludeClasses() {
4761 List<String> importClasses = new ArrayList<String>();
4762 // Add the standard list first
4763 importClasses.add("<vector>");
4764 importClasses.add("<set>");
4765 importClasses.add("\"IoTRMIComm.hpp\"");
4766 importClasses.add("\"IoTRMICommClient.hpp\"");
4767 importClasses.add("\"IoTRMICommServer.hpp\"");
4769 return importClasses;
4773 // Combine all classes for import statements
4774 private List<String> getAllLibClasses(Collection<String> stdLibClasses, Collection<String> libClasses) {
4776 List<String> allLibClasses = new ArrayList<String>(stdLibClasses);
4777 // Iterate over the list of import classes
4778 for (String str : libClasses) {
4779 if (!allLibClasses.contains(str)) {
4780 allLibClasses.add(str);
4783 return allLibClasses;
4788 // Generate a set of classes for import statements
4789 private Set<String> getImportClasses(Collection<String> methods, InterfaceDecl intDecl) {
4791 Set<String> importClasses = new HashSet<String>();
4792 for (String method : methods) {
4793 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4794 for (String paramType : methPrmTypes) {
4796 String simpleType = getSimpleType(paramType);
4797 if (getParamCategory(simpleType) == ParamCategory.NONPRIMITIVES) {
4798 importClasses.add(getNonPrimitiveJavaClass(simpleType));
4802 return importClasses;
4806 // Handle and return the correct enum declaration
4807 // In Java, if we declare enum in Camera interface, then it becomes "Camera.<enum>"
4808 private String getEnumParamDecl(String type, InterfaceDecl intDecl) {
4810 // Strips off array "[]" for return type
4811 String pureType = getSimpleArrayType(type);
4812 // Take the inner type of generic
4813 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
4814 pureType = getTypeOfGeneric(type)[0];
4815 if (isEnumClass(pureType)) {
4816 String enumType = intDecl.getInterface() + "." + type;
4823 // Handle and return the correct type
4824 private String getEnumParam(String type, String param, int i) {
4826 // Strips off array "[]" for return type
4827 String pureType = getSimpleArrayType(type);
4828 // Take the inner type of generic
4829 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
4830 pureType = getTypeOfGeneric(type)[0];
4831 if (isEnumClass(pureType)) {
4832 String enumParam = "paramEnum" + i;
4839 // Handle and return the correct enum declaration translate into int[]
4840 private String getEnumType(String type) {
4842 // Strips off array "[]" for return type
4843 String pureType = getSimpleArrayType(type);
4844 // Take the inner type of generic
4845 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
4846 pureType = getGenericType(type);
4847 if (isEnumClass(pureType)) {
4848 String enumType = "int[]";
4854 // Handle and return the correct enum declaration translate into int* for C
4855 private String getEnumCplusClsType(String type) {
4857 // Strips off array "[]" for return type
4858 String pureType = getSimpleArrayType(type);
4859 // Take the inner type of generic
4860 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
4861 pureType = getGenericType(type);
4862 if (isEnumClass(pureType)) {
4863 String enumType = "int*";
4870 // Handle and return the correct struct declaration
4871 private String getStructType(String type) {
4873 // Strips off array "[]" for return type
4874 String pureType = getSimpleArrayType(type);
4875 // Take the inner type of generic
4876 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
4877 pureType = getGenericType(type);
4878 if (isStructClass(pureType)) {
4879 String structType = "int";
4886 // Check if this an enum declaration
4887 private boolean isEnumClass(String type) {
4889 // Just iterate over the set of interfaces
4890 for (String intface : mapIntfacePTH.keySet()) {
4891 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4892 EnumDecl enumDecl = (EnumDecl) decHandler.getEnumDecl(intface);
4893 Set<String> setEnumDecl = enumDecl.getEnumDeclarations();
4894 if (setEnumDecl.contains(type))
4901 // Check if this an struct declaration
4902 private boolean isStructClass(String type) {
4904 // Just iterate over the set of interfaces
4905 for (String intface : mapIntfacePTH.keySet()) {
4906 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4907 StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
4908 List<String> listStructDecl = structDecl.getStructTypes();
4909 if (listStructDecl.contains(type))
4916 // Return a struct declaration
4917 private StructDecl getStructDecl(String type) {
4919 // Just iterate over the set of interfaces
4920 for (String intface : mapIntfacePTH.keySet()) {
4921 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4922 StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
4923 List<String> listStructDecl = structDecl.getStructTypes();
4924 if (listStructDecl.contains(type))
4931 // Return number of members (-1 if not found)
4932 private int getNumOfMembers(String type) {
4934 // Just iterate over the set of interfaces
4935 for (String intface : mapIntfacePTH.keySet()) {
4936 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4937 StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
4938 List<String> listStructDecl = structDecl.getStructTypes();
4939 if (listStructDecl.contains(type))
4940 return structDecl.getNumOfMembers(type);
4946 // Generate a set of classes for include statements
4947 private Set<String> getIncludeClasses(Collection<String> methods, InterfaceDecl intDecl, String intface, boolean needExchange) {
4949 Set<String> includeClasses = new HashSet<String>();
4950 for (String method : methods) {
4952 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4953 List<String> methParams = intDecl.getMethodParams(method);
4954 for (int i = 0; i < methPrmTypes.size(); i++) {
4956 String genericType = getGenericType(methPrmTypes.get(i));
4957 String simpleType = getSimpleType(methPrmTypes.get(i));
4958 String param = methParams.get(i);
4959 if (getParamCategory(simpleType) == ParamCategory.NONPRIMITIVES) {
4960 includeClasses.add("<" + getNonPrimitiveCplusClass(simpleType) + ">");
4961 //} else if (getParamCategory(simpleType) == ParamCategory.USERDEFINED) {
4963 if (getParamCategory(getSimpleArrayType(genericType)) == ParamCategory.USERDEFINED) {
4964 // For original interface, we need it exchanged... not for stub interfaces
4966 //includeClasses.add("\"" + exchangeParamType(simpleType) + ".hpp\"");
4967 includeClasses.add("\"" + exchangeParamType(getSimpleArrayType(genericType)) + ".hpp\"");
4969 //includeClasses.add("\"" + simpleType + ".hpp\"");
4970 includeClasses.add("\"" + getSimpleArrayType(genericType) + ".hpp\"");
4973 if (getParamCategory(getSimpleArrayType(genericType)) == ParamCategory.ENUM) {
4974 includeClasses.add("\"" + genericType + ".hpp\"");
4976 if (getParamCategory(getSimpleArrayType(genericType)) == ParamCategory.STRUCT) {
4977 includeClasses.add("\"" + genericType + ".hpp\"");
4979 if (param.contains("[]")) {
4980 // Check if this is array for C++; translate into vector
4981 includeClasses.add("<vector>");
4985 return includeClasses;
4989 // Generate a set of callback classes
4990 private Set<String> getCallbackClasses(Collection<String> methods, InterfaceDecl intDecl) {
4992 Set<String> callbackClasses = new HashSet<String>();
4993 for (String method : methods) {
4995 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4996 List<String> methParams = intDecl.getMethodParams(method);
4997 for (int i = 0; i < methPrmTypes.size(); i++) {
4999 String type = methPrmTypes.get(i);
5000 if (getParamCategory(type) == ParamCategory.USERDEFINED) {
5001 callbackClasses.add(type);
5002 } else if (getParamCategory(type) == ParamCategory.NONPRIMITIVES) {
5003 // Can be a List<...> of callback objects ...
5004 String genericType = getTypeOfGeneric(type)[0];
5005 if (getParamCategory(type) == ParamCategory.USERDEFINED) {
5006 callbackClasses.add(type);
5011 return callbackClasses;
5015 // Check if this is a callback class
5016 private boolean isCallbackClass(String className) {
5018 Set<String> intfaceSet = mapIntDeclHand.keySet();
5019 for(String intface : intfaceSet) {
5021 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
5022 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
5023 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
5024 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
5025 Set<String> methods = intMeth.getValue();
5026 for (String method : methods) {
5028 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
5029 List<String> methParams = intDecl.getMethodParams(method);
5030 for (int i = 0; i < methPrmTypes.size(); i++) {
5032 String type = methPrmTypes.get(i);
5033 if (getParamCategory(type) == ParamCategory.USERDEFINED) {
5034 // Final check to see if this is the searched class
5035 if (type.equals(className))
5037 } else if (getParamCategory(type) == ParamCategory.NONPRIMITIVES) {
5038 // Can be a List<...> of callback objects ...
5039 String genericType = getTypeOfGeneric(type)[0];
5040 if (getParamCategory(type) == ParamCategory.USERDEFINED) {
5041 if (type.equals(className))
5054 // Print import statements into file
5055 private void printImportStatements(Collection<String> importClasses) {
5057 for(String cls : importClasses) {
5058 println("import " + cls + ";");
5063 // Print include statements into file
5064 private void printIncludeStatements(Collection<String> includeClasses) {
5066 for(String cls : includeClasses) {
5067 println("#include " + cls);
5072 // Get the C++ version of a non-primitive type
5073 // e.g. set for Set and map for Map
5074 // Input nonPrimitiveType has to be generics in format
5075 private String[] getTypeOfGeneric(String nonPrimitiveType) {
5077 // Handle <, >, and , for 2-type generic/template
5078 String[] substr = nonPrimitiveType.split("<")[1].split(">")[0].split(",");
5083 // Gets generic type inside "<" and ">"
5084 private String getGenericType(String type) {
5086 // Handle <, >, and , for 2-type generic/template
5087 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES) {
5088 String[] substr = type.split("<")[1].split(">")[0].split(",");
5095 // This helper function strips off array declaration, e.g. int[] becomes int
5096 private String getSimpleArrayType(String type) {
5098 // Handle [ for array declaration
5099 String substr = type;
5100 if (type.contains("[]")) {
5101 substr = type.split("\\[\\]")[0];
5107 // This helper function strips off array declaration, e.g. D[] becomes D
5108 private String getSimpleIdentifier(String ident) {
5110 // Handle [ for array declaration
5111 String substr = ident;
5112 if (ident.contains("[]")) {
5113 substr = ident.split("\\[\\]")[0];
5119 // Checks and gets type in C++
5120 private String checkAndGetCplusType(String paramType) {
5122 if (getParamCategory(paramType) == ParamCategory.PRIMITIVES) {
5123 return convertType(paramType);
5124 } else if (getParamCategory(paramType) == ParamCategory.NONPRIMITIVES) {
5126 // Check for generic/template format
5127 if (paramType.contains("<") && paramType.contains(">")) {
5129 String genericClass = getSimpleType(paramType);
5130 String genericType = getGenericType(paramType);
5131 String cplusTemplate = null;
5132 cplusTemplate = getNonPrimitiveCplusClass(genericClass);
5133 if(getParamCategory(getGenericType(paramType)) == ParamCategory.USERDEFINED) {
5134 cplusTemplate = cplusTemplate + "<" + genericType + "*>";
5136 cplusTemplate = cplusTemplate + "<" + convertType(genericType) + ">";
5138 return cplusTemplate;
5140 return getNonPrimitiveCplusClass(paramType);
5141 } else if(paramType.contains("[]")) { // Array type (used for return type only)
5142 String cArray = "vector<" + convertType(getSimpleArrayType(paramType)) + ">";
5144 } else if(getParamCategory(paramType) == ParamCategory.USERDEFINED) {
5145 return paramType + "*";
5147 // Just return it as is if it's not non-primitives
5152 // Detect array declaration, e.g. int A[],
5153 // then generate "int A[]" in C++ as "vector<int> A"
5154 private String checkAndGetCplusArray(String paramType, String param) {
5156 String paramComplete = null;
5157 // Check for array declaration
5158 if (param.contains("[]")) {
5159 paramComplete = "vector<" + paramType + "> " + param.replace("[]","");
5161 // Just return it as is if it's not an array
5162 paramComplete = paramType + " " + param;
5164 return paramComplete;
5168 // Detect array declaration, e.g. int A[],
5169 // then generate "int A[]" in C++ as "vector<int> A"
5170 // This method just returns the type
5171 private String checkAndGetCplusArrayType(String paramType) {
5173 String paramTypeRet = null;
5174 // Check for array declaration
5175 if (paramType.contains("[]")) {
5176 String type = paramType.split("\\[\\]")[0];
5177 paramTypeRet = checkAndGetCplusType(type) + "[]";
5178 } else if (paramType.contains("vector")) {
5179 // Just return it as is if it's not an array
5180 String type = paramType.split("<")[1].split(">")[0];
5181 paramTypeRet = checkAndGetCplusType(type) + "[]";
5183 paramTypeRet = paramType;
5185 return paramTypeRet;
5189 // Detect array declaration, e.g. int A[],
5190 // then generate "int A[]" in C++ as "vector<int> A"
5191 // This method just returns the type
5192 private String checkAndGetCplusArrayType(String paramType, String param) {
5194 String paramTypeRet = null;
5195 // Check for array declaration
5196 if (param.contains("[]")) {
5197 paramTypeRet = checkAndGetCplusType(paramType) + "[]";
5198 } else if (paramType.contains("vector")) {
5199 // Just return it as is if it's not an array
5200 String type = paramType.split("<")[1].split(">")[0];
5201 paramTypeRet = checkAndGetCplusType(type) + "[]";
5203 paramTypeRet = paramType;
5205 return paramTypeRet;
5209 // Return the class type for class resolution (for return value)
5210 // - Check and return C++ array class, e.g. int A[] into int*
5211 // - Check and return C++ vector class, e.g. List<Integer> A into vector<int>
5212 private String checkAndGetCplusRetClsType(String paramType) {
5214 String paramTypeRet = null;
5215 // Check for array declaration
5216 if (paramType.contains("[]")) {
5217 String type = paramType.split("\\[\\]")[0];
5218 paramTypeRet = getSimpleArrayType(type) + "*";
5219 } else if (paramType.contains("<") && paramType.contains(">")) {
5220 // Just return it as is if it's not an array
5221 String type = paramType.split("<")[1].split(">")[0];
5222 paramTypeRet = "vector<" + getGenericType(type) + ">";
5224 paramTypeRet = paramType;
5226 return paramTypeRet;
5230 // Return the class type for class resolution (for method arguments)
5231 // - Check and return C++ array class, e.g. int A[] into int*
5232 // - Check and return C++ vector class, e.g. List<Integer> A into vector<int>
5233 private String checkAndGetCplusArgClsType(String paramType, String param) {
5235 String paramTypeRet = getEnumCplusClsType(paramType);
5236 if (!paramTypeRet.equals(paramType))
5237 // Just return if it is an enum type
5238 // Type will still be the same if it's not an enum type
5239 return paramTypeRet;
5241 // Check for array declaration
5242 if (param.contains("[]")) {
5243 paramTypeRet = getSimpleArrayType(paramType) + "*";
5244 } else if (paramType.contains("<") && paramType.contains(">")) {
5245 // Just return it as is if it's not an array
5246 String type = paramType.split("<")[1].split(">")[0];
5247 paramTypeRet = "vector<" + getGenericType(type) + ">";
5249 paramTypeRet = paramType;
5251 return paramTypeRet;
5255 // Detect array declaration, e.g. int A[],
5256 // then generate type "int[]"
5257 private String checkAndGetArray(String paramType, String param) {
5259 String paramTypeRet = null;
5260 // Check for array declaration
5261 if (param.contains("[]")) {
5262 paramTypeRet = paramType + "[]";
5264 // Just return it as is if it's not an array
5265 paramTypeRet = paramType;
5267 return paramTypeRet;
5271 // Is array or list?
5272 private boolean isArrayOrList(String paramType, String param) {
5274 // Check for array declaration
5277 else if (isList(paramType))
5285 // For return type we use retType as input parameter
5286 private boolean isArray(String param) {
5288 // Check for array declaration
5289 if (param.contains("[]"))
5297 private boolean isList(String paramType) {
5299 // Check for array declaration
5300 if (paramType.contains("List"))
5307 // Get the right type for a callback object
5308 private String checkAndGetParamClass(String paramType) {
5310 // Check if this is generics
5311 if(getParamCategory(paramType) == ParamCategory.USERDEFINED) {
5312 return exchangeParamType(paramType);
5313 } else if (isList(paramType) &&
5314 (getParamCategory(getGenericType(paramType)) == ParamCategory.USERDEFINED)) {
5315 return "List<" + exchangeParamType(getGenericType(paramType)) + ">";
5321 // Returns the other interface for type-checking purposes for USERDEFINED
5322 // classes based on the information provided in multiple policy files
5323 // e.g. return CameraWithXXX instead of Camera
5324 private String exchangeParamType(String intface) {
5326 // Param type that's passed is the interface name we need to look for
5327 // in the map of interfaces, based on available policy files.
5328 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
5329 if (decHandler != null) {
5330 // We've found the required interface policy files
5331 RequiresDecl reqDecl = (RequiresDecl) decHandler.getRequiresDecl(intface);
5332 Set<String> setExchInt = reqDecl.getInterfaces();
5333 if (setExchInt.size() == 1) {
5334 Iterator iter = setExchInt.iterator();
5335 return (String) iter.next();
5337 throw new Error("IoTCompiler: Ambiguous stub interfaces: " + setExchInt.toString() +
5338 ". Only one new interface can be declared if the object " + intface +
5339 " needs to be passed in as an input parameter!\n");
5342 // NULL value - this means policy files missing
5343 throw new Error("IoTCompiler: Parameter type lookup failed for " + intface +
5344 "... Please provide the necessary policy files for user-defined types." +
5345 " If this is an array please type the brackets after the variable name," +
5346 " e.g. \"String str[]\", not \"String[] str\"." +
5347 " If this is a Collections (Java) / STL (C++) type, this compiler only" +
5348 " supports List/ArrayList (Java) or list (C++).\n");
5353 public static void main(String[] args) throws Exception {
5355 // If there is no argument or just "--help" or "-h", then invoke printUsage()
5356 if ((args.length == 0 ||
5357 args[0].equals("-help") ||
5358 args[0].equals("--help")||
5359 args[0].equals("-h"))) {
5361 IoTCompiler.printUsage();
5363 } else if (args.length > 1) {
5365 IoTCompiler comp = new IoTCompiler();
5367 boolean controllerDefined = false;
5369 if (!controllerDefined && args[i].equals("-cont")) {
5370 comp.setControllerClass(args[i+1]);
5371 controllerDefined = true;
5374 // Parse main policy file
5375 ParseNode pnPol = IoTCompiler.parseFile(args[i]);
5376 // Parse "requires" policy file
5377 ParseNode pnReq = IoTCompiler.parseFile(args[i+1]);
5378 // Get interface name
5379 String intface = ParseTreeHandler.getOrigIntface(pnPol);
5380 comp.setDataStructures(intface, pnPol, pnReq);
5381 comp.getMethodsForIntface(intface);
5384 if (args[i].equals("-drv")) {
5385 comp.setDriverClass(intface, args[i+1]);
5388 throw new Error("IoTCompiler: ERROR - driver class name is needed for the interface: " + intface + "\n");
5389 // Object ID (for a stub/skeleton pair that is also used in other applications)
5390 if (args[i].equals("-objid")) {
5391 comp.setObjectId(intface, args[i+1]);
5395 // 1) Check if this is the last option before "-java" or "-cplus"
5396 // 2) Check if this is really the last option
5397 } while(!args[i].equals("-java") &&
5398 !args[i].equals("-cplus") &&
5400 // Controller class name needs to be defined at least once
5401 if (!controllerDefined)
5402 throw new Error("IoTCompiler: ERROR - controller class name has not been specified!\n");
5404 // Generate everything if we don't see "-java" or "-cplus"
5405 if (i == args.length) {
5406 comp.generateEnumJava();
5407 comp.generateStructJava();
5408 comp.generateJavaLocalInterfaces();
5409 comp.generateJavaInterfaces();
5410 comp.generateJavaStubClasses();
5411 comp.generateJavaSkeletonClass();
5412 comp.generateEnumCplus();
5413 comp.generateStructCplus();
5414 comp.generateCplusLocalInterfaces();
5415 comp.generateCPlusInterfaces();
5416 comp.generateCPlusStubClassesHpp();
5417 comp.generateCPlusStubClassesCpp();
5418 comp.generateCplusSkeletonClassHpp();
5419 comp.generateCplusSkeletonClassCpp();
5421 // Check other options
5422 while(i < args.length) {
5424 if (!args[i].equals("-java") &&
5425 !args[i].equals("-cplus")) {
5426 throw new Error("IoTCompiler: ERROR - unrecognized command line option: " + args[i] + "\n");
5428 if (i + 1 < args.length) {
5429 comp.setDirectory(args[i+1]);
5431 throw new Error("IoTCompiler: ERROR - please provide <directory> after option: " + args[i] + "\n");
5433 if (args[i].equals("-java")) {
5434 comp.generateEnumJava();
5435 comp.generateStructJava();
5436 comp.generateJavaLocalInterfaces();
5437 comp.generateJavaInterfaces();
5438 comp.generateJavaStubClasses();
5439 comp.generateJavaSkeletonClass();
5441 comp.generateEnumCplus();
5442 comp.generateStructCplus();
5443 comp.generateCplusLocalInterfaces();
5444 comp.generateCPlusInterfaces();
5445 comp.generateCPlusStubClassesHpp();
5446 comp.generateCPlusStubClassesCpp();
5447 comp.generateCplusSkeletonClassHpp();
5448 comp.generateCplusSkeletonClassCpp();
5455 // Need to at least have exactly 2 parameters, i.e. main policy file and requires file
5456 IoTCompiler.printUsage();
5457 throw new Error("IoTCompiler: At least two arguments (main and requires policy files) have to be provided!\n");