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 // Data structure to store our types (primitives and non-primitives) for compilation
53 private Map<String,String> mapPrimitives;
54 private Map<String,String> mapNonPrimitivesJava;
55 private Map<String,String> mapNonPrimitivesCplus;
56 // Other data structures
57 private Map<String,Integer> mapIntfaceObjId; // Maps interface name to object Id
58 private Map<String,Integer> mapNewIntfaceObjId; // Maps new interface name to its object Id (keep track of stubs)
59 private PrintWriter pw;
61 private String subdir;
62 private Map<String,Integer> mapPortCount; // Counter for ports
63 private static int portCount = 0;
64 private static int countObjId = 1; // Always increment object Id for a new stub/skeleton
65 private String mainClass;
71 private final static String OUTPUT_DIRECTORY = "output_files";
73 private enum ParamCategory {
75 PRIMITIVES, // All the primitive types, e.g. byte, short, int, long, etc.
76 NONPRIMITIVES, // Non-primitive types, e.g. Set, Map, List, etc.
78 STRUCT, // Struct type
79 USERDEFINED // Assumed as driver classes
86 public IoTCompiler() {
88 mapIntfacePTH = new HashMap<String,ParseTreeHandler>();
89 mapIntDeclHand = new HashMap<String,DeclarationHandler>();
90 mapInt2NewInts = new HashMap<String,Map<String,Set<String>>>();
91 mapInt2NewIntName = new HashMap<String,String>();
92 mapIntfaceObjId = new HashMap<String,Integer>();
93 mapNewIntfaceObjId = new HashMap<String,Integer>();
94 mapPrimitives = new HashMap<String,String>();
95 arraysToMap(mapPrimitives, IoTRMITypes.primitivesJava, IoTRMITypes.primitivesCplus);
96 mapNonPrimitivesJava = new HashMap<String,String>();
97 arraysToMap(mapNonPrimitivesJava, IoTRMITypes.nonPrimitivesJava, IoTRMITypes.nonPrimitiveJavaLibs);
98 mapNonPrimitivesCplus = new HashMap<String,String>();
99 arraysToMap(mapNonPrimitivesCplus, IoTRMITypes.nonPrimitivesJava, IoTRMITypes.nonPrimitivesCplus);
100 mapPortCount = new HashMap<String,Integer>();
102 dir = OUTPUT_DIRECTORY;
109 * setDataStructures() sets parse tree and other data structures based on policy files.
111 * It also generates parse tree (ParseTreeHandler) and
112 * copies useful information from parse tree into
113 * InterfaceDecl, CapabilityDecl, and RequiresDecl
115 * Additionally, the data structure handles are
116 * returned from tree-parsing for further process.
118 public void setDataStructures(String origInt, ParseNode pnPol, ParseNode pnReq) {
120 ParseTreeHandler ptHandler = new ParseTreeHandler(origInt, pnPol, pnReq);
121 DeclarationHandler decHandler = new DeclarationHandler();
122 // Process ParseNode and generate Declaration objects
124 ptHandler.processInterfaceDecl();
125 InterfaceDecl intDecl = ptHandler.getInterfaceDecl();
126 decHandler.addInterfaceDecl(origInt, intDecl);
128 ptHandler.processCapabilityDecl();
129 CapabilityDecl capDecl = ptHandler.getCapabilityDecl();
130 decHandler.addCapabilityDecl(origInt, capDecl);
132 ptHandler.processRequiresDecl();
133 RequiresDecl reqDecl = ptHandler.getRequiresDecl();
134 decHandler.addRequiresDecl(origInt, reqDecl);
136 ptHandler.processEnumDecl();
137 EnumDecl enumDecl = ptHandler.getEnumDecl();
138 decHandler.addEnumDecl(origInt, enumDecl);
140 ptHandler.processStructDecl();
141 StructDecl structDecl = ptHandler.getStructDecl();
142 decHandler.addStructDecl(origInt, structDecl);
144 mapIntfacePTH.put(origInt, ptHandler);
145 mapIntDeclHand.put(origInt, decHandler);
146 // Set object Id counter to 0 for each interface
147 mapIntfaceObjId.put(origInt, countObjId++);
152 * getMethodsForIntface() reads for methods in the data structure
154 * It is going to give list of methods for a certain interface
155 * based on the declaration of capabilities.
157 public void getMethodsForIntface(String origInt) {
159 ParseTreeHandler ptHandler = mapIntfacePTH.get(origInt);
160 Map<String,Set<String>> mapNewIntMethods = new HashMap<String,Set<String>>();
161 // Get set of new interfaces, e.g. CameraWithCaptureAndData
162 // Generate this new interface with all the methods it needs
163 // from different capabilities it declares
164 DeclarationHandler decHandler = mapIntDeclHand.get(origInt);
165 RequiresDecl reqDecl = (RequiresDecl) decHandler.getRequiresDecl(origInt);
166 Set<String> setIntfaces = reqDecl.getInterfaces();
167 for (String strInt : setIntfaces) {
169 // Initialize a set of methods
170 Set<String> setMethods = new HashSet<String>();
171 // Get list of capabilities, e.g. ImageCapture, VideoRecording, etc.
172 List<String> listCapab = reqDecl.getCapabList(strInt);
173 for (String strCap : listCapab) {
175 // Get list of methods for each capability
176 CapabilityDecl capDecl = (CapabilityDecl) decHandler.getCapabilityDecl(origInt);
177 List<String> listCapabMeth = capDecl.getMethods(strCap);
178 for (String strMeth : listCapabMeth) {
180 // Add methods into setMethods
181 // This is to also handle redundancies (say two capabilities
182 // share the same methods)
183 setMethods.add(strMeth);
186 // Add interface and methods information into map
187 mapNewIntMethods.put(strInt, setMethods);
188 // Map new interface method name to the original interface
189 // TODO: perhaps need to check in the future if we have more than 1 stub interface for one original interface
190 mapInt2NewIntName.put(origInt, strInt);
191 if (mainClass == null) // Take the first class as the main class (whichever is placed first in the order of compilation files)
194 // Map the map of interface-methods to the original interface
195 mapInt2NewInts.put(origInt, mapNewIntMethods);
204 * HELPER: writeMethodJavaLocalInterface() writes the method of the local interface
206 private void writeMethodJavaLocalInterface(Collection<String> methods, InterfaceDecl intDecl) {
208 for (String method : methods) {
210 List<String> methParams = intDecl.getMethodParams(method);
211 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
212 print("public " + intDecl.getMethodType(method) + " " +
213 intDecl.getMethodId(method) + "(");
214 for (int i = 0; i < methParams.size(); i++) {
215 // Check for params with driver class types and exchange it
216 // with its remote interface
217 String paramType = checkAndGetParamClass(methPrmTypes.get(i));
218 print(paramType + " " + methParams.get(i));
219 // Check if this is the last element (don't print a comma)
220 if (i != methParams.size() - 1) {
230 * HELPER: writeMethodJavaInterface() writes the method of the interface
232 private void writeMethodJavaInterface(Collection<String> methods, InterfaceDecl intDecl) {
234 for (String method : methods) {
236 List<String> methParams = intDecl.getMethodParams(method);
237 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
238 print("public " + intDecl.getMethodType(method) + " " +
239 intDecl.getMethodId(method) + "(");
240 for (int i = 0; i < methParams.size(); i++) {
241 // Check for params with driver class types and exchange it
242 // with its remote interface
243 String paramType = methPrmTypes.get(i);
244 print(paramType + " " + methParams.get(i));
245 // Check if this is the last element (don't print a comma)
246 if (i != methParams.size() - 1) {
256 * HELPER: generateEnumJava() writes the enumeration declaration
258 private void generateEnumJava() throws IOException {
260 // Create a new directory
261 createDirectory(dir);
262 for (String intface : mapIntfacePTH.keySet()) {
263 // Get the right EnumDecl
264 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
265 EnumDecl enumDecl = (EnumDecl) decHandler.getEnumDecl(intface);
266 Set<String> enumTypes = enumDecl.getEnumDeclarations();
267 // Iterate over enum declarations
268 for (String enType : enumTypes) {
269 // Open a new file to write into
270 FileWriter fw = new FileWriter(dir + "/" + enType + ".java");
271 pw = new PrintWriter(new BufferedWriter(fw));
272 println("public enum " + enType + " {");
273 List<String> enumMembers = enumDecl.getMembers(enType);
274 for (int i = 0; i < enumMembers.size(); i++) {
276 String member = enumMembers.get(i);
278 // Check if this is the last element (don't print a comma)
279 if (i != enumMembers.size() - 1)
286 System.out.println("IoTCompiler: Generated enum class " + enType + ".java...");
293 * HELPER: generateStructJava() writes the struct declaration
295 private void generateStructJava() throws IOException {
297 // Create a new directory
298 createDirectory(dir);
299 for (String intface : mapIntfacePTH.keySet()) {
300 // Get the right StructDecl
301 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
302 StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
303 List<String> structTypes = structDecl.getStructTypes();
304 // Iterate over enum declarations
305 for (String stType : structTypes) {
306 // Open a new file to write into
307 FileWriter fw = new FileWriter(dir + "/" + stType + ".java");
308 pw = new PrintWriter(new BufferedWriter(fw));
309 println("public class " + stType + " {");
310 List<String> structMemberTypes = structDecl.getMemberTypes(stType);
311 List<String> structMembers = structDecl.getMembers(stType);
312 for (int i = 0; i < structMembers.size(); i++) {
314 String memberType = structMemberTypes.get(i);
315 String member = structMembers.get(i);
316 println("public static " + memberType + " " + member + ";");
320 System.out.println("IoTCompiler: Generated struct class " + stType + ".java...");
327 * generateJavaLocalInterface() writes the local interface and provides type-checking.
329 * It needs to rewrite and exchange USERDEFINED types in input parameters of stub
330 * and original interfaces, e.g. exchange Camera and CameraWithVideoAndRecording.
331 * The local interface has to be the input parameter for the stub and the stub
332 * interface has to be the input parameter for the local class.
334 public void generateJavaLocalInterfaces() throws IOException {
336 // Create a new directory
337 createDirectory(dir);
338 for (String intface : mapIntfacePTH.keySet()) {
339 // Open a new file to write into
340 FileWriter fw = new FileWriter(dir + "/" + intface + ".java");
341 pw = new PrintWriter(new BufferedWriter(fw));
342 // Pass in set of methods and get import classes
343 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
344 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
345 List<String> methods = intDecl.getMethods();
346 Set<String> importClasses = getImportClasses(methods, intDecl);
347 List<String> stdImportClasses = getStandardJavaIntfaceImportClasses();
348 List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
349 printImportStatements(allImportClasses);
350 // Write interface header
352 println("public interface " + intface + " {");
354 writeMethodJavaLocalInterface(methods, intDecl);
357 System.out.println("IoTCompiler: Generated local interface " + intface + ".java...");
363 * HELPER: updateIntfaceObjIdMap() updates the mapping between new interface and object Id
365 private void updateIntfaceObjIdMap(String intface, String newIntface) {
367 // We are assuming that we only generate one stub per one skeleton at this point @Feb 2017
368 Integer objId = mapIntfaceObjId.get(intface);
369 mapNewIntfaceObjId.put(newIntface, objId);
374 * generateJavaInterfaces() generate stub interfaces based on the methods list in Java
376 public void generateJavaInterfaces() throws IOException {
378 // Create a new directory
379 String path = createDirectories(dir, subdir);
380 for (String intface : mapIntfacePTH.keySet()) {
382 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
383 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
385 // Open a new file to write into
386 String newIntface = intMeth.getKey();
387 FileWriter fw = new FileWriter(path + "/" + newIntface + ".java");
388 pw = new PrintWriter(new BufferedWriter(fw));
389 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
390 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
391 // Pass in set of methods and get import classes
392 Set<String> methods = intMeth.getValue();
393 Set<String> importClasses = getImportClasses(methods, intDecl);
394 List<String> stdImportClasses = getStandardJavaIntfaceImportClasses();
395 List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
396 printImportStatements(allImportClasses);
397 // Write interface header
399 println("public interface " + newIntface + " {\n");
400 updateIntfaceObjIdMap(intface, newIntface);
402 writeMethodJavaInterface(methods, intDecl);
405 System.out.println("IoTCompiler: Generated interface " + newIntface + ".java...");
412 * HELPER: writePropertiesJavaPermission() writes the permission in properties
414 private void writePropertiesJavaPermission(String intface, InterfaceDecl intDecl) {
416 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
417 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
418 String newIntface = intMeth.getKey();
419 int newObjectId = getNewIntfaceObjectId(newIntface);
420 //println("private final static int object" + newObjectId + "Id = " +
421 // newObjectId + ";\t//" + newIntface);
422 Set<String> methodIds = intMeth.getValue();
423 print("private static Integer[] object" + newObjectId + "Permission = { ");
425 for (String methodId : methodIds) {
426 int methodNumId = intDecl.getMethodNumId(methodId);
427 print(Integer.toString(methodNumId));
428 // Check if this is the last element (don't print a comma)
429 if (i != methodIds.size() - 1) {
435 println("private static List<Integer> set" + newObjectId + "Allowed;");
441 * HELPER: writePropertiesJavaStub() writes the properties of the stub class
443 private void writePropertiesJavaStub(String intface, Set<String> methods, InterfaceDecl intDecl) {
446 Integer objId = mapIntfaceObjId.get(intface);
447 println("private int objectId = " + objId + ";");
448 println("private IoTRMIComm rmiComm;");
449 // Write the list of AtomicBoolean variables
450 println("// Synchronization variables");
451 for (String method : methods) {
452 // Generate AtomicBooleans for methods that have return values
453 String returnType = intDecl.getMethodType(method);
454 int methodNumId = intDecl.getMethodNumId(method);
455 if (!returnType.equals("void")) {
456 println("private AtomicBoolean retValueReceived" + methodNumId + " = new AtomicBoolean(false);");
464 * HELPER: writeConstructorJavaPermission() writes the permission in constructor
466 private void writeConstructorJavaPermission(String intface) {
468 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
469 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
470 String newIntface = intMeth.getKey();
471 int newObjectId = getNewIntfaceObjectId(newIntface);
472 println("set" + newObjectId + "Allowed = new ArrayList<Integer>(Arrays.asList(object" + newObjectId +"Permission));");
478 * HELPER: writeConstructorJavaStub() writes the constructor of the stub class
480 private void writeConstructorJavaStub(String intface, String newStubClass, Set<String> methods, InterfaceDecl intDecl) {
482 println("public " + newStubClass + "(int _localPortSend, int _localPortRecv, int _portSend, int _portRecv, String _skeletonAddress, int _rev) throws Exception {");
483 println("if (_localPortSend != 0 && _localPortRecv != 0) {");
484 println("rmiComm = new IoTRMICommClient(_localPortSend, _localPortRecv, _portSend, _portRecv, _skeletonAddress, _rev);");
487 println("rmiComm = new IoTRMICommClient(_portSend, _portRecv, _skeletonAddress, _rev);");
489 // Register the AtomicBoolean variables
490 for (String method : methods) {
491 // Generate AtomicBooleans for methods that have return values
492 String returnType = intDecl.getMethodType(method);
493 int methodNumId = intDecl.getMethodNumId(method);
494 if (!returnType.equals("void")) {
495 println("rmiComm.registerStub(objectId, " + methodNumId + ", retValueReceived" + methodNumId + ");");
498 println("IoTRMIUtil.mapStub.put(objectId, this);");
504 * HELPER: writeCallbackConstructorJavaStub() writes the callback constructor of the stub class
506 private void writeCallbackConstructorJavaStub(String intface, String newStubClass, Set<String> methods, InterfaceDecl intDecl) {
508 println("public " + newStubClass + "(IoTRMIComm _rmiComm, int _objectId) throws Exception {");
509 println("rmiComm = _rmiComm;");
510 println("objectId = _objectId;");
511 // Register the AtomicBoolean variables
512 for (String method : methods) {
513 // Generate AtomicBooleans for methods that have return values
514 String returnType = intDecl.getMethodType(method);
515 int methodNumId = intDecl.getMethodNumId(method);
516 if (!returnType.equals("void")) {
517 println("rmiComm.registerStub(objectId, " + methodNumId + ", retValueReceived" + methodNumId + ");");
525 * HELPER: getPortCount() gets port count for different stubs and skeletons
527 private int getPortCount(String intface) {
529 if (!mapPortCount.containsKey(intface))
530 mapPortCount.put(intface, portCount++);
531 return mapPortCount.get(intface);
536 * HELPER: checkAndWriteEnumTypeJavaStub() writes the enum type (convert from enum to int)
538 private void checkAndWriteEnumTypeJavaStub(List<String> methParams, List<String> methPrmTypes) {
540 // Iterate and find enum declarations
541 for (int i = 0; i < methParams.size(); i++) {
542 String paramType = methPrmTypes.get(i);
543 String param = methParams.get(i);
544 String simpleType = getGenericType(paramType);
545 if (isEnumClass(simpleType)) {
546 // Check if this is enum type
547 if (isArray(param)) { // An array
548 println("int len" + i + " = " + getSimpleIdentifier(param) + ".length;");
549 println("int paramEnum" + i + "[] = new int[len" + i + "];");
550 println("for (int i = 0; i < len" + i + "; i++) {");
551 println("paramEnum" + i + "[i] = " + getSimpleIdentifier(param) + "[i].ordinal();");
553 } else if (isList(paramType)) { // A list
554 println("int len" + i + " = " + getSimpleIdentifier(param) + ".size();");
555 println("int paramEnum" + i + "[] = new int[len" + i + "];");
556 println("for (int i = 0; i < len" + i + "; i++) {");
557 println("paramEnum" + i + "[i] = " + getSimpleIdentifier(param) + ".get(i).ordinal();");
559 } else { // Just one element
560 println("int paramEnum" + i + "[] = new int[1];");
561 println("paramEnum" + i + "[0] = " + param + ".ordinal();");
569 * HELPER: checkAndWriteEnumRetTypeJavaStub() writes the enum return type (convert from enum to int)
571 private void checkAndWriteEnumRetTypeJavaStub(String retType, String method, InterfaceDecl intDecl) {
573 // Write the wait-for-return-value part
574 writeWaitForReturnValueJava(method, intDecl, "Object retObj = rmiComm.getReturnValue(retType, null);");
575 // Strips off array "[]" for return type
576 String pureType = getSimpleArrayType(getGenericType(retType));
577 // Take the inner type of generic
578 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
579 pureType = getGenericType(retType);
580 if (isEnumClass(pureType)) {
581 // Check if this is enum type
583 println("int[] retEnum = (int[]) retObj;");
584 println(pureType + "[] enumVals = " + pureType + ".values();");
585 if (isArray(retType)) { // An array
586 println("int retLen = retEnum.length;");
587 println(pureType + "[] enumRetVal = new " + pureType + "[retLen];");
588 println("for (int i = 0; i < retLen; i++) {");
589 println("enumRetVal[i] = enumVals[retEnum[i]];");
591 } else if (isList(retType)) { // A list
592 println("int retLen = retEnum.length;");
593 println("List<" + pureType + "> enumRetVal = new ArrayList<" + pureType + ">();");
594 println("for (int i = 0; i < retLen; i++) {");
595 println("enumRetVal.add(enumVals[retEnum[i]]);");
597 } else { // Just one element
598 println(pureType + " enumRetVal = enumVals[retEnum[0]];");
600 println("return enumRetVal;");
606 * HELPER: checkAndWriteStructSetupJavaStub() writes the struct type setup
608 private void checkAndWriteStructSetupJavaStub(List<String> methParams, List<String> methPrmTypes,
609 InterfaceDecl intDecl, String method) {
611 // Iterate and find struct declarations
612 for (int i = 0; i < methParams.size(); i++) {
613 String paramType = methPrmTypes.get(i);
614 String param = methParams.get(i);
615 String simpleType = getGenericType(paramType);
616 if (isStructClass(simpleType)) {
617 // Check if this is enum type
618 int methodNumId = intDecl.getMethodNumId(method);
619 String helperMethod = methodNumId + "struct" + i;
620 println("int methodIdStruct" + i + " = " + intDecl.getHelperMethodNumId(helperMethod) + ";");
621 println("Class<?>[] paramClsStruct" + i + " = new Class<?>[] { int.class };");
622 if (isArray(param)) { // An array
623 println("Object[] paramObjStruct" + i + " = new Object[] { " + getSimpleArrayType(param) + ".length };");
624 } else if (isList(paramType)) { // A list
625 println("Object[] paramObjStruct" + i + " = new Object[] { " + getSimpleArrayType(param) + ".size() };");
626 } else { // Just one element
627 println("Object[] paramObjStruct" + i + " = new Object[] { new Integer(1) };");
629 println("rmiComm.remoteCall(objectId, methodIdStruct" + i +
630 ", paramClsStruct" + i + ", paramObjStruct" + i + ");\n");
637 * HELPER: isStructPresent() checks presence of struct
639 private boolean isStructPresent(List<String> methParams, List<String> methPrmTypes) {
641 // Iterate and find enum declarations
642 for (int i = 0; i < methParams.size(); i++) {
643 String paramType = methPrmTypes.get(i);
644 String param = methParams.get(i);
645 String simpleType = getGenericType(paramType);
646 if (isStructClass(simpleType))
654 * HELPER: writeLengthStructParamClassJavaStub() writes lengths of parameters
656 private void writeLengthStructParamClassJavaStub(List<String> methParams, List<String> methPrmTypes) {
658 // Iterate and find struct declarations - count number of params
659 for (int i = 0; i < methParams.size(); i++) {
660 String paramType = methPrmTypes.get(i);
661 String param = methParams.get(i);
662 String simpleType = getGenericType(paramType);
663 if (isStructClass(simpleType)) {
664 int members = getNumOfMembers(simpleType);
665 if (isArray(param)) { // An array
666 String structLen = getSimpleArrayType(param) + ".length";
667 print(members + "*" + structLen);
668 } else if (isList(paramType)) { // A list
669 String structLen = getSimpleArrayType(param) + ".size()";
670 print(members + "*" + structLen);
672 print(Integer.toString(members));
675 if (i != methParams.size() - 1) {
683 * HELPER: writeStructMembersJavaStub() writes parameters of struct
685 private void writeStructMembersJavaStub(String simpleType, String paramType, String param) {
687 // Get the struct declaration for this struct and generate initialization code
688 StructDecl structDecl = getStructDecl(simpleType);
689 List<String> memTypes = structDecl.getMemberTypes(simpleType);
690 List<String> members = structDecl.getMembers(simpleType);
691 if (isArray(param)) { // An array
692 println("for(int i = 0; i < " + getSimpleIdentifier(param) + ".length; i++) {");
693 for (int i = 0; i < members.size(); i++) {
694 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
695 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
696 print("paramObj[pos++] = " + getSimpleIdentifier(param) + "[i].");
697 print(getSimpleIdentifier(members.get(i)));
701 } else if (isList(paramType)) { // A list
702 println("for(int i = 0; i < " + getSimpleIdentifier(param) + ".size(); i++) {");
703 for (int i = 0; i < members.size(); i++) {
704 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
705 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
706 print("paramObj[pos++] = " + getSimpleIdentifier(param) + ".get(i).");
707 print(getSimpleIdentifier(members.get(i)));
711 } else { // Just one struct element
712 for (int i = 0; i < members.size(); i++) {
713 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
714 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
715 print("paramObj[pos++] = " + getSimpleIdentifier(param) + ".");
716 print(getSimpleIdentifier(members.get(i)));
724 * HELPER: writeStructParamClassJavaStub() writes parameters if struct is present
726 private void writeStructParamClassJavaStub(List<String> methParams, List<String> methPrmTypes, Set<String> callbackType) {
728 print("int paramLen = ");
729 writeLengthStructParamClassJavaStub(methParams, methPrmTypes);
731 println("Object[] paramObj = new Object[paramLen];");
732 println("Class<?>[] paramCls = new Class<?>[paramLen];");
733 println("int pos = 0;");
734 // Iterate again over the parameters
735 for (int i = 0; i < methParams.size(); i++) {
736 String paramType = methPrmTypes.get(i);
737 String param = methParams.get(i);
738 String simpleType = getGenericType(paramType);
739 if (isStructClass(simpleType)) {
740 writeStructMembersJavaStub(simpleType, paramType, param);
741 } else if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
742 println("paramCls[pos] = int[].class;");
743 println("paramObj[pos++] = objIdSent" + i + ";");
745 String prmType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
746 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
747 print("paramObj[pos++] = ");
748 print(getEnumParam(methPrmTypes.get(i), getSimpleIdentifier(methParams.get(i)), i));
757 * HELPER: writeStructRetMembersJavaStub() writes parameters of struct for return statement
759 private void writeStructRetMembersJavaStub(String simpleType, String retType) {
761 // Get the struct declaration for this struct and generate initialization code
762 StructDecl structDecl = getStructDecl(simpleType);
763 List<String> memTypes = structDecl.getMemberTypes(simpleType);
764 List<String> members = structDecl.getMembers(simpleType);
765 if (isArrayOrList(retType, retType)) { // An array or list
766 println("for(int i = 0; i < retLen; i++) {");
768 if (isArray(retType)) { // An array
769 for (int i = 0; i < members.size(); i++) {
770 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
771 print("structRet[i]." + getSimpleIdentifier(members.get(i)));
772 println(" = (" + getSimpleType(getEnumType(prmType)) + ") retActualObj[retObjPos++];");
775 } else if (isList(retType)) { // A list
776 println(simpleType + " structRetMem = new " + simpleType + "();");
777 for (int i = 0; i < members.size(); i++) {
778 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
779 print("structRetMem." + getSimpleIdentifier(members.get(i)));
780 println(" = (" + getSimpleType(getEnumType(prmType)) + ") retActualObj[retObjPos++];");
782 println("structRet.add(structRetMem);");
784 } else { // Just one struct element
785 for (int i = 0; i < members.size(); i++) {
786 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
787 print("structRet." + getSimpleIdentifier(members.get(i)));
788 println(" = (" + getSimpleType(getEnumType(prmType)) + ") retActualObj[retObjPos++];");
791 println("return structRet;");
796 * HELPER: writeStructReturnJavaStub() writes parameters if struct is present for return statement
798 private void writeStructReturnJavaStub(String simpleType, String retType, String method, InterfaceDecl intDecl) {
800 // Handle the returned struct size
801 writeWaitForReturnValueJava(method, intDecl, "Object retObj = rmiComm.getReturnValue(retType, null);");
802 // Minimum retLen is 1 if this is a single struct object
803 println("int retLen = (int) retObj;");
804 int numMem = getNumOfMembers(simpleType);
805 println("Class<?>[] retCls = new Class<?>[" + numMem + "*retLen];");
806 println("Class<?>[] retClsVal = new Class<?>[" + numMem + "*retLen];");
807 println("int retPos = 0;");
808 // Get the struct declaration for this struct and generate initialization code
809 StructDecl structDecl = getStructDecl(simpleType);
810 List<String> memTypes = structDecl.getMemberTypes(simpleType);
811 List<String> members = structDecl.getMembers(simpleType);
812 if (isArrayOrList(retType, retType)) { // An array or list
813 println("for(int i = 0; i < retLen; i++) {");
814 for (int i = 0; i < members.size(); i++) {
815 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
816 println("retCls[retPos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
817 println("retClsVal[retPos++] = null;");
820 } else { // Just one struct element
821 for (int i = 0; i < members.size(); i++) {
822 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
823 println("retCls[retPos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
824 println("retClsVal[retPos++] = null;");
827 //println("Object[] retActualObj = rmiComm.getStructObjects(retCls, retClsVal);");
828 // Handle the actual returned struct
829 writeWaitForReturnValueJava(method, intDecl, "Object[] retActualObj = rmiComm.getStructObjects(retCls, retClsVal);");
830 if (isArray(retType)) { // An array
831 println(simpleType + "[] structRet = new " + simpleType + "[retLen];");
832 println("for(int i = 0; i < retLen; i++) {");
833 println("structRet[i] = new " + simpleType + "();");
835 } else if (isList(retType)) { // A list
836 println("List<" + simpleType + "> structRet = new ArrayList<" + simpleType + ">();");
838 println(simpleType + " structRet = new " + simpleType + "();");
839 println("int retObjPos = 0;");
840 writeStructRetMembersJavaStub(simpleType, retType);
845 * HELPER: writeWaitForReturnValueJava() writes the synchronization part for return values
847 private void writeWaitForReturnValueJava(String method, InterfaceDecl intDecl, String getReturnValue) {
849 println("// Waiting for return value");
850 int methodNumId = intDecl.getMethodNumId(method);
851 println("while (!retValueReceived" + methodNumId + ".get());");
852 println(getReturnValue);
853 println("retValueReceived" + methodNumId + ".set(false);");
854 println("rmiComm.setGetReturnBytes();\n");
859 * HELPER: writeStdMethodBodyJavaStub() writes the standard method body in the stub class
861 private void writeStdMethodBodyJavaStub(InterfaceDecl intDecl, List<String> methParams,
862 List<String> methPrmTypes, String method, Set<String> callbackType) {
864 checkAndWriteStructSetupJavaStub(methParams, methPrmTypes, intDecl, method);
865 println("int methodId = " + intDecl.getMethodNumId(method) + ";");
866 String retType = intDecl.getMethodType(method);
867 println("Class<?> retType = " + getSimpleType(getStructType(getEnumType(retType))) + ".class;");
868 checkAndWriteEnumTypeJavaStub(methParams, methPrmTypes);
869 // Generate array of parameter types
870 if (isStructPresent(methParams, methPrmTypes)) {
871 writeStructParamClassJavaStub(methParams, methPrmTypes, callbackType);
873 print("Class<?>[] paramCls = new Class<?>[] { ");
874 for (int i = 0; i < methParams.size(); i++) {
875 String prmType = methPrmTypes.get(i);
876 if (checkCallbackType(prmType, callbackType)) { // Check if this has callback object
877 print("int[].class");
878 } else { // Generate normal classes if it's not a callback object
879 String paramType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
880 print(getSimpleType(getEnumType(paramType)) + ".class");
882 // Check if this is the last element (don't print a comma)
883 if (i != methParams.size() - 1) {
888 // Generate array of parameter objects
889 print("Object[] paramObj = new Object[] { ");
890 for (int i = 0; i < methParams.size(); i++) {
891 String paramType = methPrmTypes.get(i);
892 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
893 print("objIdSent" + i);
895 print(getEnumParam(methPrmTypes.get(i), getSimpleIdentifier(methParams.get(i)), i));
896 // Check if this is the last element (don't print a comma)
897 if (i != methParams.size() - 1) {
903 // Send method call first and wait for return value separately
904 println("rmiComm.remoteCall(objectId, methodId, paramCls, paramObj);");
905 // Check if this is "void"
906 if (!retType.equals("void")) { // We do have a return value
907 // Generate array of parameter types
908 if (isStructClass(getGenericType(getSimpleArrayType(retType)))) {
909 writeStructReturnJavaStub(getGenericType(getSimpleArrayType(retType)), retType, method, intDecl);
911 // This is an enum type
912 if (getParamCategory(getGenericType(getSimpleArrayType(retType))) == ParamCategory.ENUM) {
913 //println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
914 checkAndWriteEnumRetTypeJavaStub(retType, method, intDecl);
915 } else if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES) {
916 // Check if the return value NONPRIMITIVES
917 String retGenValType = getGenericType(retType);
918 println("Class<?> retGenValType = " + retGenValType + ".class;");
919 writeWaitForReturnValueJava(method, intDecl, "Object retObj = rmiComm.getReturnValue(retType, retGenValType);");
920 println("return (" + retType + ")retObj;");
922 writeWaitForReturnValueJava(method, intDecl, "Object retObj = rmiComm.getReturnValue(retType, null);");
923 println("return (" + retType + ")retObj;");
931 * HELPER: returnGenericCallbackType() returns the callback type
933 private String returnGenericCallbackType(String paramType) {
935 if (getParamCategory(paramType) == ParamCategory.NONPRIMITIVES)
936 return getGenericType(paramType);
943 * HELPER: checkCallbackType() checks the callback type
945 private boolean checkCallbackType(String paramType, Set<String> callbackType) {
947 String prmType = returnGenericCallbackType(paramType);
948 if (callbackType == null) // If there is no callbackType it means not a callback method
951 for (String type : callbackType) {
952 if (type.equals(prmType))
953 return true; // Check callbackType one by one
961 * HELPER: checkCallbackType() checks the callback type
963 private boolean checkCallbackType(String paramType, String callbackType) {
965 String prmType = returnGenericCallbackType(paramType);
966 if (callbackType == null) // If there is no callbackType it means not a callback method
969 return callbackType.equals(prmType);
974 * HELPER: writeCallbackInstantiationMethodBodyJavaStub() writes the callback object instantiation in the method of the stub class
976 private void writeCallbackInstantiationMethodBodyJavaStub(String paramIdent, String callbackType, int counter, boolean isMultipleCallbacks) {
978 println("if (!IoTRMIUtil.mapSkel.containsKey(" + paramIdent + ")) {");
979 println("int newObjIdSent = rmiComm.getObjectIdCounter();");
980 if (isMultipleCallbacks)
981 println("objIdSent" + counter + "[cnt" + counter + "++] = newObjIdSent;");
983 println("objIdSent" + counter + "[0] = newObjIdSent;");
984 println("rmiComm.decrementObjectIdCounter();");
985 println(callbackType + "_Skeleton skel" + counter + " = new " + callbackType + "_Skeleton(" + paramIdent + ", rmiComm, newObjIdSent);");
986 println("IoTRMIUtil.mapSkel.put(" + paramIdent + ", skel" + counter + ");");
987 println("IoTRMIUtil.mapSkelId.put(" + paramIdent + ", newObjIdSent);");
988 println("Thread thread = new Thread() {");
989 println("public void run() {");
991 println("skel" + counter + ".___waitRequestInvokeMethod();");
992 println("} catch (Exception ex) {");
993 println("ex.printStackTrace();");
994 println("throw new Error(\"Exception when trying to run ___waitRequestInvokeMethod() for " +
995 callbackType + "_Skeleton!\");");
999 println("thread.start();");
1000 println("while(!skel" + counter + ".didAlreadyInitWaitInvoke());");
1004 println("int newObjIdSent = IoTRMIUtil.mapSkelId.get(" + paramIdent + ");");
1005 if (isMultipleCallbacks)
1006 println("objIdSent" + counter + "[cnt" + counter + "++] = newObjIdSent;");
1008 println("objIdSent" + counter + "[0] = newObjIdSent;");
1014 * HELPER: writeCallbackMethodBodyJavaStub() writes the callback method of the stub class
1016 private void writeCallbackMethodBodyJavaStub(InterfaceDecl intDecl, List<String> methParams,
1017 List<String> methPrmTypes, String method, Set<String> callbackType) {
1019 // Determine callback object counter type (List vs. single variable)
1020 for (int i = 0; i < methParams.size(); i++) {
1021 String paramType = methPrmTypes.get(i);
1022 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
1023 print("int[] objIdSent" + i + " = ");
1024 String param = methParams.get(i);
1025 if (isArray(methParams.get(i)))
1026 println("new int[" + getSimpleIdentifier(methParams.get(i)) + ".length];");
1027 else if (isList(methPrmTypes.get(i)))
1028 println("new int[" + getSimpleIdentifier(methParams.get(i)) + ".size()];");
1030 println("new int[1];");
1034 // Check if this is single object, array, or list of objects
1035 for (int i = 0; i < methParams.size(); i++) {
1036 String paramType = methPrmTypes.get(i);
1037 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
1038 String param = methParams.get(i);
1039 if (isArrayOrList(paramType, param)) { // Generate loop
1040 println("int cnt" + i + " = 0;");
1041 println("for (" + getGenericType(paramType) + " cb : " + getSimpleIdentifier(param) + ") {");
1042 writeCallbackInstantiationMethodBodyJavaStub("cb", returnGenericCallbackType(paramType), i, true);
1044 writeCallbackInstantiationMethodBodyJavaStub(getSimpleIdentifier(param), returnGenericCallbackType(paramType), i, false);
1045 if (isArrayOrList(paramType, param))
1050 println(" catch (Exception ex) {");
1051 println("ex.printStackTrace();");
1052 println("throw new Error(\"Exception when generating skeleton objects!\");");
1058 * HELPER: writeMethodJavaStub() writes the methods of the stub class
1060 private void writeMethodJavaStub(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses, String newStubClass) {
1062 for (String method : methods) {
1064 List<String> methParams = intDecl.getMethodParams(method);
1065 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1066 print("public " + intDecl.getMethodType(method) + " " +
1067 intDecl.getMethodId(method) + "(");
1068 boolean isCallbackMethod = false;
1069 //String callbackType = null;
1070 Set<String> callbackType = new HashSet<String>();
1071 for (int i = 0; i < methParams.size(); i++) {
1073 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
1074 // Check if this has callback object
1075 if (callbackClasses.contains(paramType)) {
1076 isCallbackMethod = true;
1077 //callbackType = paramType;
1078 callbackType.add(paramType);
1079 // Even if there're 2 callback arguments, we expect them to be of the same interface
1081 print(methPrmTypes.get(i) + " " + methParams.get(i));
1082 // Check if this is the last element (don't print a comma)
1083 if (i != methParams.size() - 1) {
1088 // Now, write the body of stub!
1089 if (isCallbackMethod)
1090 writeCallbackMethodBodyJavaStub(intDecl, methParams, methPrmTypes, method, callbackType);
1092 writeStdMethodBodyJavaStub(intDecl, methParams, methPrmTypes, method, callbackType);
1099 * HELPER: getStubInterface() gets stub interface name based on original interface
1101 public String getStubInterface(String intface) {
1103 return mapInt2NewIntName.get(intface);
1108 * generateJavaStubClasses() generate stubs based on the methods list in Java
1110 public void generateJavaStubClasses() throws IOException {
1112 // Create a new directory
1113 String path = createDirectories(dir, subdir);
1114 for (String intface : mapIntfacePTH.keySet()) {
1116 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
1117 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
1119 // Open a new file to write into
1120 String newIntface = intMeth.getKey();
1121 String newStubClass = newIntface + "_Stub";
1122 FileWriter fw = new FileWriter(path + "/" + newStubClass + ".java");
1123 pw = new PrintWriter(new BufferedWriter(fw));
1124 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
1125 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
1126 // Pass in set of methods and get import classes
1127 Set<String> methods = intMeth.getValue();
1128 Set<String> importClasses = getImportClasses(methods, intDecl);
1129 List<String> stdImportClasses = getStandardJavaImportClasses();
1130 List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
1131 printImportStatements(allImportClasses); println("");
1132 // Find out if there are callback objects
1133 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
1134 boolean callbackExist = !callbackClasses.isEmpty();
1135 // Write class header
1136 println("public class " + newStubClass + " implements " + newIntface + " {\n");
1138 writePropertiesJavaStub(intface, intMeth.getValue(), intDecl);
1139 // Write constructor
1140 writeConstructorJavaStub(intface, newStubClass, intMeth.getValue(), intDecl);
1141 // Write callback constructor (used if this stub is treated as a callback stub)
1142 writeCallbackConstructorJavaStub(intface, newStubClass, intMeth.getValue(), intDecl);
1144 writeMethodJavaStub(intMeth.getValue(), intDecl, callbackClasses, newStubClass);
1147 System.out.println("IoTCompiler: Generated stub class " + newStubClass + ".java...");
1154 * HELPER: writePropertiesJavaSkeleton() writes the properties of the skeleton class
1156 private void writePropertiesJavaSkeleton(String intface, InterfaceDecl intDecl) {
1158 println("private " + intface + " mainObj;");
1159 //println("private int objectId = 0;");
1160 Integer objId = mapIntfaceObjId.get(intface);
1161 println("private int objectId = " + objId + ";");
1162 println("// Communications and synchronizations");
1163 println("private IoTRMIComm rmiComm;");
1164 println("private AtomicBoolean didAlreadyInitWaitInvoke;");
1165 println("private AtomicBoolean methodReceived;");
1166 println("private byte[] methodBytes = null;");
1167 println("// Permissions");
1168 writePropertiesJavaPermission(intface, intDecl);
1174 * HELPER: writeStructPermissionJavaSkeleton() writes permission for struct helper
1176 private void writeStructPermissionJavaSkeleton(Collection<String> methods, InterfaceDecl intDecl, String intface) {
1178 // Use this set to handle two same methodIds
1179 for (String method : methods) {
1180 List<String> methParams = intDecl.getMethodParams(method);
1181 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1182 // Check for params with structs
1183 for (int i = 0; i < methParams.size(); i++) {
1184 String paramType = methPrmTypes.get(i);
1185 String param = methParams.get(i);
1186 String simpleType = getGenericType(paramType);
1187 if (isStructClass(simpleType)) {
1188 int methodNumId = intDecl.getMethodNumId(method);
1189 String helperMethod = methodNumId + "struct" + i;
1190 int methodHelperNumId = intDecl.getHelperMethodNumId(helperMethod);
1191 // Iterate over interfaces to give permissions to
1192 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
1193 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
1194 String newIntface = intMeth.getKey();
1195 int newObjectId = getNewIntfaceObjectId(newIntface);
1196 println("set" + newObjectId + "Allowed.add(" + methodHelperNumId + ");");
1205 * HELPER: writeConstructorJavaSkeleton() writes the constructor of the skeleton class
1207 private void writeConstructorJavaSkeleton(String newSkelClass, String intface, InterfaceDecl intDecl,
1208 Collection<String> methods, boolean callbackExist) {
1210 println("public " + newSkelClass + "(" + intface + " _mainObj, int _portSend, int _portRecv) throws Exception {");
1211 println("mainObj = _mainObj;");
1212 println("rmiComm = new IoTRMICommServer(_portSend, _portRecv);");
1213 // Generate permission control initialization
1214 writeConstructorJavaPermission(intface);
1215 writeStructPermissionJavaSkeleton(methods, intDecl, intface);
1216 println("IoTRMIUtil.mapSkel.put(_mainObj, this);");
1217 println("IoTRMIUtil.mapSkelId.put(_mainObj, objectId);");
1218 println("didAlreadyInitWaitInvoke = new AtomicBoolean(false);");
1219 println("methodReceived = new AtomicBoolean(false);");
1220 println("rmiComm.registerSkeleton(objectId, methodReceived);");
1221 println("Thread thread1 = new Thread() {");
1222 println("public void run() {");
1224 println("___waitRequestInvokeMethod();");
1226 println("catch (Exception ex)");
1228 println("ex.printStackTrace();");
1232 println("thread1.start();");
1238 * HELPER: writeCallbackConstructorJavaSkeleton() writes the constructor of the skeleton class
1240 private void writeCallbackConstructorJavaSkeleton(String newSkelClass, String intface, InterfaceDecl intDecl,
1241 Collection<String> methods, boolean callbackExist) {
1243 println("public " + newSkelClass + "(" + intface + " _mainObj, IoTRMIComm _rmiComm, int _objectId) throws Exception {");
1244 println("mainObj = _mainObj;");
1245 println("rmiComm = _rmiComm;");
1246 println("objectId = _objectId;");
1247 // Generate permission control initialization
1248 writeConstructorJavaPermission(intface);
1249 writeStructPermissionJavaSkeleton(methods, intDecl, intface);
1250 println("didAlreadyInitWaitInvoke = new AtomicBoolean(false);");
1251 println("methodReceived = new AtomicBoolean(false);");
1252 println("rmiComm.registerSkeleton(objectId, methodReceived);");
1258 * HELPER: writeStdMethodBodyJavaSkeleton() writes the standard method body in the skeleton class
1260 private void writeStdMethodBodyJavaSkeleton(List<String> methParams, String methodId, String methodType) {
1262 if (methodType.equals("void"))
1263 print("mainObj." + methodId + "(");
1265 print("return mainObj." + methodId + "(");
1266 for (int i = 0; i < methParams.size(); i++) {
1268 print(getSimpleIdentifier(methParams.get(i)));
1269 // Check if this is the last element (don't print a comma)
1270 if (i != methParams.size() - 1) {
1279 * HELPER: writeMethodJavaSkeleton() writes the method of the skeleton class
1281 private void writeMethodJavaSkeleton(Collection<String> methods, InterfaceDecl intDecl) {
1283 for (String method : methods) {
1285 List<String> methParams = intDecl.getMethodParams(method);
1286 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1287 String methodId = intDecl.getMethodId(method);
1288 print("public " + intDecl.getMethodType(method) + " " + methodId + "(");
1289 for (int i = 0; i < methParams.size(); i++) {
1291 String origParamType = methPrmTypes.get(i);
1292 String paramType = checkAndGetParamClass(origParamType);
1293 print(paramType + " " + methParams.get(i));
1294 // Check if this is the last element (don't print a comma)
1295 if (i != methParams.size() - 1) {
1300 // Now, write the body of skeleton!
1301 writeStdMethodBodyJavaSkeleton(methParams, methodId, intDecl.getMethodType(method));
1308 * HELPER: writeCallbackInstantiationJavaStubGeneration() writes the instantiation of callback stubs
1310 private void writeCallbackInstantiationJavaStubGeneration(String exchParamType, int counter) {
1312 println(exchParamType + " newStub" + counter + " = null;");
1313 println("if(!IoTRMIUtil.mapStub.containsKey(objIdRecv" + counter + ")) {");
1314 println("newStub" + counter + " = new " + exchParamType + "_Stub(rmiComm, objIdRecv" + counter + ");");
1315 println("IoTRMIUtil.mapStub.put(objIdRecv" + counter + ", newStub" + counter + ");");
1316 println("rmiComm.setObjectIdCounter(objIdRecv" + counter + ");");
1317 println("rmiComm.decrementObjectIdCounter();");
1320 println("newStub" + counter + " = (" + exchParamType + "_Stub) IoTRMIUtil.mapStub.get(objIdRecv" + counter + ");");
1326 * HELPER: writeCallbackJavaStubGeneration() writes the callback stub generation part
1328 private Map<Integer,String> writeCallbackJavaStubGeneration(List<String> methParams, List<String> methPrmTypes,
1329 Set<String> callbackType, boolean isStructMethod) {
1331 Map<Integer,String> mapStubParam = new HashMap<Integer,String>();
1332 String offsetPfx = "";
1334 offsetPfx = "offset";
1335 // Iterate over callback objects
1336 for (int i = 0; i < methParams.size(); i++) {
1337 String paramType = methPrmTypes.get(i);
1338 String param = methParams.get(i);
1339 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
1340 String exchParamType = checkAndGetParamClass(getGenericType(paramType));
1341 // Print array if this is array or list if this is a list of callback objects
1342 println("int[] stubIdArray" + i + " = (int[]) paramObj[" + offsetPfx + i + "];");
1343 if (isArray(param)) {
1344 println("int numStubs" + i + " = stubIdArray" + i + ".length;");
1345 println(exchParamType + "[] stub" + i + " = new " + exchParamType + "[numStubs" + i + "];");
1346 } else if (isList(paramType)) {
1347 println("int numStubs" + i + " = stubIdArray" + i + ".length;");
1348 println("List<" + exchParamType + "> stub" + i + " = new ArrayList<" + exchParamType + ">();");
1350 println("int objIdRecv" + i + " = stubIdArray" + i + "[0];");
1351 writeCallbackInstantiationJavaStubGeneration(exchParamType, i);
1354 // Generate a loop if needed
1355 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
1356 String exchParamType = checkAndGetParamClass(getGenericType(paramType));
1357 if (isArray(param)) {
1358 println("for (int i = 0; i < numStubs" + i + "; i++) {");
1359 println("int objIdRecv" + i + " = stubIdArray" + i + "[i];");
1360 writeCallbackInstantiationJavaStubGeneration(exchParamType, i);
1361 println("stub" + i + "[i] = newStub" + i + ";");
1363 } else if (isList(paramType)) {
1364 println("for (int i = 0; i < numStubs" + i + "; i++) {");
1365 println("int objIdRecv" + i + " = stubIdArray" + i + "[i];");
1366 writeCallbackInstantiationJavaStubGeneration(exchParamType, i);
1367 println("stub" + i + ".add(newStub" + i + ");");
1370 println(exchParamType + " stub" + i + " = newStub" + i + ";");
1371 mapStubParam.put(i, "stub" + i); // List of all stub parameters
1374 return mapStubParam;
1379 * HELPER: checkAndWriteEnumTypeJavaSkeleton() writes the enum type (convert from enum to int)
1381 private void checkAndWriteEnumTypeJavaSkeleton(List<String> methParams, List<String> methPrmTypes, boolean isStructMethod) {
1383 String offsetPfx = "";
1385 offsetPfx = "offset";
1386 // Iterate and find enum declarations
1387 boolean printed = false;
1388 for (int i = 0; i < methParams.size(); i++) {
1389 String paramType = methPrmTypes.get(i);
1390 String param = methParams.get(i);
1391 String simpleType = getGenericType(paramType);
1392 if (isEnumClass(simpleType)) {
1393 // Check if this is enum type
1394 println("int paramInt" + i + "[] = (int[]) paramObj[" + offsetPfx + i + "];");
1396 println(simpleType + "[] enumVals = " + simpleType + ".values();");
1399 if (isArray(param)) { // An array
1400 println("int len" + i + " = paramInt" + i + ".length;");
1401 println(simpleType + "[] paramEnum" + i + " = new " + simpleType + "[len" + i + "];");
1402 println("for (int i = 0; i < len" + i + "; i++) {");
1403 println("paramEnum" + i + "[i] = enumVals[paramInt" + i + "[i]];");
1405 } else if (isList(paramType)) { // A list
1406 println("int len" + i + " = paramInt" + i + ".length;");
1407 println("List<" + simpleType + "> paramEnum" + i + " = new ArrayList<" + simpleType + ">();");
1408 println("for (int i = 0; i < len" + i + "; i++) {");
1409 println("paramEnum" + i + ".add(enumVals[paramInt" + i + "[i]]);");
1411 } else { // Just one element
1412 println(simpleType + " paramEnum" + i + " = enumVals[paramInt" + i + "[0]];");
1420 * HELPER: checkAndWriteEnumRetTypeJavaSkeleton() writes the enum return type (convert from enum to int)
1422 private void checkAndWriteEnumRetTypeJavaSkeleton(String retType, String methodId) {
1424 // Strips off array "[]" for return type
1425 String pureType = getSimpleArrayType(getGenericType(retType));
1426 // Take the inner type of generic
1427 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
1428 pureType = getGenericType(retType);
1429 if (isEnumClass(pureType)) {
1430 // Check if this is enum type
1432 if (isArray(retType)) { // An array
1433 print(pureType + "[] retEnum = " + methodId + "(");
1434 } else if (isList(retType)) { // A list
1435 print("List<" + pureType + "> retEnum = " + methodId + "(");
1436 } else { // Just one element
1437 print(pureType + " retEnum = " + methodId + "(");
1444 * HELPER: checkAndWriteEnumRetConvJavaSkeleton() writes the enum return type (convert from enum to int)
1446 private void checkAndWriteEnumRetConvJavaSkeleton(String retType) {
1448 // Strips off array "[]" for return type
1449 String pureType = getSimpleArrayType(getGenericType(retType));
1450 // Take the inner type of generic
1451 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
1452 pureType = getGenericType(retType);
1453 if (isEnumClass(pureType)) {
1454 // Check if this is enum type
1455 if (isArray(retType)) { // An array
1456 println("int retLen = retEnum.length;");
1457 println("int[] retEnumVal = new int[retLen];");
1458 println("for (int i = 0; i < retLen; i++) {");
1459 println("retEnumVal[i] = retEnum[i].ordinal();");
1461 } else if (isList(retType)) { // A list
1462 println("int retLen = retEnum.size();");
1463 println("int[] retEnumVal = new int[retLen];");
1464 println("for (int i = 0; i < retLen; i++) {");
1465 println("retEnumVal[i] = retEnum.get(i).ordinal();");
1467 } else { // Just one element
1468 println("int[] retEnumVal = new int[1];");
1469 println("retEnumVal[0] = retEnum.ordinal();");
1471 println("Object retObj = retEnumVal;");
1477 * HELPER: writeLengthStructParamClassSkeleton() writes lengths of params
1479 private void writeLengthStructParamClassSkeleton(List<String> methParams, List<String> methPrmTypes,
1480 String method, InterfaceDecl intDecl) {
1482 // Iterate and find struct declarations - count number of params
1483 for (int i = 0; i < methParams.size(); i++) {
1484 String paramType = methPrmTypes.get(i);
1485 String param = methParams.get(i);
1486 String simpleType = getGenericType(paramType);
1487 if (isStructClass(simpleType)) {
1488 int members = getNumOfMembers(simpleType);
1489 print(Integer.toString(members) + "*");
1490 int methodNumId = intDecl.getMethodNumId(method);
1491 print("struct" + methodNumId + "Size" + i);
1494 if (i != methParams.size() - 1) {
1502 * HELPER: writeStructMembersJavaSkeleton() writes member parameters of struct
1504 private void writeStructMembersJavaSkeleton(String simpleType, String paramType,
1505 String param, String method, InterfaceDecl intDecl, int iVar) {
1507 // Get the struct declaration for this struct and generate initialization code
1508 StructDecl structDecl = getStructDecl(simpleType);
1509 List<String> memTypes = structDecl.getMemberTypes(simpleType);
1510 List<String> members = structDecl.getMembers(simpleType);
1511 if (isArrayOrList(paramType, param)) { // An array or list
1512 int methodNumId = intDecl.getMethodNumId(method);
1513 String counter = "struct" + methodNumId + "Size" + iVar;
1514 println("for(int i = 0; i < " + counter + "; i++) {");
1516 if (isArrayOrList(paramType, param)) { // An array or list
1517 for (int i = 0; i < members.size(); i++) {
1518 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
1519 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
1520 println("paramClsGen[pos++] = null;");
1523 } else { // Just one struct element
1524 for (int i = 0; i < members.size(); i++) {
1525 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
1526 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
1527 println("paramClsGen[pos++] = null;");
1534 * HELPER: writeStructMembersInitJavaSkeleton() writes member parameters initialization of struct
1536 private void writeStructMembersInitJavaSkeleton(InterfaceDecl intDecl, List<String> methParams,
1537 List<String> methPrmTypes, String method) {
1539 println("int objPos = 0;");
1540 for (int i = 0; i < methParams.size(); i++) {
1541 String paramType = methPrmTypes.get(i);
1542 String param = methParams.get(i);
1543 String simpleType = getGenericType(paramType);
1544 if (isStructClass(simpleType)) {
1545 int methodNumId = intDecl.getMethodNumId(method);
1546 String counter = "struct" + methodNumId + "Size" + i;
1548 if (isArray(param)) { // An array
1549 println(simpleType + "[] paramStruct" + i + " = new " + simpleType + "[" + counter + "];");
1550 println("for(int i = 0; i < " + counter + "; i++) {");
1551 println("paramStruct" + i + "[i] = new " + simpleType + "();");
1553 } else if (isList(paramType)) { // A list
1554 println("List<" + simpleType + "> paramStruct" + i + " = new ArrayList<" + simpleType + ">();");
1556 println(simpleType + " paramStruct" + i + " = new " + simpleType + "();");
1557 // Initialize members
1558 StructDecl structDecl = getStructDecl(simpleType);
1559 List<String> members = structDecl.getMembers(simpleType);
1560 List<String> memTypes = structDecl.getMemberTypes(simpleType);
1561 if (isArrayOrList(paramType, param)) { // An array or list
1562 println("for(int i = 0; i < " + counter + "; i++) {");
1564 if (isArray(param)) { // An array
1565 for (int j = 0; j < members.size(); j++) {
1566 String prmType = checkAndGetArray(memTypes.get(j), members.get(j));
1567 print("paramStruct" + i + "[i]." + getSimpleIdentifier(members.get(j)));
1568 println(" = (" + getSimpleType(getEnumType(prmType)) + ") paramObj[objPos++];");
1571 } else if (isList(paramType)) { // A list
1572 println(simpleType + " paramStructMem = new " + simpleType + "();");
1573 for (int j = 0; j < members.size(); j++) {
1574 String prmType = checkAndGetArray(memTypes.get(j), members.get(j));
1575 print("paramStructMem." + getSimpleIdentifier(members.get(j)));
1576 println(" = (" + getSimpleType(getEnumType(prmType)) + ") paramObj[objPos++];");
1578 println("paramStruct" + i + ".add(paramStructMem);");
1580 } else { // Just one struct element
1581 for (int j = 0; j < members.size(); j++) {
1582 String prmType = checkAndGetArray(memTypes.get(j), members.get(j));
1583 print("paramStruct" + i + "." + getSimpleIdentifier(members.get(j)));
1584 println(" = (" + getSimpleType(getEnumType(prmType)) + ") paramObj[objPos++];");
1588 // Take offsets of parameters
1589 println("int offset" + i +" = objPos++;");
1596 * HELPER: writeStructReturnJavaSkeleton() writes struct for return statement
1598 private void writeStructReturnJavaSkeleton(String simpleType, String retType) {
1600 // Minimum retLen is 1 if this is a single struct object
1601 if (isArray(retType))
1602 println("int retLen = retStruct.length;");
1603 else if (isList(retType))
1604 println("int retLen = retStruct.size();");
1605 else // Just single struct object
1606 println("int retLen = 1;");
1607 println("Object retLenObj = retLen;");
1608 println("rmiComm.sendReturnObj(retLenObj, localMethodBytes);");
1609 int numMem = getNumOfMembers(simpleType);
1610 println("Class<?>[] retCls = new Class<?>[" + numMem + "*retLen];");
1611 println("Object[] retObj = new Object[" + numMem + "*retLen];");
1612 println("int retPos = 0;");
1613 // Get the struct declaration for this struct and generate initialization code
1614 StructDecl structDecl = getStructDecl(simpleType);
1615 List<String> memTypes = structDecl.getMemberTypes(simpleType);
1616 List<String> members = structDecl.getMembers(simpleType);
1617 if (isArray(retType)) { // An array or list
1618 println("for(int i = 0; i < retLen; i++) {");
1619 for (int i = 0; i < members.size(); i++) {
1620 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
1621 println("retCls[retPos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
1622 print("retObj[retPos++] = retStruct[i].");
1623 print(getEnumParam(memTypes.get(i), getSimpleIdentifier(members.get(i)), i));
1627 } else if (isList(retType)) { // An array or list
1628 println("for(int i = 0; i < retLen; i++) {");
1629 for (int i = 0; i < members.size(); i++) {
1630 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
1631 println("retCls[retPos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
1632 print("retObj[retPos++] = retStruct.get(i).");
1633 print(getEnumParam(memTypes.get(i), getSimpleIdentifier(members.get(i)), i));
1637 } else { // Just one struct element
1638 for (int i = 0; i < members.size(); i++) {
1639 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
1640 println("retCls[retPos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
1641 print("retObj[retPos++] = retStruct.");
1642 print(getEnumParam(memTypes.get(i), getSimpleIdentifier(members.get(i)), i));
1651 * HELPER: writeMethodHelperReturnJavaSkeleton() writes return statement part in skeleton
1653 private void writeMethodHelperReturnJavaSkeleton(InterfaceDecl intDecl, List<String> methParams,
1654 List<String> methPrmTypes, String method, boolean isCallbackMethod, Set<String> callbackType,
1655 boolean isStructMethod) {
1657 checkAndWriteEnumTypeJavaSkeleton(methParams, methPrmTypes, isStructMethod);
1658 Map<Integer,String> mapStubParam = null;
1659 if (isCallbackMethod) {
1661 mapStubParam = writeCallbackJavaStubGeneration(methParams, methPrmTypes, callbackType, isStructMethod);
1663 // Check if this is "void"
1664 String retType = intDecl.getMethodType(method);
1665 if (retType.equals("void")) {
1666 print(intDecl.getMethodId(method) + "(");
1667 } else if (isEnumClass(getSimpleArrayType(getGenericType(retType)))) { // Enum type
1668 checkAndWriteEnumRetTypeJavaSkeleton(retType, intDecl.getMethodId(method));
1669 } else if (isStructClass(getSimpleArrayType(getGenericType(retType)))) { // Struct type
1670 print(retType + " retStruct = " + intDecl.getMethodId(method) + "(");
1671 } else { // We do have a return value
1672 print("Object retObj = " + intDecl.getMethodId(method) + "(");
1674 for (int i = 0; i < methParams.size(); i++) {
1676 String paramType = methPrmTypes.get(i);
1677 if (isCallbackMethod && checkCallbackType(paramType, callbackType)) {
1678 print(mapStubParam.get(i)); // Get the callback parameter
1679 } else if (isEnumClass(getGenericType(paramType))) { // Enum class
1680 print(getEnumParam(paramType, methParams.get(i), i));
1681 } else if (isStructClass(getGenericType(paramType))) {
1682 print("paramStruct" + i);
1684 String prmType = checkAndGetArray(paramType, methParams.get(i));
1686 print("(" + prmType + ") paramObj[offset" + i + "]");
1688 print("(" + prmType + ") paramObj[" + i + "]");
1690 if (i != methParams.size() - 1)
1694 if (!retType.equals("void")) {
1695 if (isEnumClass(getSimpleArrayType(getGenericType(retType)))) { // Enum type
1696 checkAndWriteEnumRetConvJavaSkeleton(retType);
1697 println("rmiComm.sendReturnObj(retObj, localMethodBytes);");
1698 } else if (isStructClass(getSimpleArrayType(getGenericType(retType)))) { // Struct type
1699 writeStructReturnJavaSkeleton(getSimpleArrayType(getGenericType(retType)), retType);
1700 println("rmiComm.sendReturnObj(retCls, retObj, localMethodBytes);");
1702 println("rmiComm.sendReturnObj(retObj, localMethodBytes);");
1704 if (isCallbackMethod) { // Catch exception if this is callback
1706 println(" catch(Exception ex) {");
1707 println("ex.printStackTrace();");
1708 println("throw new Error(\"Exception from callback object instantiation!\");");
1715 * HELPER: writeMethodHelperStructJavaSkeleton() writes the struct in skeleton
1717 private void writeMethodHelperStructJavaSkeleton(InterfaceDecl intDecl, List<String> methParams,
1718 List<String> methPrmTypes, String method, Set<String> callbackClasses) {
1720 // Generate array of parameter objects
1721 boolean isCallbackMethod = false;
1722 //String callbackType = null;
1723 Set<String> callbackType = new HashSet<String>();
1724 println("byte[] localMethodBytes = methodBytes;");
1725 println("rmiComm.setGetMethodBytes();");
1726 print("int paramLen = ");
1727 writeLengthStructParamClassSkeleton(methParams, methPrmTypes, method, intDecl);
1729 println("Class<?>[] paramCls = new Class<?>[paramLen];");
1730 println("Class<?>[] paramClsGen = new Class<?>[paramLen];");
1731 println("int pos = 0;");
1732 // Iterate again over the parameters
1733 for (int i = 0; i < methParams.size(); i++) {
1734 String paramType = methPrmTypes.get(i);
1735 String param = methParams.get(i);
1736 String simpleType = getGenericType(paramType);
1737 if (isStructClass(simpleType)) {
1738 writeStructMembersJavaSkeleton(simpleType, paramType, param, method, intDecl, i);
1740 String prmType = returnGenericCallbackType(methPrmTypes.get(i));
1741 if (callbackClasses.contains(prmType)) {
1742 isCallbackMethod = true;
1743 //callbackType = prmType;
1744 callbackType.add(prmType);
1745 println("paramCls[pos] = int[].class;");
1746 println("paramClsGen[pos++] = null;");
1747 } else { // Generate normal classes if it's not a callback object
1748 String paramTypeOth = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
1749 println("paramCls[pos] = " + getSimpleType(getEnumType(paramTypeOth)) + ".class;");
1750 print("paramClsGen[pos++] = ");
1751 String prmTypeOth = methPrmTypes.get(i);
1752 if (getParamCategory(prmTypeOth) == ParamCategory.NONPRIMITIVES)
1753 println(getTypeOfGeneric(prmType)[0] + ".class;");
1759 println("Object[] paramObj = rmiComm.getMethodParams(paramCls, paramClsGen, localMethodBytes);");
1760 writeStructMembersInitJavaSkeleton(intDecl, methParams, methPrmTypes, method);
1761 // Write the return value part
1762 writeMethodHelperReturnJavaSkeleton(intDecl, methParams, methPrmTypes, method, isCallbackMethod, callbackType, true);
1767 * HELPER: writeStdMethodHelperBodyJavaSkeleton() writes the standard method body helper in the skeleton class
1769 private void writeStdMethodHelperBodyJavaSkeleton(InterfaceDecl intDecl, List<String> methParams,
1770 List<String> methPrmTypes, String method, Set<String> callbackClasses) {
1772 // Generate array of parameter objects
1773 boolean isCallbackMethod = false;
1774 //String callbackType = null;
1775 Set<String> callbackType = new HashSet<String>();
1776 println("byte[] localMethodBytes = methodBytes;");
1777 println("rmiComm.setGetMethodBytes();");
1778 print("Object[] paramObj = rmiComm.getMethodParams(new Class<?>[] { ");
1779 for (int i = 0; i < methParams.size(); i++) {
1781 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
1782 if (callbackClasses.contains(paramType)) {
1783 isCallbackMethod = true;
1784 //callbackType = paramType;
1785 callbackType.add(paramType);
1786 print("int[].class");
1787 } else { // Generate normal classes if it's not a callback object
1788 String prmType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
1789 print(getSimpleType(getEnumType(prmType)) + ".class");
1791 if (i != methParams.size() - 1)
1795 // Generate generic class if it's a generic type.. null otherwise
1796 print(" }, new Class<?>[] { ");
1797 for (int i = 0; i < methParams.size(); i++) {
1798 String prmType = methPrmTypes.get(i);
1799 if ((getParamCategory(prmType) == ParamCategory.NONPRIMITIVES) &&
1800 !isEnumClass(getGenericType(prmType)) &&
1801 !callbackClasses.contains(getGenericType(prmType)))
1802 print(getGenericType(prmType) + ".class");
1805 if (i != methParams.size() - 1)
1808 println(" }, localMethodBytes);");
1809 // Write the return value part
1810 writeMethodHelperReturnJavaSkeleton(intDecl, methParams, methPrmTypes, method, isCallbackMethod, callbackType, false);
1815 * HELPER: writeMethodHelperJavaSkeleton() writes the method helper of the skeleton class
1817 private void writeMethodHelperJavaSkeleton(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
1819 // Use this set to handle two same methodIds
1820 Set<String> uniqueMethodIds = new HashSet<String>();
1821 for (String method : methods) {
1823 List<String> methParams = intDecl.getMethodParams(method);
1824 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1825 if (isStructPresent(methParams, methPrmTypes)) { // Treat struct differently
1826 String methodId = intDecl.getMethodId(method);
1827 print("public void ___");
1828 String helperMethod = methodId;
1829 if (uniqueMethodIds.contains(methodId))
1830 helperMethod = helperMethod + intDecl.getMethodNumId(method);
1832 uniqueMethodIds.add(methodId);
1833 String retType = intDecl.getMethodType(method);
1834 print(helperMethod + "(");
1835 boolean begin = true;
1836 for (int i = 0; i < methParams.size(); i++) { // Print size variables
1837 String paramType = methPrmTypes.get(i);
1838 String param = methParams.get(i);
1839 String simpleType = getGenericType(paramType);
1840 if (isStructClass(simpleType)) {
1841 if (!begin) // Generate comma for not the beginning variable
1845 int methodNumId = intDecl.getMethodNumId(method);
1846 print("int struct" + methodNumId + "Size" + i);
1849 // Check if this is "void"
1850 if (retType.equals("void"))
1853 println(") throws IOException {");
1854 writeMethodHelperStructJavaSkeleton(intDecl, methParams, methPrmTypes, method, callbackClasses);
1857 String methodId = intDecl.getMethodId(method);
1858 print("public void ___");
1859 String helperMethod = methodId;
1860 if (uniqueMethodIds.contains(methodId))
1861 helperMethod = helperMethod + intDecl.getMethodNumId(method);
1863 uniqueMethodIds.add(methodId);
1864 // Check if this is "void"
1865 String retType = intDecl.getMethodType(method);
1866 if (retType.equals("void"))
1867 println(helperMethod + "() {");
1869 println(helperMethod + "() throws IOException {");
1870 // Now, write the helper body of skeleton!
1871 writeStdMethodHelperBodyJavaSkeleton(intDecl, methParams, methPrmTypes, method, callbackClasses);
1875 // Write method helper for structs
1876 writeMethodHelperStructSetupJavaSkeleton(methods, intDecl);
1881 * HELPER: writeMethodHelperStructSetupJavaSkeleton() writes the method helper of struct setup in skeleton class
1883 private void writeMethodHelperStructSetupJavaSkeleton(Collection<String> methods,
1884 InterfaceDecl intDecl) {
1886 // Use this set to handle two same methodIds
1887 for (String method : methods) {
1889 List<String> methParams = intDecl.getMethodParams(method);
1890 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1891 // Check for params with structs
1892 for (int i = 0; i < methParams.size(); i++) {
1893 String paramType = methPrmTypes.get(i);
1894 String param = methParams.get(i);
1895 String simpleType = getGenericType(paramType);
1896 if (isStructClass(simpleType)) {
1897 int methodNumId = intDecl.getMethodNumId(method);
1898 print("public int ___");
1899 String helperMethod = methodNumId + "struct" + i;
1900 println(helperMethod + "() {");
1901 // Now, write the helper body of skeleton!
1902 println("byte[] localMethodBytes = methodBytes;");
1903 println("rmiComm.setGetMethodBytes();");
1904 println("Object[] paramObj = rmiComm.getMethodParams(new Class<?>[] { int.class }, new Class<?>[] { null }, localMethodBytes);");
1905 println("return (int) paramObj[0];");
1914 * HELPER: writeMethodHelperStructSetupJavaCallbackSkeleton() writes the method helper of struct setup in callback skeleton class
1916 private void writeMethodHelperStructSetupJavaCallbackSkeleton(Collection<String> methods,
1917 InterfaceDecl intDecl) {
1919 // Use this set to handle two same methodIds
1920 for (String method : methods) {
1922 List<String> methParams = intDecl.getMethodParams(method);
1923 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1924 // Check for params with structs
1925 for (int i = 0; i < methParams.size(); i++) {
1926 String paramType = methPrmTypes.get(i);
1927 String param = methParams.get(i);
1928 String simpleType = getGenericType(paramType);
1929 if (isStructClass(simpleType)) {
1930 int methodNumId = intDecl.getMethodNumId(method);
1931 print("public int ___");
1932 String helperMethod = methodNumId + "struct" + i;
1933 println(helperMethod + "(IoTRMIObject rmiObj) {");
1934 // Now, write the helper body of skeleton!
1935 println("Object[] paramObj = rmiComm.getMethodParams(new Class<?>[] { int.class }, new Class<?>[] { null });");
1936 println("return (int) paramObj[0];");
1945 * HELPER: writeCountVarStructSkeleton() writes counter variable of struct for skeleton
1947 private void writeCountVarStructSkeleton(Collection<String> methods, InterfaceDecl intDecl) {
1949 // Use this set to handle two same methodIds
1950 for (String method : methods) {
1952 List<String> methParams = intDecl.getMethodParams(method);
1953 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1954 // Check for params with structs
1955 for (int i = 0; i < methParams.size(); i++) {
1956 String paramType = methPrmTypes.get(i);
1957 String param = methParams.get(i);
1958 String simpleType = getGenericType(paramType);
1959 if (isStructClass(simpleType)) {
1960 int methodNumId = intDecl.getMethodNumId(method);
1961 println("int struct" + methodNumId + "Size" + i + " = 0;");
1969 * HELPER: writeInputCountVarStructJavaSkeleton() writes input counter variable of struct for skeleton
1971 private boolean writeInputCountVarStructJavaSkeleton(String method, InterfaceDecl intDecl) {
1973 List<String> methParams = intDecl.getMethodParams(method);
1974 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1975 boolean structExist = false;
1976 boolean begin = true;
1977 // Check for params with structs
1978 for (int i = 0; i < methParams.size(); i++) {
1979 String paramType = methPrmTypes.get(i);
1980 String param = methParams.get(i);
1981 String simpleType = getGenericType(paramType);
1982 if (isStructClass(simpleType)) {
1988 int methodNumId = intDecl.getMethodNumId(method);
1989 print("struct" + methodNumId + "Size" + i + "Final");
1997 * HELPER: writeInputCountVarStructCplusSkeleton() writes input counter variable of struct for skeleton
1999 private boolean writeInputCountVarStructCplusSkeleton(String method, InterfaceDecl intDecl) {
2001 List<String> methParams = intDecl.getMethodParams(method);
2002 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2003 boolean structExist = false;
2004 boolean begin = true;
2005 // Check for params with structs
2006 for (int i = 0; i < methParams.size(); i++) {
2007 String paramType = methPrmTypes.get(i);
2008 String param = methParams.get(i);
2009 String simpleType = getGenericType(paramType);
2010 if (isStructClass(simpleType)) {
2016 int methodNumId = intDecl.getMethodNumId(method);
2017 print("struct" + methodNumId + "Size" + i);
2025 * HELPER: writeMethodCallStructJavaSkeleton() writes method call for wait invoke in skeleton
2027 private void writeMethodCallStructJavaSkeleton(Collection<String> methods, InterfaceDecl intDecl) {
2029 // Use this set to handle two same methodIds
2030 for (String method : methods) {
2032 List<String> methParams = intDecl.getMethodParams(method);
2033 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2034 // Check for params with structs
2035 for (int i = 0; i < methParams.size(); i++) {
2036 String paramType = methPrmTypes.get(i);
2037 String param = methParams.get(i);
2038 String simpleType = getGenericType(paramType);
2039 if (isStructClass(simpleType)) {
2040 int methodNumId = intDecl.getMethodNumId(method);
2042 String helperMethod = methodNumId + "struct" + i;
2043 String tempVar = "struct" + methodNumId + "Size" + i;
2044 print(intDecl.getHelperMethodNumId(helperMethod) + ": ");
2045 print(tempVar + " = ___");
2046 println(helperMethod + "(); break;");
2054 * HELPER: writeMethodCallStructCplusSkeleton() writes method call for wait invoke in skeleton
2056 private void writeMethodCallStructCplusSkeleton(Collection<String> methods, InterfaceDecl intDecl) {
2058 // Use this set to handle two same methodIds
2059 for (String method : methods) {
2061 List<String> methParams = intDecl.getMethodParams(method);
2062 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2063 // Check for params with structs
2064 for (int i = 0; i < methParams.size(); i++) {
2065 String paramType = methPrmTypes.get(i);
2066 String param = methParams.get(i);
2067 String simpleType = getGenericType(paramType);
2068 if (isStructClass(simpleType)) {
2069 int methodNumId = intDecl.getMethodNumId(method);
2071 String helperMethod = methodNumId + "struct" + i;
2072 String tempVar = "struct" + methodNumId + "Size" + i;
2073 print(intDecl.getHelperMethodNumId(helperMethod) + ": ");
2074 print(tempVar + " = ___");
2075 println(helperMethod + "(skel); break;");
2083 * HELPER: writeMethodCallStructCallbackSkeleton() writes method call for wait invoke in skeleton
2085 private void writeMethodCallStructCallbackSkeleton(Collection<String> methods, InterfaceDecl intDecl) {
2087 // Use this set to handle two same methodIds
2088 for (String method : methods) {
2090 List<String> methParams = intDecl.getMethodParams(method);
2091 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2092 // Check for params with structs
2093 for (int i = 0; i < methParams.size(); i++) {
2094 String paramType = methPrmTypes.get(i);
2095 String param = methParams.get(i);
2096 String simpleType = getGenericType(paramType);
2097 if (isStructClass(simpleType)) {
2098 int methodNumId = intDecl.getMethodNumId(method);
2100 String helperMethod = methodNumId + "struct" + i;
2101 String tempVar = "struct" + methodNumId + "Size" + i;
2102 print(intDecl.getHelperMethodNumId(helperMethod) + ": ");
2103 print(tempVar + " = ___");
2104 println(helperMethod + "(rmiObj); break;");
2112 * HELPER: writeJavaMethodPermission() writes permission checks in skeleton
2114 private void writeJavaMethodPermission(String intface) {
2116 // Get all the different stubs
2117 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
2118 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
2119 String newIntface = intMeth.getKey();
2120 int newObjectId = getNewIntfaceObjectId(newIntface);
2121 println("if (_objectId == objectId) {");
2122 println("if (!set" + newObjectId + "Allowed.contains(methodId)) {");
2123 println("throw new Error(\"Object with object Id: \" + _objectId + \" is not allowed to access method: \" + methodId);");
2127 println("continue;");
2134 * HELPER: writeFinalInputCountVarStructSkeleton() writes the final version of input counter variable of struct for skeleton
2136 private boolean writeFinalInputCountVarStructSkeleton(String method, InterfaceDecl intDecl) {
2138 List<String> methParams = intDecl.getMethodParams(method);
2139 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2140 boolean structExist = false;
2141 boolean begin = true;
2142 // Check for params with structs
2143 for (int i = 0; i < methParams.size(); i++) {
2144 String paramType = methPrmTypes.get(i);
2145 String param = methParams.get(i);
2146 String simpleType = getGenericType(paramType);
2147 if (isStructClass(simpleType)) {
2149 int methodNumId = intDecl.getMethodNumId(method);
2150 println("final int struct" + methodNumId + "Size" + i +
2151 "Final = struct" + methodNumId + "Size" + i + ";");
2159 * HELPER: writeJavaWaitRequestInvokeMethod() writes the main loop of the skeleton class
2161 private void writeJavaWaitRequestInvokeMethod(Collection<String> methods, InterfaceDecl intDecl, String intface) {
2163 // Use this set to handle two same methodIds
2164 Set<String> uniqueMethodIds = new HashSet<String>();
2165 println("public void ___waitRequestInvokeMethod() throws IOException {");
2166 // Write variables here if we have callbacks or enums or structs
2167 writeCountVarStructSkeleton(methods, intDecl);
2168 println("didAlreadyInitWaitInvoke.compareAndSet(false, true);");
2169 println("while (true) {");
2170 println("if (!methodReceived.get()) {");
2171 println("continue;");
2173 println("methodBytes = rmiComm.getMethodBytes();");
2174 println("methodReceived.set(false);");
2175 println("int _objectId = IoTRMIComm.getObjectId(methodBytes);");
2176 println("int methodId = IoTRMIComm.getMethodId(methodBytes);");
2177 // Generate permission check
2178 writeJavaMethodPermission(intface);
2179 println("switch (methodId) {");
2180 // Print methods and method Ids
2181 for (String method : methods) {
2182 String methodId = intDecl.getMethodId(method);
2183 int methodNumId = intDecl.getMethodNumId(method);
2184 println("case " + methodNumId + ":");
2185 // Check for stuct counters
2186 writeFinalInputCountVarStructSkeleton(method, intDecl);
2187 println("new Thread() {");
2188 println("public void run() {");
2191 String helperMethod = methodId;
2192 if (uniqueMethodIds.contains(methodId))
2193 helperMethod = helperMethod + methodNumId;
2195 uniqueMethodIds.add(methodId);
2196 print(helperMethod + "(");
2197 writeInputCountVarStructJavaSkeleton(method, intDecl);
2200 println("catch (Exception ex) {");
2201 println("ex.printStackTrace();");
2204 println("}.start();");
2207 String method = "___initCallBack()";
2208 writeMethodCallStructJavaSkeleton(methods, intDecl);
2209 println("default: ");
2210 println("throw new Error(\"Method Id \" + methodId + \" not recognized!\");");
2218 * HELPER: writeReturnDidAlreadyInitWaitInvoke() writes the function to return didAlreadyInitWaitInvoke
2220 private void writeReturnDidAlreadyInitWaitInvoke() {
2222 println("public boolean didAlreadyInitWaitInvoke() {");
2223 println("return didAlreadyInitWaitInvoke.get();");
2229 * generateJavaSkeletonClass() generate skeletons based on the methods list in Java
2231 public void generateJavaSkeletonClass() throws IOException {
2233 // Create a new directory
2234 String path = createDirectories(dir, subdir);
2235 for (String intface : mapIntfacePTH.keySet()) {
2236 // Open a new file to write into
2237 String newSkelClass = intface + "_Skeleton";
2238 FileWriter fw = new FileWriter(path + "/" + newSkelClass + ".java");
2239 pw = new PrintWriter(new BufferedWriter(fw));
2240 // Pass in set of methods and get import classes
2241 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2242 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
2243 List<String> methods = intDecl.getMethods();
2244 Set<String> importClasses = getImportClasses(methods, intDecl);
2245 List<String> stdImportClasses = getStandardJavaImportClasses();
2246 List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
2247 printImportStatements(allImportClasses);
2248 // Find out if there are callback objects
2249 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
2250 boolean callbackExist = !callbackClasses.isEmpty();
2251 // Write class header
2253 println("public class " + newSkelClass + " implements " + intface + " {\n");
2255 writePropertiesJavaSkeleton(intface, intDecl);
2256 // Write constructor
2257 writeConstructorJavaSkeleton(newSkelClass, intface, intDecl, methods, callbackExist);
2258 // Write constructor that is called when this object is a callback object
2259 writeCallbackConstructorJavaSkeleton(newSkelClass, intface, intDecl, methods, callbackExist);
2260 // Write function to return didAlreadyInitWaitInvoke
2261 writeReturnDidAlreadyInitWaitInvoke();
2263 writeMethodJavaSkeleton(methods, intDecl);
2264 // Write method helper
2265 writeMethodHelperJavaSkeleton(methods, intDecl, callbackClasses);
2266 // Write waitRequestInvokeMethod() - main loop
2267 writeJavaWaitRequestInvokeMethod(methods, intDecl, intface);
2270 System.out.println("IoTCompiler: Generated skeleton class " + newSkelClass + ".java...");
2275 /*================================================================================
2279 *================================================================================/
2282 * HELPER: writeMethodCplusLocalInterface() writes the method of the local interface
2284 private void writeMethodCplusLocalInterface(Collection<String> methods, InterfaceDecl intDecl) {
2286 for (String method : methods) {
2288 List<String> methParams = intDecl.getMethodParams(method);
2289 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2290 print("virtual " + checkAndGetCplusType(intDecl.getMethodType(method)) + " " +
2291 intDecl.getMethodId(method) + "(");
2292 for (int i = 0; i < methParams.size(); i++) {
2293 // Check for params with driver class types and exchange it
2294 // with its remote interface
2295 String paramType = checkAndGetParamClass(methPrmTypes.get(i));
2296 paramType = checkAndGetCplusType(paramType);
2297 // Check for arrays - translate into vector in C++
2298 String paramComplete = checkAndGetCplusArray(paramType, methParams.get(i));
2299 print(paramComplete);
2300 // Check if this is the last element (don't print a comma)
2301 if (i != methParams.size() - 1) {
2311 * HELPER: writeMethodCplusInterface() writes the method of the interface
2313 private void writeMethodCplusInterface(Collection<String> methods, InterfaceDecl intDecl) {
2315 for (String method : methods) {
2317 List<String> methParams = intDecl.getMethodParams(method);
2318 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2319 print("virtual " + checkAndGetCplusType(intDecl.getMethodType(method)) + " " +
2320 intDecl.getMethodId(method) + "(");
2321 for (int i = 0; i < methParams.size(); i++) {
2322 // Check for params with driver class types and exchange it
2323 // with its remote interface
2324 String paramType = methPrmTypes.get(i);
2325 paramType = checkAndGetCplusType(paramType);
2326 // Check for arrays - translate into vector in C++
2327 String paramComplete = checkAndGetCplusArray(paramType, methParams.get(i));
2328 print(paramComplete);
2329 // Check if this is the last element (don't print a comma)
2330 if (i != methParams.size() - 1) {
2340 * HELPER: generateEnumCplus() writes the enumeration declaration
2342 public void generateEnumCplus() throws IOException {
2344 // Create a new directory
2345 createDirectory(dir);
2346 for (String intface : mapIntfacePTH.keySet()) {
2347 // Get the right StructDecl
2348 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2349 EnumDecl enumDecl = (EnumDecl) decHandler.getEnumDecl(intface);
2350 Set<String> enumTypes = enumDecl.getEnumDeclarations();
2351 // Iterate over enum declarations
2352 for (String enType : enumTypes) {
2353 // Open a new file to write into
2354 FileWriter fw = new FileWriter(dir + "/" + enType + ".hpp");
2355 pw = new PrintWriter(new BufferedWriter(fw));
2356 // Write file headers
2357 println("#ifndef _" + enType.toUpperCase() + "_HPP__");
2358 println("#define _" + enType.toUpperCase() + "_HPP__");
2359 println("enum " + enType + " {");
2360 List<String> enumMembers = enumDecl.getMembers(enType);
2361 for (int i = 0; i < enumMembers.size(); i++) {
2363 String member = enumMembers.get(i);
2365 // Check if this is the last element (don't print a comma)
2366 if (i != enumMembers.size() - 1)
2374 System.out.println("IoTCompiler: Generated enum " + enType + ".hpp...");
2381 * HELPER: generateStructCplus() writes the struct declaration
2383 public void generateStructCplus() throws IOException {
2385 // Create a new directory
2386 createDirectory(dir);
2387 for (String intface : mapIntfacePTH.keySet()) {
2388 // Get the right StructDecl
2389 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2390 StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
2391 List<String> structTypes = structDecl.getStructTypes();
2392 // Iterate over enum declarations
2393 for (String stType : structTypes) {
2394 // Open a new file to write into
2395 FileWriter fw = new FileWriter(dir + "/" + stType + ".hpp");
2396 pw = new PrintWriter(new BufferedWriter(fw));
2397 // Write file headers
2398 println("#ifndef _" + stType.toUpperCase() + "_HPP__");
2399 println("#define _" + stType.toUpperCase() + "_HPP__");
2400 println("using namespace std;");
2401 println("struct " + stType + " {");
2402 List<String> structMemberTypes = structDecl.getMemberTypes(stType);
2403 List<String> structMembers = structDecl.getMembers(stType);
2404 for (int i = 0; i < structMembers.size(); i++) {
2406 String memberType = structMemberTypes.get(i);
2407 String member = structMembers.get(i);
2408 String structTypeC = checkAndGetCplusType(memberType);
2409 String structComplete = checkAndGetCplusArray(structTypeC, member);
2410 println(structComplete + ";");
2415 System.out.println("IoTCompiler: Generated struct " + stType + ".hpp...");
2422 * generateCplusLocalInterfaces() writes the local interfaces and provides type-checking.
2424 * It needs to rewrite and exchange USERDEFINED types in input parameters of stub
2425 * and original interfaces, e.g. exchange Camera and CameraWithVideoAndRecording.
2426 * The local interface has to be the input parameter for the stub and the stub
2427 * interface has to be the input parameter for the local class.
2429 public void generateCplusLocalInterfaces() throws IOException {
2431 // Create a new directory
2432 createDirectory(dir);
2433 for (String intface : mapIntfacePTH.keySet()) {
2434 // Open a new file to write into
2435 FileWriter fw = new FileWriter(dir + "/" + intface + ".hpp");
2436 pw = new PrintWriter(new BufferedWriter(fw));
2437 // Write file headers
2438 println("#ifndef _" + intface.toUpperCase() + "_HPP__");
2439 println("#define _" + intface.toUpperCase() + "_HPP__");
2440 println("#include <iostream>");
2441 // Pass in set of methods and get include classes
2442 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2443 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
2444 List<String> methods = intDecl.getMethods();
2445 Set<String> includeClasses = getIncludeClasses(methods, intDecl, intface, true);
2446 printIncludeStatements(includeClasses); println("");
2447 println("using namespace std;\n");
2448 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
2449 if (!intface.equals(mainClass)) // Forward declare if not main class
2450 writeMethodCplusInterfaceForwardDecl(methods, intDecl, callbackClasses, true);
2451 println("class " + intface); println("{");
2454 writeMethodCplusLocalInterface(methods, intDecl);
2458 System.out.println("IoTCompiler: Generated local interface " + intface + ".hpp...");
2464 * HELPER: writeMethodCplusInterfaceForwardDecl() writes the forward declaration of the interface
2466 private void writeMethodCplusInterfaceForwardDecl(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses, boolean needNewIntface) {
2468 Set<String> isDefined = new HashSet<String>();
2469 for (String method : methods) {
2471 List<String> methParams = intDecl.getMethodParams(method);
2472 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2473 for (int i = 0; i < methParams.size(); i++) {
2474 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
2475 // Check if this has callback object
2476 if (callbackClasses.contains(paramType)) {
2477 if (!isDefined.contains(paramType)) {
2479 println("class " + getStubInterface(paramType) + ";\n");
2481 println("class " + paramType + ";\n");
2482 isDefined.add(paramType);
2491 * generateCPlusInterfaces() generate stub interfaces based on the methods list in C++
2493 * For C++ we use virtual classe as interface
2495 public void generateCPlusInterfaces() throws IOException {
2497 // Create a new directory
2498 String path = createDirectories(dir, subdir);
2499 for (String intface : mapIntfacePTH.keySet()) {
2501 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
2502 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
2504 // Open a new file to write into
2505 String newIntface = intMeth.getKey();
2506 FileWriter fw = new FileWriter(path + "/" + newIntface + ".hpp");
2507 pw = new PrintWriter(new BufferedWriter(fw));
2508 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2509 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
2510 // Write file headers
2511 println("#ifndef _" + newIntface.toUpperCase() + "_HPP__");
2512 println("#define _" + newIntface.toUpperCase() + "_HPP__");
2513 println("#include <iostream>");
2514 updateIntfaceObjIdMap(intface, newIntface);
2515 // Pass in set of methods and get import classes
2516 Set<String> methods = intMeth.getValue();
2517 Set<String> includeClasses = getIncludeClasses(methods, intDecl, intface, false);
2518 printIncludeStatements(includeClasses); println("");
2519 println("using namespace std;\n");
2520 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
2521 writeMethodCplusInterfaceForwardDecl(methods, intDecl, callbackClasses, false);
2522 println("class " + newIntface);
2526 writeMethodCplusInterface(methods, intDecl);
2530 System.out.println("IoTCompiler: Generated interface " + newIntface + ".hpp...");
2537 * HELPER: writeMethodDeclCplusStub() writes the method declarations of the stub
2539 private void writeMethodDeclCplusStub(Collection<String> methods, InterfaceDecl intDecl) {
2541 for (String method : methods) {
2543 List<String> methParams = intDecl.getMethodParams(method);
2544 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2545 print(checkAndGetCplusType(intDecl.getMethodType(method)) + " " +
2546 intDecl.getMethodId(method) + "(");
2547 for (int i = 0; i < methParams.size(); i++) {
2549 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
2550 String methPrmType = checkAndGetCplusType(methPrmTypes.get(i));
2551 String methParamComplete = checkAndGetCplusArray(methPrmType, methParams.get(i));
2552 print(methParamComplete);
2553 // Check if this is the last element (don't print a comma)
2554 if (i != methParams.size() - 1) {
2564 * HELPER: writeMethodCplusStub() writes the methods of the stub
2566 private void writeMethodCplusStub(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses, String newStubClass) {
2568 for (String method : methods) {
2570 List<String> methParams = intDecl.getMethodParams(method);
2571 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2572 // Print the mutex lock first
2573 int methodNumId = intDecl.getMethodNumId(method);
2574 String mutexVar = "mtx" + newStubClass + "MethodExec" + methodNumId;
2575 println("mutex " + mutexVar + ";");
2576 print(checkAndGetCplusType(intDecl.getMethodType(method)) + " " + newStubClass + "::" +
2577 intDecl.getMethodId(method) + "(");
2578 boolean isCallbackMethod = false;
2579 Set<String> callbackType = new HashSet<String>();
2580 for (int i = 0; i < methParams.size(); i++) {
2582 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
2583 // Check if this has callback object
2584 if (callbackClasses.contains(paramType)) {
2585 isCallbackMethod = true;
2586 //callbackType = paramType;
2587 callbackType.add(paramType);
2588 // Even if there're 2 callback arguments, we expect them to be of the same interface
2590 String methPrmType = checkAndGetCplusType(methPrmTypes.get(i));
2591 String methParamComplete = checkAndGetCplusArray(methPrmType, methParams.get(i));
2592 print(methParamComplete);
2593 // Check if this is the last element (don't print a comma)
2594 if (i != methParams.size() - 1) {
2599 println("lock_guard<mutex> guard(" + mutexVar + ");");
2600 if (isCallbackMethod)
2601 writeCallbackMethodBodyCplusStub(intDecl, methParams, methPrmTypes, method, callbackType);
2602 writeStdMethodBodyCplusStub(intDecl, methParams, methPrmTypes, method, callbackType, isCallbackMethod);
2610 * HELPER: writeCallbackInstantiationMethodBodyCplusStub() writes the callback object instantiation in the method of the stub class
2612 private void writeCallbackInstantiationMethodBodyCplusStub(String paramIdent, String callbackType, int counter) {
2614 println("auto it" + counter + " = IoTRMIUtil::mapSkel->find(" + paramIdent + ");");
2615 println("if (it" + counter + " == IoTRMIUtil::mapSkel->end()) {");
2616 println("int newObjIdSent = rmiComm->getObjectIdCounter();");
2617 println("objIdSent" + counter + ".push_back(newObjIdSent);");
2618 println("rmiComm->decrementObjectIdCounter();");
2619 println(callbackType + "_Skeleton* skel" + counter + " = new " + callbackType + "_Skeleton(" + paramIdent + ", rmiComm, newObjIdSent);");
2620 println("IoTRMIUtil::mapSkel->insert(make_pair(" + paramIdent + ", skel" + counter + "));");
2621 println("IoTRMIUtil::mapSkelId->insert(make_pair(" + paramIdent + ", newObjIdSent));");
2622 println("thread th" + counter + " (&" + callbackType + "_Skeleton::___waitRequestInvokeMethod, std::ref(skel" + counter +
2623 "), std::ref(skel" + counter +"));");
2624 println("th" + counter + ".detach();");
2625 println("while(!skel" + counter + "->didInitWaitInvoke());");
2629 println("auto itId = IoTRMIUtil::mapSkelId->find(" + paramIdent + ");");
2630 println("objIdSent" + counter + ".push_back(itId->second);");
2636 * HELPER: writeCallbackMethodBodyCplusStub() writes the callback method of the stub class
2638 private void writeCallbackMethodBodyCplusStub(InterfaceDecl intDecl, List<String> methParams,
2639 List<String> methPrmTypes, String method, Set<String> callbackType) {
2641 // Check if this is single object, array, or list of objects
2642 boolean isArrayOrList = false;
2643 String callbackParam = null;
2644 for (int i = 0; i < methParams.size(); i++) {
2645 String paramType = methPrmTypes.get(i);
2646 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
2647 println("vector<int> objIdSent" + i + ";");
2648 String param = methParams.get(i);
2649 if (isArrayOrList(paramType, param)) { // Generate loop
2650 println("for (" + getGenericType(paramType) + "* cb : " + getSimpleIdentifier(param) + ") {");
2651 writeCallbackInstantiationMethodBodyCplusStub("cb", returnGenericCallbackType(paramType), i);
2652 isArrayOrList = true;
2653 callbackParam = getSimpleIdentifier(param);
2655 writeCallbackInstantiationMethodBodyCplusStub(getSimpleIdentifier(param), returnGenericCallbackType(paramType), i);
2659 println("vector<int> ___paramCB" + i + " = objIdSent" + i + ";");
2666 * HELPER: checkAndWriteEnumTypeCplusStub() writes the enum type (convert from enum to int)
2668 private void checkAndWriteEnumTypeCplusStub(List<String> methParams, List<String> methPrmTypes) {
2670 // Iterate and find enum declarations
2671 for (int i = 0; i < methParams.size(); i++) {
2672 String paramType = methPrmTypes.get(i);
2673 String param = methParams.get(i);
2674 if (isEnumClass(getGenericType(paramType))) {
2675 // Check if this is enum type
2676 if (isArrayOrList(paramType, param)) { // An array or vector
2677 println("int len" + i + " = " + getSimpleIdentifier(param) + ".size();");
2678 println("vector<int> paramEnum" + i + "(len" + i + ");");
2679 println("for (int i = 0; i < len" + i + "; i++) {");
2680 println("paramEnum" + i + "[i] = (int) " + getSimpleIdentifier(param) + "[i];");
2682 } else { // Just one element
2683 println("vector<int> paramEnum" + i + "(1);");
2684 println("paramEnum" + i + "[0] = (int) " + param + ";");
2692 * HELPER: checkAndWriteEnumRetTypeCplusStub() writes the enum return type (convert from enum to int)
2694 private void checkAndWriteEnumRetTypeCplusStub(String retType, String method, InterfaceDecl intDecl) {
2696 // Strips off array "[]" for return type
2697 String pureType = getSimpleArrayType(getGenericType(retType));
2698 // Take the inner type of generic
2699 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
2700 pureType = getGenericType(retType);
2701 if (isEnumClass(pureType)) {
2702 // Check if this is enum type
2703 println("vector<int> retEnumInt;");
2704 println("void* retObj = &retEnumInt;");
2705 println("rmiComm->remoteCall(objectId, methodId, paramCls, paramObj, numParam);");
2706 writeWaitForReturnValueCplus(method, intDecl, "rmiComm->getReturnValue(retType, retObj);");
2707 if (isArrayOrList(retType, retType)) { // An array or vector
2708 println("int retLen = retEnumInt.size();");
2709 println("vector<" + pureType + "> retVal(retLen);");
2710 println("for (int i = 0; i < retLen; i++) {");
2711 println("retVal[i] = (" + pureType + ") retEnumInt[i];");
2713 } else { // Just one element
2714 println(pureType + " retVal = (" + pureType + ") retEnumInt[0];");
2716 println("return retVal;");
2722 * HELPER: checkAndWriteStructSetupCplusStub() writes the struct type setup
2724 private void checkAndWriteStructSetupCplusStub(List<String> methParams, List<String> methPrmTypes,
2725 InterfaceDecl intDecl, String method) {
2727 // Iterate and find struct declarations
2728 for (int i = 0; i < methParams.size(); i++) {
2729 String paramType = methPrmTypes.get(i);
2730 String param = methParams.get(i);
2731 String simpleType = getGenericType(paramType);
2732 if (isStructClass(simpleType)) {
2733 // Check if this is enum type
2734 println("int numParam" + i + " = 1;");
2735 int methodNumId = intDecl.getMethodNumId(method);
2736 String helperMethod = methodNumId + "struct" + i;
2737 println("int methodIdStruct" + i + " = " + intDecl.getHelperMethodNumId(helperMethod) + ";");
2738 //println("string retTypeStruct" + i + " = \"void\";");
2739 println("string paramClsStruct" + i + "[] = { \"int\" };");
2740 print("int structLen" + i + " = ");
2741 if (isArrayOrList(paramType, param)) { // An array
2742 println(getSimpleArrayType(param) + ".size();");
2743 } else { // Just one element
2746 println("void* paramObjStruct" + i + "[] = { &structLen" + i + " };");
2747 //println("void* retStructLen" + i + " = NULL;");
2748 println("rmiComm->remoteCall(objectId, methodIdStruct" + i +
2749 ", paramClsStruct" + i + ", paramObjStruct" + i +
2750 ", numParam" + i + ");\n");
2757 * HELPER: writeLengthStructParamClassCplusStub() writes lengths of params
2759 private void writeLengthStructParamClassCplusStub(List<String> methParams, List<String> methPrmTypes) {
2761 // Iterate and find struct declarations - count number of params
2762 for (int i = 0; i < methParams.size(); i++) {
2763 String paramType = methPrmTypes.get(i);
2764 String param = methParams.get(i);
2765 String simpleType = getGenericType(paramType);
2766 if (isStructClass(simpleType)) {
2767 int members = getNumOfMembers(simpleType);
2768 if (isArrayOrList(paramType, param)) { // An array or list
2769 String structLen = getSimpleIdentifier(param) + ".size()";
2770 print(members + "*" + structLen);
2772 print(Integer.toString(members));
2775 if (i != methParams.size() - 1) {
2783 * HELPER: writeStructMembersCplusStub() writes member parameters of struct
2785 private void writeStructMembersCplusStub(String simpleType, String paramType, String param) {
2787 // Get the struct declaration for this struct and generate initialization code
2788 StructDecl structDecl = getStructDecl(simpleType);
2789 List<String> memTypes = structDecl.getMemberTypes(simpleType);
2790 List<String> members = structDecl.getMembers(simpleType);
2791 if (isArrayOrList(paramType, param)) { // An array or list
2792 println("for(int i = 0; i < " + getSimpleIdentifier(param) + ".size(); i++) {");
2794 if (isArrayOrList(paramType, param)) { // An array or list
2795 for (int i = 0; i < members.size(); i++) {
2796 String prmTypeC = checkAndGetCplusArgClsType(memTypes.get(i), members.get(i));
2797 println("paramCls[pos] = \"" + prmTypeC + "\";");
2798 print("paramObj[pos++] = &" + getSimpleIdentifier(param) + "[i].");
2799 print(getSimpleIdentifier(members.get(i)));
2803 } else { // Just one struct element
2804 for (int i = 0; i < members.size(); i++) {
2805 String prmTypeC = checkAndGetCplusArgClsType(memTypes.get(i), members.get(i));
2806 println("paramCls[pos] = \"" + prmTypeC + "\";");
2807 print("paramObj[pos++] = &" + param + ".");
2808 print(getSimpleIdentifier(members.get(i)));
2816 * HELPER: writeStructParamClassCplusStub() writes member parameters of struct
2818 private void writeStructParamClassCplusStub(List<String> methParams, List<String> methPrmTypes, Set<String> callbackType) {
2820 print("int numParam = ");
2821 writeLengthStructParamClassCplusStub(methParams, methPrmTypes);
2823 println("void* paramObj[numParam];");
2824 println("string paramCls[numParam];");
2825 println("int pos = 0;");
2826 // Iterate again over the parameters
2827 for (int i = 0; i < methParams.size(); i++) {
2828 String paramType = methPrmTypes.get(i);
2829 String param = methParams.get(i);
2830 String simpleType = getGenericType(paramType);
2831 if (isStructClass(simpleType)) {
2832 writeStructMembersCplusStub(simpleType, paramType, param);
2833 } else if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
2834 println("paramCls[pos] = \"int\";");
2835 println("paramObj[pos++] = &___paramCB" + i + ";");
2837 String prmTypeC = checkAndGetCplusArgClsType(methPrmTypes.get(i), methParams.get(i));
2838 println("paramCls[pos] = \"" + prmTypeC + "\";");
2839 print("paramObj[pos++] = &");
2840 print(getEnumParam(methPrmTypes.get(i), getSimpleIdentifier(methParams.get(i)), i));
2849 * HELPER: writeStructRetMembersCplusStub() writes member parameters of struct for return statement
2851 private void writeStructRetMembersCplusStub(String simpleType, String retType) {
2853 // Get the struct declaration for this struct and generate initialization code
2854 StructDecl structDecl = getStructDecl(simpleType);
2855 List<String> memTypes = structDecl.getMemberTypes(simpleType);
2856 List<String> members = structDecl.getMembers(simpleType);
2857 if (isArrayOrList(retType, retType)) { // An array or list
2858 println("for(int i = 0; i < retLen; i++) {");
2860 if (isArrayOrList(retType, retType)) { // An array or list
2861 for (int i = 0; i < members.size(); i++) {
2862 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
2863 print("structRet[i]." + getSimpleIdentifier(members.get(i)));
2864 println(" = retParam" + i + "[i];");
2867 } else { // Just one struct element
2868 for (int i = 0; i < members.size(); i++) {
2869 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
2870 print("structRet." + getSimpleIdentifier(members.get(i)));
2871 println(" = retParam" + i + ";");
2874 println("return structRet;");
2879 * HELPER: writeStructReturnCplusStub() writes member parameters of struct for return statement
2881 private void writeStructReturnCplusStub(String simpleType, String retType, String method, InterfaceDecl intDecl) {
2883 // Minimum retLen is 1 if this is a single struct object
2884 println("int retLen = 0;");
2885 println("void* retLenObj = { &retLen };");
2886 // Handle the returned struct!!!
2887 println("rmiComm->remoteCall(objectId, methodId, paramCls, paramObj, numParam);");
2888 writeWaitForReturnValueCplus(method, intDecl, "rmiComm->getReturnValue(retType, retLenObj);");
2889 int numMem = getNumOfMembers(simpleType);
2890 println("int numRet = " + numMem + "*retLen;");
2891 println("string retCls[numRet];");
2892 println("void* retObj[numRet];");
2893 StructDecl structDecl = getStructDecl(simpleType);
2894 List<String> memTypes = structDecl.getMemberTypes(simpleType);
2895 List<String> members = structDecl.getMembers(simpleType);
2897 if (isArrayOrList(retType, retType)) { // An array or list
2898 for (int i = 0; i < members.size(); i++) {
2899 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
2900 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
2901 println(getSimpleType(getEnumType(prmType)) + " retParam" + i + "[retLen];");
2903 } else { // Just one struct element
2904 for (int i = 0; i < members.size(); i++) {
2905 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
2906 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
2907 println(getSimpleType(getEnumType(prmType)) + " retParam" + i + ";");
2910 println("int retPos = 0;");
2911 // Get the struct declaration for this struct and generate initialization code
2912 if (isArrayOrList(retType, retType)) { // An array or list
2913 println("for(int i = 0; i < retLen; i++) {");
2914 for (int i = 0; i < members.size(); i++) {
2915 String prmTypeC = checkAndGetCplusArgClsType(memTypes.get(i), members.get(i));
2916 println("retCls[retPos] = \"" + prmTypeC + "\";");
2917 println("retObj[retPos++] = &retParam" + i + "[i];");
2920 } else { // Just one struct element
2921 for (int i = 0; i < members.size(); i++) {
2922 String prmTypeC = checkAndGetCplusArgClsType(memTypes.get(i), members.get(i));
2923 println("retCls[retPos] = \"" + prmTypeC + "\";");
2924 println("retObj[retPos++] = &retParam" + i + ";");
2927 //println("rmiComm->getStructObjects(retCls, numRet, retObj);");
2928 writeWaitForReturnValueCplus(method, intDecl, "rmiComm->getStructObjects(retCls, numRet, retObj);");
2929 if (isArrayOrList(retType, retType)) { // An array or list
2930 println("vector<" + simpleType + "> structRet(retLen);");
2932 println(simpleType + " structRet;");
2933 writeStructRetMembersCplusStub(simpleType, retType);
2938 * HELPER: writeWaitForReturnValueCplus() writes the synchronization part for return values
2940 private void writeWaitForReturnValueCplus(String method, InterfaceDecl intDecl, String getReturnValue) {
2942 println("// Waiting for return value");
2943 int methodNumId = intDecl.getMethodNumId(method);
2944 println("while (!retValueReceived" + methodNumId + ");");
2945 println(getReturnValue);
2946 println("retValueReceived" + methodNumId + " = false;");
2947 println("didGetReturnBytes.exchange(true);\n");
2952 * HELPER: writeStdMethodBodyCplusStub() writes the standard method body in the stub class
2954 private void writeStdMethodBodyCplusStub(InterfaceDecl intDecl, List<String> methParams,
2955 List<String> methPrmTypes, String method, Set<String> callbackType, boolean isCallbackMethod) {
2957 checkAndWriteStructSetupCplusStub(methParams, methPrmTypes, intDecl, method);
2958 println("int methodId = " + intDecl.getMethodNumId(method) + ";");
2959 String retType = intDecl.getMethodType(method);
2960 println("string retType = \"" + checkAndGetCplusRetClsType(getStructType(getEnumType(retType))) + "\";");
2961 checkAndWriteEnumTypeCplusStub(methParams, methPrmTypes);
2962 // Generate array of parameter types
2963 if (isStructPresent(methParams, methPrmTypes)) {
2964 writeStructParamClassCplusStub(methParams, methPrmTypes, callbackType);
2966 println("int numParam = " + methParams.size() + ";");
2967 print("string paramCls[] = { ");
2968 for (int i = 0; i < methParams.size(); i++) {
2969 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
2970 if (checkCallbackType(paramType, callbackType)) {
2973 String paramTypeC = checkAndGetCplusArgClsType(methPrmTypes.get(i), methParams.get(i));
2974 print("\"" + paramTypeC + "\"");
2976 // Check if this is the last element (don't print a comma)
2977 if (i != methParams.size() - 1) {
2982 // Generate array of parameter objects
2983 print("void* paramObj[] = { ");
2984 for (int i = 0; i < methParams.size(); i++) {
2985 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
2986 if (checkCallbackType(paramType, callbackType)) // Check if this has callback object
2987 print("&___paramCB" + i);
2989 print("&" + getEnumParam(methPrmTypes.get(i), getSimpleIdentifier(methParams.get(i)), i));
2990 // Check if this is the last element (don't print a comma)
2991 if (i != methParams.size() - 1) {
2997 // Check if this is "void"
2998 if (retType.equals("void")) {
2999 println("rmiComm->remoteCall(objectId, methodId, paramCls, paramObj, numParam);");
3000 } else { // We do have a return value
3001 // Generate array of parameter types
3002 if (isStructClass(getGenericType(getSimpleArrayType(retType)))) {
3003 writeStructReturnCplusStub(getGenericType(getSimpleArrayType(retType)), retType, method, intDecl);
3005 // Check if the return value NONPRIMITIVES
3006 if (isEnumClass(getSimpleArrayType(getGenericType(retType)))) {
3007 checkAndWriteEnumRetTypeCplusStub(retType, method, intDecl);
3009 //if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
3010 if (isArrayOrList(retType,retType))
3011 println(checkAndGetCplusType(retType) + " retVal;");
3013 println(checkAndGetCplusType(retType) + " retVal = " + generateCplusInitializer(retType) + ";");
3015 println("void* retObj = &retVal;");
3016 println("rmiComm->remoteCall(objectId, methodId, paramCls, paramObj, numParam);");
3017 writeWaitForReturnValueCplus(method, intDecl, "rmiComm->getReturnValue(retType, retObj);");
3018 println("return retVal;");
3026 * HELPER: writePropertiesCplusPermission() writes the properties of the stub class
3028 private void writePropertiesCplusPermission(String intface) {
3030 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3031 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3032 String newIntface = intMeth.getKey();
3033 int newObjectId = getNewIntfaceObjectId(newIntface);
3034 println("static set<int> set" + newObjectId + "Allowed;");
3039 * HELPER: writePropertiesCplusStub() writes the properties of the stub class
3041 private void writePropertiesCplusStub(String intface, String newIntface, boolean callbackExist,
3042 Set<String> callbackClasses, Set<String> methods, InterfaceDecl intDecl) {
3044 println("IoTRMIComm *rmiComm;");
3045 // Get the object Id
3046 Integer objId = mapIntfaceObjId.get(intface);
3047 println("int objectId = " + objId + ";");
3048 println("// Synchronization variables");
3049 for (String method : methods) {
3050 // Generate AtomicBooleans for methods that have return values
3051 String returnType = intDecl.getMethodType(method);
3052 int methodNumId = intDecl.getMethodNumId(method);
3053 if (!returnType.equals("void")) {
3054 println("bool retValueReceived" + methodNumId + " = false;");
3062 * HELPER: writeConstructorCplusStub() writes the constructor of the stub class
3064 private void writeConstructorCplusStub(String newStubClass, boolean callbackExist,
3065 Set<String> callbackClasses, Set<String> methods, InterfaceDecl intDecl) {
3067 println(newStubClass + "::" + newStubClass +
3068 "(int _portSend, int _portRecv, const char* _skeletonAddress, int _rev, bool* _bResult) {");
3069 println("rmiComm = new IoTRMICommClient(_portSend, _portRecv, _skeletonAddress, _rev, _bResult);");
3070 // Register the AtomicBoolean variables
3071 for (String method : methods) {
3072 // Generate AtomicBooleans for methods that have return values
3073 String returnType = intDecl.getMethodType(method);
3074 int methodNumId = intDecl.getMethodNumId(method);
3075 if (!returnType.equals("void")) {
3076 println("rmiComm->registerStub(objectId, " + methodNumId + ", &retValueReceived" + methodNumId + ");");
3079 println("IoTRMIUtil::mapStub->insert(make_pair(objectId, this));");
3085 * HELPER: writeCallbackConstructorCplusStub() writes the callback constructor of the stub class
3087 private void writeCallbackConstructorCplusStub(String newStubClass, boolean callbackExist,
3088 Set<String> callbackClasses, Set<String> methods, InterfaceDecl intDecl) {
3090 println(newStubClass + "::" + newStubClass + "(IoTRMIComm* _rmiComm, int _objectId) {");
3091 println("rmiComm = _rmiComm;");
3092 println("objectId = _objectId;");
3093 // Register the AtomicBoolean variables
3094 for (String method : methods) {
3095 // Generate AtomicBooleans for methods that have return values
3096 String returnType = intDecl.getMethodType(method);
3097 int methodNumId = intDecl.getMethodNumId(method);
3098 if (!returnType.equals("void")) {
3099 println("rmiComm->registerStub(objectId, " + methodNumId + ", &retValueReceived" + methodNumId + ");");
3107 * HELPER: writeDeconstructorCplusStub() writes the deconstructor of the stub class
3109 private void writeDeconstructorCplusStub(String newStubClass, boolean callbackExist, Set<String> callbackClasses) {
3111 println(newStubClass + "::~" + newStubClass + "() {");
3112 println("if (rmiComm != NULL) {");
3113 println("delete rmiComm;");
3114 println("rmiComm = NULL;");
3122 * generateCPlusStubClassesHpp() generate stubs based on the methods list in C++ (.hpp file)
3124 public void generateCPlusStubClassesHpp() throws IOException {
3126 // Create a new directory
3127 String path = createDirectories(dir, subdir);
3128 for (String intface : mapIntfacePTH.keySet()) {
3130 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3131 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3132 // Open a new file to write into
3133 String newIntface = intMeth.getKey();
3134 String newStubClass = newIntface + "_Stub";
3135 FileWriter fw = new FileWriter(path + "/" + newStubClass + ".hpp");
3136 pw = new PrintWriter(new BufferedWriter(fw));
3137 // Write file headers
3138 println("#ifndef _" + newStubClass.toUpperCase() + "_HPP__");
3139 println("#define _" + newStubClass.toUpperCase() + "_HPP__");
3140 println("#include <iostream>");
3141 // Find out if there are callback objects
3142 Set<String> methods = intMeth.getValue();
3143 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
3144 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
3145 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
3146 boolean callbackExist = !callbackClasses.isEmpty();
3147 println("#include <thread>");
3148 println("#include <mutex>");
3149 List<String> stdIncludeClasses = getStandardCplusIncludeClasses();
3150 printIncludeStatements(stdIncludeClasses); println("");
3151 println("#include \"" + newIntface + ".hpp\""); println("");
3152 println("using namespace std;"); println("");
3153 println("class " + newStubClass + " : public " + newIntface); println("{");
3154 println("private:\n");
3155 writePropertiesCplusStub(intface, newIntface, callbackExist, callbackClasses, methods, intDecl);
3156 println("public:\n");
3157 // Add default constructor and destructor
3158 println(newStubClass + "();");
3160 println(newStubClass + "(int _portSend, int _portRecv, const char* _skeletonAddress, int _rev, bool* _bResult);");
3161 println(newStubClass + "(IoTRMIComm* _rmiComm, int _objectId);");
3162 println("~" + newStubClass + "();");
3164 writeMethodDeclCplusStub(methods, intDecl);
3165 print("}"); println(";");
3168 System.out.println("IoTCompiler: Generated stub class " + newStubClass + ".hpp...");
3175 * writeStubExternalCFunctions() generate external functions for .so file
3177 public void writeStubExternalCFunctions(String newStubClass) throws IOException {
3179 println("extern \"C\" void* create" + newStubClass + "(void** params) {");
3180 println("// Args: int _portSend, int _portRecv, const char* _skeletonAddress, int _rev, bool* _bResult");
3181 println("return new " + newStubClass + "(*((int*) params[0]), *((int*) params[1]), ((string*) params[2])->c_str(), " +
3182 "*((int*) params[3]), (bool*) params[4]);");
3184 println("extern \"C\" void destroy" + newStubClass + "(void* t) {");
3185 println(newStubClass + "* obj = (" + newStubClass + "*) t;");
3186 println("delete obj;");
3188 println("extern \"C\" void init" + newStubClass + "(void* t) {");
3189 //println(newStubClass + "* obj = (" + newStubClass + "*) t;");
3190 //println("obj->init();");
3191 //println("while(true);");
3197 * generateCPlusStubClassesCpp() generate stubs based on the methods list in C++ (.cpp file)
3199 public void generateCPlusStubClassesCpp() throws IOException {
3201 // Create a new directory
3202 String path = createDirectories(dir, subdir);
3203 for (String intface : mapIntfacePTH.keySet()) {
3205 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3206 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3207 // Open a new file to write into
3208 String newIntface = intMeth.getKey();
3209 String newStubClass = newIntface + "_Stub";
3210 FileWriter fw = new FileWriter(path + "/" + newStubClass + ".cpp");
3211 pw = new PrintWriter(new BufferedWriter(fw));
3212 // Write file headers
3213 println("#include <iostream>");
3214 // Find out if there are callback objects
3215 Set<String> methods = intMeth.getValue();
3216 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
3217 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
3218 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
3219 boolean callbackExist = !callbackClasses.isEmpty();
3220 println("#include \"" + newStubClass + ".hpp\""); println("");
3221 for(String str: callbackClasses) {
3222 if (intface.equals(mainClass))
3223 println("#include \"" + str + "_Skeleton.cpp\"\n");
3225 println("#include \"" + str + "_Skeleton.hpp\"\n");
3227 println("using namespace std;"); println("");
3228 // Add default constructor and destructor
3229 //println(newStubClass + "() { }"); println("");
3230 writeConstructorCplusStub(newStubClass, callbackExist, callbackClasses, methods, intDecl);
3231 writeCallbackConstructorCplusStub(newStubClass, callbackExist, callbackClasses, methods, intDecl);
3232 writeDeconstructorCplusStub(newStubClass, callbackExist, callbackClasses);
3234 writeMethodCplusStub(methods, intDecl, callbackClasses, newStubClass);
3235 // Write external functions for .so file
3236 writeStubExternalCFunctions(newStubClass);
3237 // TODO: Remove this later
3238 if (intface.equals(mainClass)) {
3239 println("int main() {");
3240 println("return 0;");
3244 System.out.println("IoTCompiler: Generated stub class " + newStubClass + ".cpp...");
3251 * HELPER: writePropertiesCplusSkeleton() writes the properties of the skeleton class
3253 private void writePropertiesCplusSkeleton(String intface, boolean callbackExist, Set<String> callbackClasses) {
3255 println(intface + " *mainObj;");
3256 println("IoTRMIComm *rmiComm;");
3257 println("char* methodBytes;");
3258 println("int methodLen;");
3259 Integer objId = mapIntfaceObjId.get(intface);
3260 println("int objectId = " + objId + ";");
3261 // Keep track of object Ids of all stubs registered to this interface
3262 writePropertiesCplusPermission(intface);
3263 println("// Synchronization variables");
3264 println("bool methodReceived = false;");
3265 println("bool didAlreadyInitWaitInvoke = false;");
3271 * HELPER: writeObjectIdCountInitializationCplus() writes the initialization of objIdCnt variable
3273 private void writeObjectIdCountInitializationCplus(String newSkelClass, boolean callbackExist) {
3276 println("int " + newSkelClass + "::objIdCnt = 0;");
3281 * HELPER: writePermissionInitializationCplus() writes the initialization of permission set
3283 private void writePermissionInitializationCplus(String intface, String newSkelClass, InterfaceDecl intDecl) {
3285 // Keep track of object Ids of all stubs registered to this interface
3286 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3287 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3288 String newIntface = intMeth.getKey();
3289 int newObjectId = getNewIntfaceObjectId(newIntface);
3290 print("set<int> " + newSkelClass + "::set" + newObjectId + "Allowed { ");
3291 Set<String> methodIds = intMeth.getValue();
3293 for (String methodId : methodIds) {
3294 int methodNumId = intDecl.getMethodNumId(methodId);
3295 print(Integer.toString(methodNumId));
3296 // Check if this is the last element (don't print a comma)
3297 if (i != methodIds.size() - 1) {
3308 * HELPER: writeStructPermissionCplusSkeleton() writes permission for struct helper
3310 private void writeStructPermissionCplusSkeleton(Collection<String> methods, InterfaceDecl intDecl, String intface) {
3312 // Use this set to handle two same methodIds
3313 for (String method : methods) {
3314 List<String> methParams = intDecl.getMethodParams(method);
3315 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
3316 // Check for params with structs
3317 for (int i = 0; i < methParams.size(); i++) {
3318 String paramType = methPrmTypes.get(i);
3319 String param = methParams.get(i);
3320 String simpleType = getGenericType(paramType);
3321 if (isStructClass(simpleType)) {
3322 int methodNumId = intDecl.getMethodNumId(method);
3323 String helperMethod = methodNumId + "struct" + i;
3324 int helperMethodNumId = intDecl.getHelperMethodNumId(helperMethod);
3325 // Iterate over interfaces to give permissions to
3326 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3327 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3328 String newIntface = intMeth.getKey();
3329 int newObjectId = getNewIntfaceObjectId(newIntface);
3330 println("set" + newObjectId + "Allowed.insert(" + helperMethodNumId + ");");
3339 * HELPER: writeConstructorCplusSkeleton() writes the constructor of the skeleton class
3341 private void writeConstructorCplusSkeleton(String newSkelClass, String intface, boolean callbackExist, InterfaceDecl intDecl, Collection<String> methods) {
3343 println(newSkelClass + "::" + newSkelClass + "(" + intface + " *_mainObj, int _portSend, int _portRecv) {");
3344 println("bool _bResult = false;");
3345 println("mainObj = _mainObj;");
3346 println("rmiComm = new IoTRMICommServer(_portSend, _portRecv, &_bResult);");
3347 println("IoTRMIUtil::mapSkel->insert(make_pair(_mainObj, this));");
3348 println("IoTRMIUtil::mapSkelId->insert(make_pair(_mainObj, objectId));");
3349 println("rmiComm->registerSkeleton(objectId, &methodReceived);");
3350 writeStructPermissionCplusSkeleton(methods, intDecl, intface);
3351 println("thread th1 (&" + newSkelClass + "::___waitRequestInvokeMethod, this, this);");
3352 println("th1.join();");
3358 * HELPER: writeCallbackConstructorCplusSkeleton() writes the callback constructor of the skeleton class
3360 private void writeCallbackConstructorCplusSkeleton(String newSkelClass, String intface, boolean callbackExist, InterfaceDecl intDecl, Collection<String> methods) {
3362 println(newSkelClass + "::" + newSkelClass + "(" + intface + " *_mainObj, IoTRMIComm *_rmiComm, int _objectId) {");
3363 println("bool _bResult = false;");
3364 println("mainObj = _mainObj;");
3365 println("rmiComm = _rmiComm;");
3366 println("objectId = _objectId;");
3367 println("rmiComm->registerSkeleton(objectId, &methodReceived);");
3368 writeStructPermissionCplusSkeleton(methods, intDecl, intface);
3374 * HELPER: writeDeconstructorCplusSkeleton() writes the deconstructor of the skeleton class
3376 private void writeDeconstructorCplusSkeleton(String newSkelClass, boolean callbackExist, Set<String> callbackClasses) {
3378 println(newSkelClass + "::~" + newSkelClass + "() {");
3379 println("if (rmiComm != NULL) {");
3380 println("delete rmiComm;");
3381 println("rmiComm = NULL;");
3389 * HELPER: writeStdMethodBodyCplusSkeleton() writes the standard method body in the skeleton class
3391 private void writeStdMethodBodyCplusSkeleton(List<String> methParams, String methodId, String methodType) {
3393 if (methodType.equals("void"))
3394 print("mainObj->" + methodId + "(");
3396 print("return mainObj->" + methodId + "(");
3397 for (int i = 0; i < methParams.size(); i++) {
3399 print(getSimpleIdentifier(methParams.get(i)));
3400 // Check if this is the last element (don't print a comma)
3401 if (i != methParams.size() - 1) {
3410 * HELPER: writeMethodDeclCplusSkeleton() writes the method declaration of the skeleton class
3412 private void writeMethodDeclCplusSkeleton(Collection<String> methods, InterfaceDecl intDecl,
3413 Set<String> callbackClasses) {
3415 for (String method : methods) {
3417 List<String> methParams = intDecl.getMethodParams(method);
3418 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
3419 String methodId = intDecl.getMethodId(method);
3420 String methodType = checkAndGetCplusType(intDecl.getMethodType(method));
3421 print(methodType + " " + methodId + "(");
3422 boolean isCallbackMethod = false;
3423 String callbackType = null;
3424 for (int i = 0; i < methParams.size(); i++) {
3426 String origParamType = methPrmTypes.get(i);
3427 if (callbackClasses.contains(origParamType)) { // Check if this has callback object
3428 isCallbackMethod = true;
3429 callbackType = origParamType;
3431 String paramType = checkAndGetParamClass(methPrmTypes.get(i));
3432 String methPrmType = checkAndGetCplusType(paramType);
3433 String methParamComplete = checkAndGetCplusArray(methPrmType, methParams.get(i));
3434 print(methParamComplete);
3435 // Check if this is the last element (don't print a comma)
3436 if (i != methParams.size() - 1) {
3446 * HELPER: writeMethodCplusSkeleton() writes the method of the skeleton class
3448 private void writeMethodCplusSkeleton(Collection<String> methods, InterfaceDecl intDecl, String newSkelClass) {
3450 for (String method : methods) {
3452 List<String> methParams = intDecl.getMethodParams(method);
3453 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
3454 String methodId = intDecl.getMethodId(method);
3455 String methodType = checkAndGetCplusType(intDecl.getMethodType(method));
3456 print(methodType + " " + newSkelClass + "::" + methodId + "(");
3457 for (int i = 0; i < methParams.size(); i++) {
3459 String origParamType = methPrmTypes.get(i);
3460 String paramType = checkAndGetParamClass(methPrmTypes.get(i));
3461 String methPrmType = checkAndGetCplusType(paramType);
3462 String methParamComplete = checkAndGetCplusArray(methPrmType, methParams.get(i));
3463 print(methParamComplete);
3464 // Check if this is the last element (don't print a comma)
3465 if (i != methParams.size() - 1) {
3470 // Now, write the body of skeleton!
3471 writeStdMethodBodyCplusSkeleton(methParams, methodId, intDecl.getMethodType(method));
3478 * HELPER: writeCallbackCplusNumStubs() writes the numStubs variable
3480 private void writeCallbackCplusNumStubs(List<String> methParams, List<String> methPrmTypes, Set<String> callbackType) {
3482 for (int i = 0; i < methParams.size(); i++) {
3483 String paramType = methPrmTypes.get(i);
3484 String param = methParams.get(i);
3485 //if (callbackType.equals(paramType)) {
3486 if (checkCallbackType(paramType, callbackType)) // Check if this has callback object
3487 //println("int numStubs" + i + " = 0;");
3488 println("vector<int> numStubIdArray" + i + ";");
3494 * HELPER: writeCallbackInstantiationCplusStubGeneration() writes the instantiation of callback stubs
3496 private void writeCallbackInstantiationCplusStubGeneration(String exchParamType, int counter) {
3498 println(exchParamType + "* newStub" + counter + " = NULL;");
3499 println("auto it" + counter + " = IoTRMIUtil::mapStub->find(objIdRecv" + counter + ");");
3500 println("if (it" + counter + " == IoTRMIUtil::mapStub->end()) {");
3501 println("newStub" + counter + " = new " + exchParamType + "_Stub(rmiComm, objIdRecv" + counter + ");");
3502 println("IoTRMIUtil::mapStub->insert(make_pair(objIdRecv" + counter + ", newStub" + counter + "));");
3503 println("rmiComm->setObjectIdCounter(objIdRecv" + counter + ");");
3504 println("rmiComm->decrementObjectIdCounter();");
3507 println("newStub" + counter + " = (" + exchParamType + "_Stub*) it" + counter + "->second;");
3513 * HELPER: writeCallbackCplusStubGeneration() writes the callback stub generation part
3515 private void writeCallbackCplusStubGeneration(List<String> methParams, List<String> methPrmTypes, Set<String> callbackType) {
3517 // Iterate over callback objects
3518 for (int i = 0; i < methParams.size(); i++) {
3519 String paramType = methPrmTypes.get(i);
3520 String param = methParams.get(i);
3521 // Generate a loop if needed
3522 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
3523 String exchParamType = checkAndGetParamClass(getGenericType(paramType));
3524 if (isArrayOrList(paramType, param)) {
3525 println("vector<" + exchParamType + "*> stub" + i + ";");
3526 println("for (int i = 0; i < numStubIdArray" + i + ".size(); i++) {");
3527 println("int objIdRecv" + i + " = numStubIdArray" + i + "[i];");
3528 writeCallbackInstantiationCplusStubGeneration(exchParamType, i);
3529 println("stub" + i + ".push_back(newStub" + i + ");");
3532 println("int objIdRecv" + i + " = numStubIdArray" + i + "[0];");
3533 writeCallbackInstantiationCplusStubGeneration(exchParamType, i);
3534 println(exchParamType + "* stub" + i + " = newStub" + i + ";");
3542 * HELPER: checkAndWriteEnumTypeCplusSkeleton() writes the enum type (convert from enum to int)
3544 private void checkAndWriteEnumTypeCplusSkeleton(List<String> methParams, List<String> methPrmTypes) {
3546 // Iterate and find enum declarations
3547 for (int i = 0; i < methParams.size(); i++) {
3548 String paramType = methPrmTypes.get(i);
3549 String param = methParams.get(i);
3550 String simpleType = getGenericType(paramType);
3551 if (isEnumClass(simpleType)) {
3552 // Check if this is enum type
3553 if (isArrayOrList(paramType, param)) { // An array
3554 println("int len" + i + " = paramEnumInt" + i + ".size();");
3555 println("vector<" + simpleType + "> paramEnum" + i + "(len" + i + ");");
3556 println("for (int i=0; i < len" + i + "; i++) {");
3557 println("paramEnum" + i + "[i] = (" + simpleType + ") paramEnumInt" + i + "[i];");
3559 } else { // Just one element
3560 println(simpleType + " paramEnum" + i + ";");
3561 println("paramEnum" + i + " = (" + simpleType + ") paramEnumInt" + i + "[0];");
3569 * HELPER: checkAndWriteEnumRetTypeCplusSkeleton() writes the enum return type (convert from enum to int)
3571 private void checkAndWriteEnumRetTypeCplusSkeleton(String retType) {
3573 // Strips off array "[]" for return type
3574 String pureType = getSimpleArrayType(getGenericType(retType));
3575 // Take the inner type of generic
3576 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
3577 pureType = getGenericType(retType);
3578 if (isEnumClass(pureType)) {
3579 // Check if this is enum type
3581 if (isArrayOrList(retType, retType)) { // An array
3582 println("int retLen = retEnum.size();");
3583 println("vector<int> retEnumInt(retLen);");
3584 println("for (int i=0; i < retLen; i++) {");
3585 println("retEnumInt[i] = (int) retEnum[i];");
3587 } else { // Just one element
3588 println("vector<int> retEnumInt(1);");
3589 println("retEnumInt[0] = (int) retEnum;");
3596 * HELPER: writeMethodInputParameters() writes the parameter variables for C++ skeleton
3598 private void writeMethodInputParameters(List<String> methParams, List<String> methPrmTypes,
3599 Set<String> callbackClasses, String methodId) {
3601 print(methodId + "(");
3602 for (int i = 0; i < methParams.size(); i++) {
3603 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
3604 if (callbackClasses.contains(paramType))
3606 else if (isEnumClass(getGenericType(paramType))) // Check if this is enum type
3607 print("paramEnum" + i);
3608 else if (isStructClass(getGenericType(paramType))) // Struct type
3609 print("paramStruct" + i);
3611 print(getSimpleIdentifier(methParams.get(i)));
3612 if (i != methParams.size() - 1) {
3621 * HELPER: writeMethodHelperReturnCplusSkeleton() writes the return statement part in skeleton
3623 private void writeMethodHelperReturnCplusSkeleton(InterfaceDecl intDecl, List<String> methParams,
3624 List<String> methPrmTypes, String method, boolean isCallbackMethod, Set<String> callbackType,
3625 String methodId, Set<String> callbackClasses) {
3627 println("rmiComm->getMethodParams(paramCls, numParam, paramObj, localMethodBytes);");
3628 if (isCallbackMethod)
3629 writeCallbackCplusStubGeneration(methParams, methPrmTypes, callbackType);
3630 checkAndWriteEnumTypeCplusSkeleton(methParams, methPrmTypes);
3631 writeStructMembersInitCplusSkeleton(intDecl, methParams, methPrmTypes, method);
3632 // Check if this is "void"
3633 String retType = intDecl.getMethodType(method);
3634 // Check if this is "void"
3635 if (retType.equals("void")) {
3636 writeMethodInputParameters(methParams, methPrmTypes, callbackClasses, methodId);
3637 } else { // We do have a return value
3638 if (isEnumClass(getSimpleArrayType(getGenericType(retType)))) // Enum type
3639 print(checkAndGetCplusType(retType) + " retEnum = ");
3640 else if (isStructClass(getSimpleArrayType(getGenericType(retType)))) // Struct type
3641 print(checkAndGetCplusType(retType) + " retStruct = ");
3643 print(checkAndGetCplusType(retType) + " retVal = ");
3644 writeMethodInputParameters(methParams, methPrmTypes, callbackClasses, methodId);
3645 checkAndWriteEnumRetTypeCplusSkeleton(retType);
3646 if (isStructClass(getSimpleArrayType(getGenericType(retType)))) // Struct type
3647 writeStructReturnCplusSkeleton(getSimpleArrayType(getGenericType(retType)), retType);
3648 if (isEnumClass(getSimpleArrayType(getGenericType(retType)))) // Enum type
3649 println("void* retObj = &retEnumInt;");
3651 if (!isStructClass(getSimpleArrayType(getGenericType(retType)))) // Struct type
3652 println("void* retObj = &retVal;");
3653 String retTypeC = checkAndGetCplusType(retType);
3654 if (isStructClass(getSimpleArrayType(getGenericType(retType)))) // Struct type
3655 println("rmiComm->sendReturnObj(retObj, retCls, numRetObj, localMethodBytes);");
3657 println("rmiComm->sendReturnObj(retObj, \"" + checkAndGetCplusRetClsType(getEnumType(retType)) + "\", localMethodBytes);");
3663 * HELPER: writeStdMethodHelperBodyCplusSkeleton() writes the standard method body helper in the skeleton class
3665 private void writeStdMethodHelperBodyCplusSkeleton(InterfaceDecl intDecl, List<String> methParams,
3666 List<String> methPrmTypes, String method, String methodId, Set<String> callbackClasses) {
3668 // Generate array of parameter types
3669 boolean isCallbackMethod = false;
3670 //String callbackType = null;
3671 Set<String> callbackType = new HashSet<String>();
3672 print("string paramCls[] = { ");
3673 for (int i = 0; i < methParams.size(); i++) {
3674 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
3675 if (callbackClasses.contains(paramType)) {
3676 isCallbackMethod = true;
3677 //callbackType = paramType;
3678 callbackType.add(paramType);
3680 } else { // Generate normal classes if it's not a callback object
3681 String paramTypeC = checkAndGetCplusArgClsType(methPrmTypes.get(i), methParams.get(i));
3682 print("\"" + paramTypeC + "\"");
3684 if (i != methParams.size() - 1) {
3689 println("int numParam = " + methParams.size() + ";");
3690 if (isCallbackMethod)
3691 writeCallbackCplusNumStubs(methParams, methPrmTypes, callbackType);
3692 // Generate parameters
3693 for (int i = 0; i < methParams.size(); i++) {
3694 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
3695 if (!callbackClasses.contains(paramType)) {
3696 String methParamType = methPrmTypes.get(i);
3697 if (isEnumClass(getSimpleArrayType(getGenericType(methParamType)))) {
3698 // Check if this is enum type
3699 println("vector<int> paramEnumInt" + i + ";");
3701 String methPrmType = checkAndGetCplusType(methParamType);
3702 String methParamComplete = checkAndGetCplusArray(methPrmType, methParams.get(i));
3703 println(methParamComplete + ";");
3707 // Generate array of parameter objects
3708 print("void* paramObj[] = { ");
3709 for (int i = 0; i < methParams.size(); i++) {
3710 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
3711 if (callbackClasses.contains(paramType))
3712 print("&numStubIdArray" + i);
3713 else if (isEnumClass(getGenericType(paramType))) // Check if this is enum type
3714 print("¶mEnumInt" + i);
3716 print("&" + getSimpleIdentifier(methParams.get(i)));
3717 if (i != methParams.size() - 1) {
3722 // Write the return value part
3723 writeMethodHelperReturnCplusSkeleton(intDecl, methParams, methPrmTypes, method, isCallbackMethod,
3724 callbackType, methodId, callbackClasses);
3729 * HELPER: writeStructMembersCplusSkeleton() writes member parameters of struct
3731 private void writeStructMembersCplusSkeleton(String simpleType, String paramType,
3732 String param, String method, InterfaceDecl intDecl, int iVar) {
3734 // Get the struct declaration for this struct and generate initialization code
3735 StructDecl structDecl = getStructDecl(simpleType);
3736 List<String> memTypes = structDecl.getMemberTypes(simpleType);
3737 List<String> members = structDecl.getMembers(simpleType);
3738 int methodNumId = intDecl.getMethodNumId(method);
3739 String counter = "struct" + methodNumId + "Size" + iVar;
3741 if (isArrayOrList(paramType, param)) { // An array or list
3742 for (int i = 0; i < members.size(); i++) {
3743 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
3744 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
3745 println(getSimpleType(getEnumType(prmType)) + " param" + iVar + i + "[" + counter + "];");
3747 } else { // Just one struct element
3748 for (int i = 0; i < members.size(); i++) {
3749 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
3750 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
3751 println(getSimpleType(getEnumType(prmType)) + " param" + iVar + i + ";");
3754 if (isArrayOrList(paramType, param)) { // An array or list
3755 println("for(int i = 0; i < " + counter + "; i++) {");
3757 if (isArrayOrList(paramType, param)) { // An array or list
3758 for (int i = 0; i < members.size(); i++) {
3759 String prmTypeC = checkAndGetCplusArgClsType(memTypes.get(i), members.get(i));
3760 println("paramCls[pos] = \"" + prmTypeC + "\";");
3761 println("paramObj[pos++] = ¶m" + iVar + i + "[i];");
3764 } else { // Just one struct element
3765 for (int i = 0; i < members.size(); i++) {
3766 String prmTypeC = checkAndGetCplusArgClsType(memTypes.get(i), members.get(i));
3767 println("paramCls[pos] = \"" + prmTypeC + "\";");
3768 println("paramObj[pos++] = ¶m" + iVar + i + ";");
3775 * HELPER: writeStructMembersInitCplusSkeleton() writes member parameters initialization of struct
3777 private void writeStructMembersInitCplusSkeleton(InterfaceDecl intDecl, List<String> methParams,
3778 List<String> methPrmTypes, String method) {
3780 for (int i = 0; i < methParams.size(); i++) {
3781 String paramType = methPrmTypes.get(i);
3782 String param = methParams.get(i);
3783 String simpleType = getGenericType(paramType);
3784 if (isStructClass(simpleType)) {
3785 int methodNumId = intDecl.getMethodNumId(method);
3786 String counter = "struct" + methodNumId + "Size" + i;
3788 if (isArrayOrList(paramType, param)) { // An array or list
3789 println("vector<" + simpleType + "> paramStruct" + i + "(" + counter + ");");
3791 println(simpleType + " paramStruct" + i + ";");
3792 // Initialize members
3793 StructDecl structDecl = getStructDecl(simpleType);
3794 List<String> members = structDecl.getMembers(simpleType);
3795 List<String> memTypes = structDecl.getMemberTypes(simpleType);
3796 if (isArrayOrList(paramType, param)) { // An array or list
3797 println("for(int i = 0; i < " + counter + "; i++) {");
3798 for (int j = 0; j < members.size(); j++) {
3799 print("paramStruct" + i + "[i]." + getSimpleIdentifier(members.get(j)));
3800 println(" = param" + i + j + "[i];");
3803 } else { // Just one struct element
3804 for (int j = 0; j < members.size(); j++) {
3805 print("paramStruct" + i + "." + getSimpleIdentifier(members.get(j)));
3806 println(" = param" + i + j + ";");
3815 * HELPER: writeStructReturnCplusSkeleton() writes parameters of struct for return statement
3817 private void writeStructReturnCplusSkeleton(String simpleType, String retType) {
3819 // Minimum retLen is 1 if this is a single struct object
3820 if (isArrayOrList(retType, retType))
3821 println("int retLen = retStruct.size();");
3822 else // Just single struct object
3823 println("int retLen = 1;");
3824 println("void* retLenObj = &retLen;");
3825 println("rmiComm->sendReturnObj(retLenObj, \"int\", localMethodBytes);");
3826 int numMem = getNumOfMembers(simpleType);
3827 println("int numRetObj = " + numMem + "*retLen;");
3828 println("string retCls[numRetObj];");
3829 println("void* retObj[numRetObj];");
3830 println("int retPos = 0;");
3831 // Get the struct declaration for this struct and generate initialization code
3832 StructDecl structDecl = getStructDecl(simpleType);
3833 List<String> memTypes = structDecl.getMemberTypes(simpleType);
3834 List<String> members = structDecl.getMembers(simpleType);
3835 if (isArrayOrList(retType, retType)) { // An array or list
3836 println("for(int i = 0; i < retLen; i++) {");
3837 for (int i = 0; i < members.size(); i++) {
3838 String prmTypeC = checkAndGetCplusArgClsType(memTypes.get(i), members.get(i));
3839 println("retCls[retPos] = \"" + prmTypeC + "\";");
3840 print("retObj[retPos++] = &retStruct[i].");
3841 print(getEnumParam(memTypes.get(i), getSimpleIdentifier(members.get(i)), i));
3845 } else { // Just one struct element
3846 for (int i = 0; i < members.size(); i++) {
3847 String prmTypeC = checkAndGetCplusArgClsType(memTypes.get(i), members.get(i));
3848 println("retCls[retPos] = \"" + prmTypeC + "\";");
3849 print("retObj[retPos++] = &retStruct.");
3850 print(getEnumParam(memTypes.get(i), getSimpleIdentifier(members.get(i)), i));
3859 * HELPER: writeMethodHelperStructCplusSkeleton() writes the struct in skeleton
3861 private void writeMethodHelperStructCplusSkeleton(InterfaceDecl intDecl, List<String> methParams,
3862 List<String> methPrmTypes, String method, String methodId, Set<String> callbackClasses) {
3864 // Generate array of parameter objects
3865 boolean isCallbackMethod = false;
3866 Set<String> callbackType = new HashSet<String>();
3867 print("int numParam = ");
3868 writeLengthStructParamClassSkeleton(methParams, methPrmTypes, method, intDecl);
3870 println("string paramCls[numParam];");
3871 println("void* paramObj[numParam];");
3872 println("int pos = 0;");
3873 // Iterate again over the parameters
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 writeStructMembersCplusSkeleton(simpleType, paramType, param, method, intDecl, i);
3881 String prmType = returnGenericCallbackType(methPrmTypes.get(i));
3882 if (callbackClasses.contains(prmType)) {
3883 isCallbackMethod = true;
3884 //callbackType = prmType;
3885 callbackType.add(prmType);
3886 //println("int numStubs" + i + " = 0;");
3887 println("vector<int> numStubIdArray" + i + ";");
3888 println("paramCls[pos] = \"int*\";");
3889 println("paramObj[pos++] = &numStubIdArray" + i + ";");
3890 } else { // Generate normal classes if it's not a callback object
3891 String paramTypeC = checkAndGetCplusType(methPrmTypes.get(i));
3892 if (isEnumClass(getGenericType(paramTypeC))) { // Check if this is enum type
3893 println("vector<int> paramEnumInt" + i + ";");
3895 String methParamComplete = checkAndGetCplusArray(paramTypeC, methParams.get(i));
3896 println(methParamComplete + ";");
3898 String prmTypeC = checkAndGetCplusArgClsType(methPrmTypes.get(i), methParams.get(i));
3899 println("paramCls[pos] = \"" + prmTypeC + "\";");
3900 if (isEnumClass(getGenericType(paramType))) // Check if this is enum type
3901 println("paramObj[pos++] = ¶mEnumInt" + i + ";");
3903 println("paramObj[pos++] = &" + getSimpleIdentifier(methParams.get(i)) + ";");
3907 // Write the return value part
3908 writeMethodHelperReturnCplusSkeleton(intDecl, methParams, methPrmTypes, method, isCallbackMethod,
3909 callbackType, methodId, callbackClasses);
3914 * HELPER: writeMethodHelperDeclCplusSkeleton() writes the method helper declarations of the skeleton class
3916 private void writeMethodHelperDeclCplusSkeleton(Collection<String> methods, InterfaceDecl intDecl, String newSkelClass) {
3918 // Use this set to handle two same methodIds
3919 Set<String> uniqueMethodIds = new HashSet<String>();
3920 for (String method : methods) {
3922 List<String> methParams = intDecl.getMethodParams(method);
3923 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
3924 if (isStructPresent(methParams, methPrmTypes)) { // Treat struct differently
3925 String methodId = intDecl.getMethodId(method);
3927 String helperMethod = methodId;
3928 if (uniqueMethodIds.contains(methodId))
3929 helperMethod = helperMethod + intDecl.getMethodNumId(method);
3931 uniqueMethodIds.add(methodId);
3932 String retType = intDecl.getMethodType(method);
3933 print(helperMethod + "(");
3934 boolean begin = true;
3935 for (int i = 0; i < methParams.size(); i++) { // Print size variables
3936 String paramType = methPrmTypes.get(i);
3937 String param = methParams.get(i);
3938 String simpleType = getGenericType(paramType);
3939 if (isStructClass(simpleType)) {
3940 if (!begin) // Generate comma for not the beginning variable
3944 int methodNumId = intDecl.getMethodNumId(method);
3945 print("int struct" + methodNumId + "Size" + i);
3948 println(", " + newSkelClass + "* skel);");
3950 String methodId = intDecl.getMethodId(method);
3952 String helperMethod = methodId;
3953 if (uniqueMethodIds.contains(methodId))
3954 helperMethod = helperMethod + intDecl.getMethodNumId(method);
3956 uniqueMethodIds.add(methodId);
3957 // Check if this is "void"
3958 String retType = intDecl.getMethodType(method);
3959 println(helperMethod + "(" + newSkelClass + "* skel);");
3962 // Write method helper for structs
3963 writeMethodHelperStructDeclSetupCplusSkeleton(methods, intDecl, newSkelClass);
3968 * HELPER: writeMethodHelperStructDeclSetupCplusSkeleton() writes the struct method helper declaration in skeleton class
3970 private void writeMethodHelperStructDeclSetupCplusSkeleton(Collection<String> methods,
3971 InterfaceDecl intDecl, String newSkelClass) {
3973 // Use this set to handle two same methodIds
3974 for (String method : methods) {
3976 List<String> methParams = intDecl.getMethodParams(method);
3977 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
3978 // Check for params with structs
3979 for (int i = 0; i < methParams.size(); i++) {
3980 String paramType = methPrmTypes.get(i);
3981 String param = methParams.get(i);
3982 String simpleType = getGenericType(paramType);
3983 if (isStructClass(simpleType)) {
3984 int methodNumId = intDecl.getMethodNumId(method);
3986 String helperMethod = methodNumId + "struct" + i;
3987 println(helperMethod + "(" + newSkelClass + "* skel);");
3995 * HELPER: writeMethodBytesCopy() writes the methodBytes copy part in C++ skeleton
3997 private void writeMethodBytesCopy() {
3999 println("char* localMethodBytes = new char[methodLen];");
4000 println("memcpy(localMethodBytes, skel->methodBytes, methodLen);");
4001 println("didGetMethodBytes.exchange(true);");
4006 * HELPER: writeMethodHelperCplusSkeleton() writes the method helper of the skeleton class
4008 private void writeMethodHelperCplusSkeleton(Collection<String> methods, InterfaceDecl intDecl,
4009 Set<String> callbackClasses, String newSkelClass) {
4011 // Use this set to handle two same methodIds
4012 Set<String> uniqueMethodIds = new HashSet<String>();
4013 for (String method : methods) {
4015 List<String> methParams = intDecl.getMethodParams(method);
4016 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4017 if (isStructPresent(methParams, methPrmTypes)) { // Treat struct differently
4018 String methodId = intDecl.getMethodId(method);
4019 print("void " + newSkelClass + "::___");
4020 String helperMethod = methodId;
4021 if (uniqueMethodIds.contains(methodId))
4022 helperMethod = helperMethod + intDecl.getMethodNumId(method);
4024 uniqueMethodIds.add(methodId);
4025 String retType = intDecl.getMethodType(method);
4026 print(helperMethod + "(");
4027 boolean begin = true;
4028 for (int i = 0; i < methParams.size(); i++) { // Print size variables
4029 String paramType = methPrmTypes.get(i);
4030 String param = methParams.get(i);
4031 String simpleType = getGenericType(paramType);
4032 if (isStructClass(simpleType)) {
4033 if (!begin) // Generate comma for not the beginning variable
4037 int methodNumId = intDecl.getMethodNumId(method);
4038 print("int struct" + methodNumId + "Size" + i);
4041 println(", " + newSkelClass + "* skel) {");
4042 writeMethodBytesCopy();
4043 writeMethodHelperStructCplusSkeleton(intDecl, methParams, methPrmTypes, method, methodId, callbackClasses);
4044 println("delete[] localMethodBytes;");
4047 String methodId = intDecl.getMethodId(method);
4048 print("void " + newSkelClass + "::___");
4049 String helperMethod = methodId;
4050 if (uniqueMethodIds.contains(methodId))
4051 helperMethod = helperMethod + intDecl.getMethodNumId(method);
4053 uniqueMethodIds.add(methodId);
4054 // Check if this is "void"
4055 String retType = intDecl.getMethodType(method);
4056 println(helperMethod + "(" + newSkelClass + "* skel) {");
4057 writeMethodBytesCopy();
4058 // Now, write the helper body of skeleton!
4059 writeStdMethodHelperBodyCplusSkeleton(intDecl, methParams, methPrmTypes, method, methodId, callbackClasses);
4060 println("delete[] localMethodBytes;");
4064 // Write method helper for structs
4065 writeMethodHelperStructSetupCplusSkeleton(methods, intDecl, newSkelClass);
4070 * HELPER: writeMethodHelperStructSetupCplusSkeleton() writes the method helper of struct in skeleton class
4072 private void writeMethodHelperStructSetupCplusSkeleton(Collection<String> methods,
4073 InterfaceDecl intDecl, String newSkelClass) {
4075 // Use this set to handle two same methodIds
4076 for (String method : methods) {
4078 List<String> methParams = intDecl.getMethodParams(method);
4079 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4080 // Check for params with structs
4081 for (int i = 0; i < methParams.size(); i++) {
4082 String paramType = methPrmTypes.get(i);
4083 String param = methParams.get(i);
4084 String simpleType = getGenericType(paramType);
4085 if (isStructClass(simpleType)) {
4086 int methodNumId = intDecl.getMethodNumId(method);
4087 print("int " + newSkelClass + "::___");
4088 String helperMethod = methodNumId + "struct" + i;
4089 println(helperMethod + "(" + newSkelClass + "* skel) {");
4090 // Now, write the helper body of skeleton!
4091 writeMethodBytesCopy();
4092 println("string paramCls[] = { \"int\" };");
4093 println("int numParam = 1;");
4094 println("int param0 = 0;");
4095 println("void* paramObj[] = { ¶m0 };");
4096 println("rmiComm->getMethodParams(paramCls, numParam, paramObj, localMethodBytes);");
4097 println("return param0;");
4098 println("delete[] localMethodBytes;");
4107 * HELPER: writeMethodHelperStructSetupCplusCallbackSkeleton() writes the method helper of struct in skeleton class
4109 private void writeMethodHelperStructSetupCplusCallbackSkeleton(Collection<String> methods,
4110 InterfaceDecl intDecl) {
4112 // Use this set to handle two same methodIds
4113 for (String method : methods) {
4115 List<String> methParams = intDecl.getMethodParams(method);
4116 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4117 // Check for params with structs
4118 for (int i = 0; i < methParams.size(); i++) {
4119 String paramType = methPrmTypes.get(i);
4120 String param = methParams.get(i);
4121 String simpleType = getGenericType(paramType);
4122 if (isStructClass(simpleType)) {
4123 int methodNumId = intDecl.getMethodNumId(method);
4125 String helperMethod = methodNumId + "struct" + i;
4126 println(helperMethod + "(IoTRMIObject* rmiObj) {");
4127 // Now, write the helper body of skeleton!
4128 println("string paramCls[] = { \"int\" };");
4129 println("int numParam = 1;");
4130 println("int param0 = 0;");
4131 println("void* paramObj[] = { ¶m0 };");
4132 println("rmiComm->getMethodParams(paramCls, numParam, paramObj, localMethodBytes);");
4133 println("return param0;");
4142 * HELPER: writeCplusMethodPermission() writes permission checks in skeleton
4144 private void writeCplusMethodPermission(String intface) {
4146 // Get all the different stubs
4147 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
4148 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
4149 String newIntface = intMeth.getKey();
4150 int newObjectId = getNewIntfaceObjectId(newIntface);
4151 println("if (_objectId == objectId) {");
4152 println("if (set" + newObjectId + "Allowed.find(methodId) == set" + newObjectId + "Allowed.end()) {");
4153 println("cerr << \"Object with object Id: \" << _objectId << \" is not allowed to access method: \" << methodId << endl;");
4158 println("continue;");
4165 * HELPER: writeCplusWaitRequestInvokeMethod() writes the main loop of the skeleton class
4167 private void writeCplusWaitRequestInvokeMethod(Collection<String> methods, InterfaceDecl intDecl,
4168 boolean callbackExist, String intface, String newSkelClass) {
4170 // Use this set to handle two same methodIds
4171 Set<String> uniqueMethodIds = new HashSet<String>();
4172 println("void " + newSkelClass + "::___waitRequestInvokeMethod(" + newSkelClass + "* skel) {");
4173 // Write variables here if we have callbacks or enums or structs
4174 writeCountVarStructSkeleton(methods, intDecl);
4175 println("skel->didAlreadyInitWaitInvoke = true;");
4176 println("while (true) {");
4177 println("if (!methodReceived) {");
4178 println("continue;");
4180 println("skel->methodBytes = skel->rmiComm->getMethodBytes();");
4181 println("skel->methodLen = skel->rmiComm->getMethodLength();");
4182 println("methodReceived = false;");
4183 println("int _objectId = skel->rmiComm->getObjectId(skel->methodBytes);");
4184 println("int methodId = skel->rmiComm->getMethodId(skel->methodBytes);");
4185 // Generate permission check
4186 writeCplusMethodPermission(intface);
4187 println("switch (methodId) {");
4188 // Print methods and method Ids
4189 for (String method : methods) {
4190 String methodId = intDecl.getMethodId(method);
4191 int methodNumId = intDecl.getMethodNumId(method);
4192 println("case " + methodNumId + ": {");
4193 print("thread th" + methodNumId + " (&" + newSkelClass + "::___");
4194 String helperMethod = methodId;
4195 if (uniqueMethodIds.contains(methodId))
4196 helperMethod = helperMethod + methodNumId;
4198 uniqueMethodIds.add(methodId);
4199 print(helperMethod + ", std::ref(skel), ");
4200 boolean structExists = writeInputCountVarStructCplusSkeleton(method, intDecl);
4204 println("th" + methodNumId + ".detach(); break;");
4207 writeMethodCallStructCplusSkeleton(methods, intDecl);
4208 println("default: ");
4209 println("cerr << \"Method Id \" << methodId << \" not recognized!\" << endl;");
4218 * generateCplusSkeletonClassHpp() generate skeletons based on the methods list in C++ (.hpp file)
4220 public void generateCplusSkeletonClassHpp() throws IOException {
4222 // Create a new directory
4223 String path = createDirectories(dir, subdir);
4224 for (String intface : mapIntfacePTH.keySet()) {
4225 // Open a new file to write into
4226 String newSkelClass = intface + "_Skeleton";
4227 FileWriter fw = new FileWriter(path + "/" + newSkelClass + ".hpp");
4228 pw = new PrintWriter(new BufferedWriter(fw));
4229 // Write file headers
4230 println("#ifndef _" + newSkelClass.toUpperCase() + "_HPP__");
4231 println("#define _" + newSkelClass.toUpperCase() + "_HPP__");
4232 println("#include <iostream>");
4233 println("#include \"" + intface + ".hpp\"\n");
4234 // Pass in set of methods and get import classes
4235 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4236 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
4237 List<String> methods = intDecl.getMethods();
4238 List<String> stdIncludeClasses = getStandardCplusIncludeClasses();
4239 printIncludeStatements(stdIncludeClasses); println("");
4240 println("using namespace std;\n");
4241 // Find out if there are callback objects
4242 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
4243 boolean callbackExist = !callbackClasses.isEmpty();
4244 // Write class header
4245 println("class " + newSkelClass + " : public " + intface); println("{");
4246 println("private:\n");
4248 writePropertiesCplusSkeleton(intface, callbackExist, callbackClasses);
4249 println("public:\n");
4250 // Write constructors
4251 println(newSkelClass + "();");
4252 println(newSkelClass + "(" + intface + "*_mainObj, int _portSend, int _portRecv);");
4253 println(newSkelClass + "(" + intface + "*_mainObj, IoTRMIComm *rmiComm, int _objectId);");
4254 // Write deconstructor
4255 println("~" + newSkelClass + "();");
4256 // Write method declarations
4257 println("bool didInitWaitInvoke();");
4258 writeMethodDeclCplusSkeleton(methods, intDecl, callbackClasses);
4259 // Write method helper declarations
4260 writeMethodHelperDeclCplusSkeleton(methods, intDecl, newSkelClass);
4261 // Write waitRequestInvokeMethod() declaration - main loop
4262 println("void ___waitRequestInvokeMethod(" + newSkelClass + "* skel);");
4264 writePermissionInitializationCplus(intface, newSkelClass, intDecl);
4267 System.out.println("IoTCompiler: Generated skeleton class " + newSkelClass + ".hpp...");
4272 * HELPER: writeReturnDidAlreadyInitWaitInvoke() writes the function to return didAlreadyInitWaitInvoke
4274 private void writeReturnDidAlreadyInitWaitInvoke(String newSkelClass) {
4276 println("bool " + newSkelClass + "::didInitWaitInvoke() {");
4277 println("return didAlreadyInitWaitInvoke;");
4283 * writeSkelExternalCFunctions() generate external functions for .so file
4285 public void writeSkelExternalCFunctions(String newSkelClass, String intface) throws IOException {
4287 println("extern \"C\" void* create" + newSkelClass + "(void** params) {");
4288 println("// Args: *_mainObj, int _portSend, int _portRecv");
4289 println("return new " + newSkelClass + "((" + intface + "*) params[0], *((int*) params[1]), *((int*) params[2]));");
4291 println("extern \"C\" void destroy" + newSkelClass + "(void* t) {");
4292 println(newSkelClass + "* obj = (" + newSkelClass + "*) t;");
4293 println("delete obj;");
4295 println("extern \"C\" void init" + newSkelClass + "(void* t) {");
4296 //println(newSkelClass + "* obj = (" + newSkelClass + "*) t;");
4297 //println("obj->init();");
4298 //println("while(true);");
4304 * generateCplusSkeletonClassCpp() generate skeletons based on the methods list in C++ (.cpp file)
4306 public void generateCplusSkeletonClassCpp() throws IOException {
4308 // Create a new directory
4309 String path = createDirectories(dir, subdir);
4310 for (String intface : mapIntfacePTH.keySet()) {
4311 // Open a new file to write into
4312 String newSkelClass = intface + "_Skeleton";
4313 FileWriter fw = new FileWriter(path + "/" + newSkelClass + ".cpp");
4314 pw = new PrintWriter(new BufferedWriter(fw));
4315 // Write file headers
4316 println("#include <iostream>");
4317 println("#include \"" + newSkelClass + ".hpp\"\n");
4318 // Pass in set of methods and get import classes
4319 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4320 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
4321 List<String> methods = intDecl.getMethods();
4322 // Find out if there are callback objects
4323 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
4324 boolean callbackExist = !callbackClasses.isEmpty();
4325 for(String str: callbackClasses) {
4326 if (intface.equals(mainClass))
4327 println("#include \"" + getStubInterface(str) + "_Stub.cpp\"\n");
4329 println("#include \"" + getStubInterface(str) + "_Stub.hpp\"\n");
4331 println("using namespace std;\n");
4332 // Write constructor
4333 writeConstructorCplusSkeleton(newSkelClass, intface, callbackExist, intDecl, methods);
4334 // Write callback constructor
4335 writeCallbackConstructorCplusSkeleton(newSkelClass, intface, callbackExist, intDecl, methods);
4336 // Write deconstructor
4337 writeDeconstructorCplusSkeleton(newSkelClass, callbackExist, callbackClasses);
4338 // Write didInitWaitInvoke() to return bool
4339 writeReturnDidAlreadyInitWaitInvoke(newSkelClass);
4341 writeMethodCplusSkeleton(methods, intDecl, newSkelClass);
4342 // Write method helper
4343 writeMethodHelperCplusSkeleton(methods, intDecl, callbackClasses, newSkelClass);
4344 // Write waitRequestInvokeMethod() - main loop
4345 writeCplusWaitRequestInvokeMethod(methods, intDecl, callbackExist, intface, newSkelClass);
4346 // Write external functions for .so file
4347 writeSkelExternalCFunctions(newSkelClass, intface);
4348 // TODO: Remove this later
4349 if (intface.equals(mainClass)) {
4350 println("int main() {");
4351 println("return 0;");
4355 System.out.println("IoTCompiler: Generated skeleton class " + newSkelClass + ".cpp...");
4361 * generateInitializer() generate initializer based on type
4363 public String generateCplusInitializer(String type) {
4365 // Generate dummy returns for now
4366 if (type.equals("short")||
4367 type.equals("int") ||
4368 type.equals("long") ||
4369 type.equals("float")||
4370 type.equals("double")) {
4373 } else if ( type.equals("String") ||
4374 type.equals("string")) {
4377 } else if ( type.equals("char") ||
4378 type.equals("byte")) {
4381 } else if ( type.equals("boolean")) {
4391 * setDirectory() sets a new directory for stub files
4393 public void setDirectory(String _subdir) {
4400 * printUsage() prints the usage of this compiler
4402 public static void printUsage() {
4404 System.out.println();
4405 System.out.println("Sentinel interface and stub compiler version 1.0");
4406 System.out.println("Copyright (c) 2015-2016 University of California, Irvine - Programming Language Group.");
4407 System.out.println("All rights reserved.");
4408 System.out.println("Usage:");
4409 System.out.println("\tjava IoTCompiler -help / --help / -h\n");
4410 System.out.println("\t\tDisplay this help texts\n\n");
4411 System.out.println("\tjava IoTCompiler [<main-policy-file> <req-policy-file>]");
4412 System.out.println("\tjava IoTCompiler [<main-policy-file> <req-policy-file>] [options]\n");
4413 System.out.println("\t\tTake one or more pairs of main-req policy files, and generate Java and/or C++ files\n");
4414 System.out.println("Options:");
4415 System.out.println("\t-java\t<directory>\tGenerate Java stub files");
4416 System.out.println("\t-cplus\t<directory>\tGenerate C++ stub files");
4417 System.out.println();
4422 * parseFile() prepares Lexer and Parser objects, then parses the file
4424 public static ParseNode parseFile(String file) {
4426 ParseNode pn = null;
4428 ComplexSymbolFactory csf = new ComplexSymbolFactory();
4429 ScannerBuffer lexer =
4430 new ScannerBuffer(new Lexer(new BufferedReader(new FileReader(file)),csf));
4431 Parser parse = new Parser(lexer,csf);
4432 pn = (ParseNode) parse.parse().value;
4433 } catch (Exception e) {
4434 e.printStackTrace();
4435 throw new Error("IoTCompiler: ERROR parsing policy file or wrong command line option: " + file + "\n");
4443 * Basic helper functions
4446 boolean newline=true;
4449 private void print(String str) {
4452 if (str.equals("}"))
4454 for(int i=0; i<tab; i++)
4464 * This function converts Java to C++ type for compilation
4466 private String convertType(String type) {
4468 if (mapPrimitives.containsKey(type))
4469 return mapPrimitives.get(type);
4476 * A collection of methods with print-to-file functionality
4478 private void println(String str) {
4481 if (str.contains("}") && !str.contains("{"))
4483 for(int i=0; i<tab; i++)
4492 private void updatetabbing(String str) {
4494 tablevel+=count(str,'{')-count(str,'}');
4498 private int count(String str, char key) {
4499 char[] array = str.toCharArray();
4501 for(int i=0; i<array.length; i++) {
4502 if (array[i] == key)
4509 private void createDirectory(String dirName) {
4511 File file = new File(dirName);
4512 if (!file.exists()) {
4514 System.out.println("IoTCompiler: Directory " + dirName + " has been created!");
4516 System.out.println("IoTCompiler: Failed to create directory " + dirName + "!");
4519 System.out.println("IoTCompiler: Directory " + dirName + " exists...");
4524 // Create a directory and possibly a sub directory
4525 private String createDirectories(String dir, String subdir) {
4528 createDirectory(path);
4529 if (subdir != null) {
4530 path = path + "/" + subdir;
4531 createDirectory(path);
4537 // Inserting array members into a Map object
4538 // that maps arrKey to arrVal objects
4539 private void arraysToMap(Map map, Object[] arrKey, Object[] arrVal) {
4541 for(int i = 0; i < arrKey.length; i++) {
4543 map.put(arrKey[i], arrVal[i]);
4548 // Check and find object Id for new interface in mapNewIntfaceObjId (callbacks)
4549 // Throw an error if the new interface is not found!
4550 // Basically the compiler needs to parse the policy (and requires) files for callback class first
4551 private int getNewIntfaceObjectId(String newIntface) {
4553 // if (!mapNewIntfaceObjId.containsKey(newIntface)) {
4554 // throw new Error("IoTCompiler: Need to parse policy and requires files for callback class first! " +
4555 // "Please place the two files for callback class in front...\n");
4558 int retObjId = mapNewIntfaceObjId.get(newIntface);
4564 // Return parameter category, i.e. PRIMITIVES, NONPRIMITIVES, USERDEFINED, ENUM, or STRUCT
4565 private ParamCategory getParamCategory(String paramType) {
4567 if (mapPrimitives.containsKey(paramType)) {
4568 return ParamCategory.PRIMITIVES;
4569 // We can either use mapNonPrimitivesJava or mapNonPrimitivesCplus here
4570 } else if (mapNonPrimitivesJava.containsKey(getSimpleType(paramType))) {
4571 return ParamCategory.NONPRIMITIVES;
4572 } else if (isEnumClass(paramType)) {
4573 return ParamCategory.ENUM;
4574 } else if (isStructClass(paramType)) {
4575 return ParamCategory.STRUCT;
4577 return ParamCategory.USERDEFINED;
4581 // Return full class name for non-primitives to generate Java import statements
4582 // e.g. java.util.Set for Set
4583 private String getNonPrimitiveJavaClass(String paramNonPrimitives) {
4585 return mapNonPrimitivesJava.get(paramNonPrimitives);
4589 // Return full class name for non-primitives to generate Cplus include statements
4590 // e.g. #include <set> for Set
4591 private String getNonPrimitiveCplusClass(String paramNonPrimitives) {
4593 return mapNonPrimitivesCplus.get(paramNonPrimitives);
4597 // Get simple types, e.g. HashSet for HashSet<...>
4598 // Basically strip off the "<...>"
4599 private String getSimpleType(String paramType) {
4601 // Check if this is generics
4602 if(paramType.contains("<")) {
4603 String[] type = paramType.split("<");
4610 // Generate a set of standard classes for import statements
4611 private List<String> getStandardJavaIntfaceImportClasses() {
4613 List<String> importClasses = new ArrayList<String>();
4614 // Add the standard list first
4615 importClasses.add("java.util.List");
4616 importClasses.add("java.util.ArrayList");
4618 return importClasses;
4622 // Generate a set of standard classes for import statements
4623 private List<String> getStandardJavaImportClasses() {
4625 List<String> importClasses = new ArrayList<String>();
4626 // Add the standard list first
4627 importClasses.add("java.io.IOException");
4628 importClasses.add("java.util.List");
4629 importClasses.add("java.util.ArrayList");
4630 importClasses.add("java.util.Arrays");
4631 importClasses.add("java.util.Map");
4632 importClasses.add("java.util.HashMap");
4633 importClasses.add("java.util.concurrent.atomic.AtomicBoolean");
4634 importClasses.add("iotrmi.Java.IoTRMIComm");
4635 importClasses.add("iotrmi.Java.IoTRMICommClient");
4636 importClasses.add("iotrmi.Java.IoTRMICommServer");
4637 importClasses.add("iotrmi.Java.IoTRMIUtil");
4639 return importClasses;
4643 // Generate a set of standard classes for import statements
4644 private List<String> getStandardCplusIncludeClasses() {
4646 List<String> importClasses = new ArrayList<String>();
4647 // Add the standard list first
4648 importClasses.add("<vector>");
4649 importClasses.add("<set>");
4650 //importClasses.add("\"IoTRMICall.hpp\"");
4651 //importClasses.add("\"IoTRMIObject.hpp\"");
4652 importClasses.add("\"IoTRMIComm.hpp\"");
4653 importClasses.add("\"IoTRMICommClient.hpp\"");
4654 importClasses.add("\"IoTRMICommServer.hpp\"");
4656 return importClasses;
4660 // Combine all classes for import statements
4661 private List<String> getAllLibClasses(Collection<String> stdLibClasses, Collection<String> libClasses) {
4663 List<String> allLibClasses = new ArrayList<String>(stdLibClasses);
4664 // Iterate over the list of import classes
4665 for (String str : libClasses) {
4666 if (!allLibClasses.contains(str)) {
4667 allLibClasses.add(str);
4670 return allLibClasses;
4675 // Generate a set of classes for import statements
4676 private Set<String> getImportClasses(Collection<String> methods, InterfaceDecl intDecl) {
4678 Set<String> importClasses = new HashSet<String>();
4679 for (String method : methods) {
4680 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4681 for (String paramType : methPrmTypes) {
4683 String simpleType = getSimpleType(paramType);
4684 if (getParamCategory(simpleType) == ParamCategory.NONPRIMITIVES) {
4685 importClasses.add(getNonPrimitiveJavaClass(simpleType));
4689 return importClasses;
4693 // Handle and return the correct enum declaration
4694 // In Java, if we declare enum in Camera interface, then it becomes "Camera.<enum>"
4695 private String getEnumParamDecl(String type, InterfaceDecl intDecl) {
4697 // Strips off array "[]" for return type
4698 String pureType = getSimpleArrayType(type);
4699 // Take the inner type of generic
4700 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
4701 pureType = getTypeOfGeneric(type)[0];
4702 if (isEnumClass(pureType)) {
4703 String enumType = intDecl.getInterface() + "." + type;
4710 // Handle and return the correct type
4711 private String getEnumParam(String type, String param, int i) {
4713 // Strips off array "[]" for return type
4714 String pureType = getSimpleArrayType(type);
4715 // Take the inner type of generic
4716 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
4717 pureType = getTypeOfGeneric(type)[0];
4718 if (isEnumClass(pureType)) {
4719 String enumParam = "paramEnum" + i;
4726 // Handle and return the correct enum declaration translate into int[]
4727 private String getEnumType(String type) {
4729 // Strips off array "[]" for return type
4730 String pureType = getSimpleArrayType(type);
4731 // Take the inner type of generic
4732 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
4733 pureType = getGenericType(type);
4734 if (isEnumClass(pureType)) {
4735 String enumType = "int[]";
4741 // Handle and return the correct enum declaration translate into int* for C
4742 private String getEnumCplusClsType(String type) {
4744 // Strips off array "[]" for return type
4745 String pureType = getSimpleArrayType(type);
4746 // Take the inner type of generic
4747 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
4748 pureType = getGenericType(type);
4749 if (isEnumClass(pureType)) {
4750 String enumType = "int*";
4757 // Handle and return the correct struct declaration
4758 private String getStructType(String type) {
4760 // Strips off array "[]" for return type
4761 String pureType = getSimpleArrayType(type);
4762 // Take the inner type of generic
4763 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
4764 pureType = getGenericType(type);
4765 if (isStructClass(pureType)) {
4766 String structType = "int";
4773 // Check if this an enum declaration
4774 private boolean isEnumClass(String type) {
4776 // Just iterate over the set of interfaces
4777 for (String intface : mapIntfacePTH.keySet()) {
4778 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4779 EnumDecl enumDecl = (EnumDecl) decHandler.getEnumDecl(intface);
4780 Set<String> setEnumDecl = enumDecl.getEnumDeclarations();
4781 if (setEnumDecl.contains(type))
4788 // Check if this an struct declaration
4789 private boolean isStructClass(String type) {
4791 // Just iterate over the set of interfaces
4792 for (String intface : mapIntfacePTH.keySet()) {
4793 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4794 StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
4795 List<String> listStructDecl = structDecl.getStructTypes();
4796 if (listStructDecl.contains(type))
4803 // Return a struct declaration
4804 private StructDecl getStructDecl(String type) {
4806 // Just iterate over the set of interfaces
4807 for (String intface : mapIntfacePTH.keySet()) {
4808 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4809 StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
4810 List<String> listStructDecl = structDecl.getStructTypes();
4811 if (listStructDecl.contains(type))
4818 // Return number of members (-1 if not found)
4819 private int getNumOfMembers(String type) {
4821 // Just iterate over the set of interfaces
4822 for (String intface : mapIntfacePTH.keySet()) {
4823 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4824 StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
4825 List<String> listStructDecl = structDecl.getStructTypes();
4826 if (listStructDecl.contains(type))
4827 return structDecl.getNumOfMembers(type);
4833 // Generate a set of classes for include statements
4834 private Set<String> getIncludeClasses(Collection<String> methods, InterfaceDecl intDecl, String intface, boolean needExchange) {
4836 Set<String> includeClasses = new HashSet<String>();
4837 for (String method : methods) {
4839 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4840 List<String> methParams = intDecl.getMethodParams(method);
4841 for (int i = 0; i < methPrmTypes.size(); i++) {
4843 String genericType = getGenericType(methPrmTypes.get(i));
4844 String simpleType = getSimpleType(methPrmTypes.get(i));
4845 String param = methParams.get(i);
4846 if (getParamCategory(simpleType) == ParamCategory.NONPRIMITIVES) {
4847 includeClasses.add("<" + getNonPrimitiveCplusClass(simpleType) + ">");
4848 //} else if (getParamCategory(simpleType) == ParamCategory.USERDEFINED) {
4850 if (getParamCategory(getSimpleArrayType(genericType)) == ParamCategory.USERDEFINED) {
4851 // For original interface, we need it exchanged... not for stub interfaces
4853 //includeClasses.add("\"" + exchangeParamType(simpleType) + ".hpp\"");
4854 includeClasses.add("\"" + exchangeParamType(getSimpleArrayType(genericType)) + ".hpp\"");
4856 //includeClasses.add("\"" + simpleType + ".hpp\"");
4857 includeClasses.add("\"" + getSimpleArrayType(genericType) + ".hpp\"");
4860 if (getParamCategory(getSimpleArrayType(genericType)) == ParamCategory.ENUM) {
4861 includeClasses.add("\"" + genericType + ".hpp\"");
4863 if (getParamCategory(getSimpleArrayType(genericType)) == ParamCategory.STRUCT) {
4864 includeClasses.add("\"" + genericType + ".hpp\"");
4866 if (param.contains("[]")) {
4867 // Check if this is array for C++; translate into vector
4868 includeClasses.add("<vector>");
4872 return includeClasses;
4876 // Generate a set of callback classes
4877 private Set<String> getCallbackClasses(Collection<String> methods, InterfaceDecl intDecl) {
4879 Set<String> callbackClasses = new HashSet<String>();
4880 for (String method : methods) {
4882 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4883 List<String> methParams = intDecl.getMethodParams(method);
4884 for (int i = 0; i < methPrmTypes.size(); i++) {
4886 String type = methPrmTypes.get(i);
4887 if (getParamCategory(type) == ParamCategory.USERDEFINED) {
4888 callbackClasses.add(type);
4889 } else if (getParamCategory(type) == ParamCategory.NONPRIMITIVES) {
4890 // Can be a List<...> of callback objects ...
4891 String genericType = getTypeOfGeneric(type)[0];
4892 if (getParamCategory(type) == ParamCategory.USERDEFINED) {
4893 callbackClasses.add(type);
4898 return callbackClasses;
4902 // Print import statements into file
4903 private void printImportStatements(Collection<String> importClasses) {
4905 for(String cls : importClasses) {
4906 println("import " + cls + ";");
4911 // Print include statements into file
4912 private void printIncludeStatements(Collection<String> includeClasses) {
4914 for(String cls : includeClasses) {
4915 println("#include " + cls);
4920 // Get the C++ version of a non-primitive type
4921 // e.g. set for Set and map for Map
4922 // Input nonPrimitiveType has to be generics in format
4923 private String[] getTypeOfGeneric(String nonPrimitiveType) {
4925 // Handle <, >, and , for 2-type generic/template
4926 String[] substr = nonPrimitiveType.split("<")[1].split(">")[0].split(",");
4931 // Gets generic type inside "<" and ">"
4932 private String getGenericType(String type) {
4934 // Handle <, >, and , for 2-type generic/template
4935 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES) {
4936 String[] substr = type.split("<")[1].split(">")[0].split(",");
4943 // This helper function strips off array declaration, e.g. int[] becomes int
4944 private String getSimpleArrayType(String type) {
4946 // Handle [ for array declaration
4947 String substr = type;
4948 if (type.contains("[]")) {
4949 substr = type.split("\\[\\]")[0];
4955 // This helper function strips off array declaration, e.g. D[] becomes D
4956 private String getSimpleIdentifier(String ident) {
4958 // Handle [ for array declaration
4959 String substr = ident;
4960 if (ident.contains("[]")) {
4961 substr = ident.split("\\[\\]")[0];
4967 // Checks and gets type in C++
4968 private String checkAndGetCplusType(String paramType) {
4970 if (getParamCategory(paramType) == ParamCategory.PRIMITIVES) {
4971 return convertType(paramType);
4972 } else if (getParamCategory(paramType) == ParamCategory.NONPRIMITIVES) {
4974 // Check for generic/template format
4975 if (paramType.contains("<") && paramType.contains(">")) {
4977 String genericClass = getSimpleType(paramType);
4978 String genericType = getGenericType(paramType);
4979 String cplusTemplate = null;
4980 cplusTemplate = getNonPrimitiveCplusClass(genericClass);
4981 if(getParamCategory(getGenericType(paramType)) == ParamCategory.USERDEFINED) {
4982 cplusTemplate = cplusTemplate + "<" + genericType + "*>";
4984 cplusTemplate = cplusTemplate + "<" + convertType(genericType) + ">";
4986 return cplusTemplate;
4988 return getNonPrimitiveCplusClass(paramType);
4989 } else if(paramType.contains("[]")) { // Array type (used for return type only)
4990 String cArray = "vector<" + convertType(getSimpleArrayType(paramType)) + ">";
4992 } else if(getParamCategory(paramType) == ParamCategory.USERDEFINED) {
4993 return paramType + "*";
4995 // Just return it as is if it's not non-primitives
5000 // Detect array declaration, e.g. int A[],
5001 // then generate "int A[]" in C++ as "vector<int> A"
5002 private String checkAndGetCplusArray(String paramType, String param) {
5004 String paramComplete = null;
5005 // Check for array declaration
5006 if (param.contains("[]")) {
5007 paramComplete = "vector<" + paramType + "> " + param.replace("[]","");
5009 // Just return it as is if it's not an array
5010 paramComplete = paramType + " " + param;
5012 return paramComplete;
5016 // Detect array declaration, e.g. int A[],
5017 // then generate "int A[]" in C++ as "vector<int> A"
5018 // This method just returns the type
5019 private String checkAndGetCplusArrayType(String paramType) {
5021 String paramTypeRet = null;
5022 // Check for array declaration
5023 if (paramType.contains("[]")) {
5024 String type = paramType.split("\\[\\]")[0];
5025 paramTypeRet = checkAndGetCplusType(type) + "[]";
5026 } else if (paramType.contains("vector")) {
5027 // Just return it as is if it's not an array
5028 String type = paramType.split("<")[1].split(">")[0];
5029 paramTypeRet = checkAndGetCplusType(type) + "[]";
5031 paramTypeRet = paramType;
5033 return paramTypeRet;
5037 // Detect array declaration, e.g. int A[],
5038 // then generate "int A[]" in C++ as "vector<int> A"
5039 // This method just returns the type
5040 private String checkAndGetCplusArrayType(String paramType, String param) {
5042 String paramTypeRet = null;
5043 // Check for array declaration
5044 if (param.contains("[]")) {
5045 paramTypeRet = checkAndGetCplusType(paramType) + "[]";
5046 } else if (paramType.contains("vector")) {
5047 // Just return it as is if it's not an array
5048 String type = paramType.split("<")[1].split(">")[0];
5049 paramTypeRet = checkAndGetCplusType(type) + "[]";
5051 paramTypeRet = paramType;
5053 return paramTypeRet;
5057 // Return the class type for class resolution (for return value)
5058 // - Check and return C++ array class, e.g. int A[] into int*
5059 // - Check and return C++ vector class, e.g. List<Integer> A into vector<int>
5060 private String checkAndGetCplusRetClsType(String paramType) {
5062 String paramTypeRet = null;
5063 // Check for array declaration
5064 if (paramType.contains("[]")) {
5065 String type = paramType.split("\\[\\]")[0];
5066 paramTypeRet = getSimpleArrayType(type) + "*";
5067 } else if (paramType.contains("<") && paramType.contains(">")) {
5068 // Just return it as is if it's not an array
5069 String type = paramType.split("<")[1].split(">")[0];
5070 paramTypeRet = "vector<" + getGenericType(type) + ">";
5072 paramTypeRet = paramType;
5074 return paramTypeRet;
5078 // Return the class type for class resolution (for method arguments)
5079 // - Check and return C++ array class, e.g. int A[] into int*
5080 // - Check and return C++ vector class, e.g. List<Integer> A into vector<int>
5081 private String checkAndGetCplusArgClsType(String paramType, String param) {
5083 String paramTypeRet = getEnumCplusClsType(paramType);
5084 if (!paramTypeRet.equals(paramType))
5085 // Just return if it is an enum type
5086 // Type will still be the same if it's not an enum type
5087 return paramTypeRet;
5089 // Check for array declaration
5090 if (param.contains("[]")) {
5091 paramTypeRet = getSimpleArrayType(paramType) + "*";
5092 } else if (paramType.contains("<") && paramType.contains(">")) {
5093 // Just return it as is if it's not an array
5094 String type = paramType.split("<")[1].split(">")[0];
5095 paramTypeRet = "vector<" + getGenericType(type) + ">";
5097 paramTypeRet = paramType;
5099 return paramTypeRet;
5103 // Detect array declaration, e.g. int A[],
5104 // then generate type "int[]"
5105 private String checkAndGetArray(String paramType, String param) {
5107 String paramTypeRet = null;
5108 // Check for array declaration
5109 if (param.contains("[]")) {
5110 paramTypeRet = paramType + "[]";
5112 // Just return it as is if it's not an array
5113 paramTypeRet = paramType;
5115 return paramTypeRet;
5119 // Is array or list?
5120 private boolean isArrayOrList(String paramType, String param) {
5122 // Check for array declaration
5125 else if (isList(paramType))
5133 // For return type we use retType as input parameter
5134 private boolean isArray(String param) {
5136 // Check for array declaration
5137 if (param.contains("[]"))
5145 private boolean isList(String paramType) {
5147 // Check for array declaration
5148 if (paramType.contains("List"))
5155 // Get the right type for a callback object
5156 private String checkAndGetParamClass(String paramType) {
5158 // Check if this is generics
5159 if(getParamCategory(paramType) == ParamCategory.USERDEFINED) {
5160 return exchangeParamType(paramType);
5161 } else if (isList(paramType) &&
5162 (getParamCategory(getGenericType(paramType)) == ParamCategory.USERDEFINED)) {
5163 return "List<" + exchangeParamType(getGenericType(paramType)) + ">";
5169 // Returns the other interface for type-checking purposes for USERDEFINED
5170 // classes based on the information provided in multiple policy files
5171 // e.g. return CameraWithXXX instead of Camera
5172 private String exchangeParamType(String intface) {
5174 // Param type that's passed is the interface name we need to look for
5175 // in the map of interfaces, based on available policy files.
5176 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
5177 if (decHandler != null) {
5178 // We've found the required interface policy files
5179 RequiresDecl reqDecl = (RequiresDecl) decHandler.getRequiresDecl(intface);
5180 Set<String> setExchInt = reqDecl.getInterfaces();
5181 if (setExchInt.size() == 1) {
5182 Iterator iter = setExchInt.iterator();
5183 return (String) iter.next();
5185 throw new Error("IoTCompiler: Ambiguous stub interfaces: " + setExchInt.toString() +
5186 ". Only one new interface can be declared if the object " + intface +
5187 " needs to be passed in as an input parameter!\n");
5190 // NULL value - this means policy files missing
5191 throw new Error("IoTCompiler: Parameter type lookup failed for " + intface +
5192 "... Please provide the necessary policy files for user-defined types." +
5193 " If this is an array please type the brackets after the variable name," +
5194 " e.g. \"String str[]\", not \"String[] str\"." +
5195 " If this is a Collections (Java) / STL (C++) type, this compiler only" +
5196 " supports List/ArrayList (Java) or list (C++).\n");
5201 public static void main(String[] args) throws Exception {
5203 // If there is no argument or just "--help" or "-h", then invoke printUsage()
5204 if ((args[0].equals("-help") ||
5205 args[0].equals("--help")||
5206 args[0].equals("-h")) ||
5207 (args.length == 0)) {
5209 IoTCompiler.printUsage();
5211 } else if (args.length > 1) {
5213 IoTCompiler comp = new IoTCompiler();
5216 // Parse main policy file
5217 ParseNode pnPol = IoTCompiler.parseFile(args[i]);
5218 // Parse "requires" policy file
5219 ParseNode pnReq = IoTCompiler.parseFile(args[i+1]);
5220 // Get interface name
5221 String intface = ParseTreeHandler.getOrigIntface(pnPol);
5222 comp.setDataStructures(intface, pnPol, pnReq);
5223 comp.getMethodsForIntface(intface);
5225 // 1) Check if this is the last option before "-java" or "-cplus"
5226 // 2) Check if this is really the last option (no "-java" or "-cplus")
5227 } while(!args[i].equals("-java") &&
5228 !args[i].equals("-cplus") &&
5231 // Generate everything if we don't see "-java" or "-cplus"
5232 if (i == args.length) {
5233 comp.generateEnumJava();
5234 comp.generateStructJava();
5235 comp.generateJavaLocalInterfaces();
5236 comp.generateJavaInterfaces();
5237 comp.generateJavaStubClasses();
5238 comp.generateJavaSkeletonClass();
5239 comp.generateEnumCplus();
5240 comp.generateStructCplus();
5241 comp.generateCplusLocalInterfaces();
5242 comp.generateCPlusInterfaces();
5243 comp.generateCPlusStubClassesHpp();
5244 comp.generateCPlusStubClassesCpp();
5245 comp.generateCplusSkeletonClassHpp();
5246 comp.generateCplusSkeletonClassCpp();
5248 // Check other options
5249 while(i < args.length) {
5251 if (!args[i].equals("-java") &&
5252 !args[i].equals("-cplus")) {
5253 throw new Error("IoTCompiler: ERROR - unrecognized command line option: " + args[i] + "\n");
5255 if (i + 1 < args.length) {
5256 comp.setDirectory(args[i+1]);
5258 throw new Error("IoTCompiler: ERROR - please provide <directory> after option: " + args[i] + "\n");
5260 if (args[i].equals("-java")) {
5261 comp.generateEnumJava();
5262 comp.generateStructJava();
5263 comp.generateJavaLocalInterfaces();
5264 comp.generateJavaInterfaces();
5265 comp.generateJavaStubClasses();
5266 comp.generateJavaSkeletonClass();
5268 comp.generateEnumCplus();
5269 comp.generateStructCplus();
5270 comp.generateCplusLocalInterfaces();
5271 comp.generateCPlusInterfaces();
5272 comp.generateCPlusStubClassesHpp();
5273 comp.generateCPlusStubClassesCpp();
5274 comp.generateCplusSkeletonClassHpp();
5275 comp.generateCplusSkeletonClassCpp();
5282 // Need to at least have exactly 2 parameters, i.e. main policy file and requires file
5283 IoTCompiler.printUsage();
5284 throw new Error("IoTCompiler: At least two arguments (main and requires policy files) have to be provided!\n");