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 String mainClass;
70 private final static String OUTPUT_DIRECTORY = "output_files";
72 private enum ParamCategory {
74 PRIMITIVES, // All the primitive types, e.g. byte, short, int, long, etc.
75 NONPRIMITIVES, // Non-primitive types, e.g. Set, Map, List, etc.
77 STRUCT, // Struct type
78 USERDEFINED // Assumed as driver classes
85 public IoTCompiler() {
87 mapIntfacePTH = new HashMap<String,ParseTreeHandler>();
88 mapIntDeclHand = new HashMap<String,DeclarationHandler>();
89 mapInt2NewInts = new HashMap<String,Map<String,Set<String>>>();
90 mapInt2NewIntName = new HashMap<String,String>();
91 mapIntfaceObjId = new HashMap<String,Integer>();
92 mapNewIntfaceObjId = new HashMap<String,Integer>();
93 mapPrimitives = new HashMap<String,String>();
94 arraysToMap(mapPrimitives, IoTRMITypes.primitivesJava, IoTRMITypes.primitivesCplus);
95 mapNonPrimitivesJava = new HashMap<String,String>();
96 arraysToMap(mapNonPrimitivesJava, IoTRMITypes.nonPrimitivesJava, IoTRMITypes.nonPrimitiveJavaLibs);
97 mapNonPrimitivesCplus = new HashMap<String,String>();
98 arraysToMap(mapNonPrimitivesCplus, IoTRMITypes.nonPrimitivesJava, IoTRMITypes.nonPrimitivesCplus);
99 mapPortCount = new HashMap<String,Integer>();
101 dir = OUTPUT_DIRECTORY;
108 * setDataStructures() sets parse tree and other data structures based on policy files.
110 * It also generates parse tree (ParseTreeHandler) and
111 * copies useful information from parse tree into
112 * InterfaceDecl, CapabilityDecl, and RequiresDecl
114 * Additionally, the data structure handles are
115 * returned from tree-parsing for further process.
117 public void setDataStructures(String origInt, ParseNode pnPol, ParseNode pnReq) {
119 ParseTreeHandler ptHandler = new ParseTreeHandler(origInt, pnPol, pnReq);
120 DeclarationHandler decHandler = new DeclarationHandler();
121 // Process ParseNode and generate Declaration objects
123 ptHandler.processInterfaceDecl();
124 InterfaceDecl intDecl = ptHandler.getInterfaceDecl();
125 decHandler.addInterfaceDecl(origInt, intDecl);
127 ptHandler.processCapabilityDecl();
128 CapabilityDecl capDecl = ptHandler.getCapabilityDecl();
129 decHandler.addCapabilityDecl(origInt, capDecl);
131 ptHandler.processRequiresDecl();
132 RequiresDecl reqDecl = ptHandler.getRequiresDecl();
133 decHandler.addRequiresDecl(origInt, reqDecl);
135 ptHandler.processEnumDecl();
136 EnumDecl enumDecl = ptHandler.getEnumDecl();
137 decHandler.addEnumDecl(origInt, enumDecl);
139 ptHandler.processStructDecl();
140 StructDecl structDecl = ptHandler.getStructDecl();
141 decHandler.addStructDecl(origInt, structDecl);
143 mapIntfacePTH.put(origInt, ptHandler);
144 mapIntDeclHand.put(origInt, decHandler);
145 // Set object Id counter to 0 for each interface
146 mapIntfaceObjId.put(origInt, new Integer(0));
151 * getMethodsForIntface() reads for methods in the data structure
153 * It is going to give list of methods for a certain interface
154 * based on the declaration of capabilities.
156 public void getMethodsForIntface(String origInt) {
158 ParseTreeHandler ptHandler = mapIntfacePTH.get(origInt);
159 Map<String,Set<String>> mapNewIntMethods = new HashMap<String,Set<String>>();
160 // Get set of new interfaces, e.g. CameraWithCaptureAndData
161 // Generate this new interface with all the methods it needs
162 // from different capabilities it declares
163 DeclarationHandler decHandler = mapIntDeclHand.get(origInt);
164 RequiresDecl reqDecl = (RequiresDecl) decHandler.getRequiresDecl(origInt);
165 Set<String> setIntfaces = reqDecl.getInterfaces();
166 for (String strInt : setIntfaces) {
168 // Initialize a set of methods
169 Set<String> setMethods = new HashSet<String>();
170 // Get list of capabilities, e.g. ImageCapture, VideoRecording, etc.
171 List<String> listCapab = reqDecl.getCapabList(strInt);
172 for (String strCap : listCapab) {
174 // Get list of methods for each capability
175 CapabilityDecl capDecl = (CapabilityDecl) decHandler.getCapabilityDecl(origInt);
176 List<String> listCapabMeth = capDecl.getMethods(strCap);
177 for (String strMeth : listCapabMeth) {
179 // Add methods into setMethods
180 // This is to also handle redundancies (say two capabilities
181 // share the same methods)
182 setMethods.add(strMeth);
185 // Add interface and methods information into map
186 mapNewIntMethods.put(strInt, setMethods);
187 // Map new interface method name to the original interface
188 // TODO: perhaps need to check in the future if we have more than 1 stub interface for one original interface
189 mapInt2NewIntName.put(origInt, strInt);
190 if (mainClass == null) // Take the first class as the main class (whichever is placed first in the order of compilation files)
193 // Map the map of interface-methods to the original interface
194 mapInt2NewInts.put(origInt, mapNewIntMethods);
203 * HELPER: writeMethodJavaLocalInterface() writes the method of the local interface
205 private void writeMethodJavaLocalInterface(Collection<String> methods, InterfaceDecl intDecl) {
207 for (String method : methods) {
209 List<String> methParams = intDecl.getMethodParams(method);
210 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
211 print("public " + intDecl.getMethodType(method) + " " +
212 intDecl.getMethodId(method) + "(");
213 for (int i = 0; i < methParams.size(); i++) {
214 // Check for params with driver class types and exchange it
215 // with its remote interface
216 String paramType = checkAndGetParamClass(methPrmTypes.get(i));
217 print(paramType + " " + methParams.get(i));
218 // Check if this is the last element (don't print a comma)
219 if (i != methParams.size() - 1) {
229 * HELPER: writeMethodJavaInterface() writes the method of the interface
231 private void writeMethodJavaInterface(Collection<String> methods, InterfaceDecl intDecl) {
233 for (String method : methods) {
235 List<String> methParams = intDecl.getMethodParams(method);
236 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
237 print("public " + intDecl.getMethodType(method) + " " +
238 intDecl.getMethodId(method) + "(");
239 for (int i = 0; i < methParams.size(); i++) {
240 // Check for params with driver class types and exchange it
241 // with its remote interface
242 String paramType = methPrmTypes.get(i);
243 print(paramType + " " + methParams.get(i));
244 // Check if this is the last element (don't print a comma)
245 if (i != methParams.size() - 1) {
255 * HELPER: generateEnumJava() writes the enumeration declaration
257 private void generateEnumJava() throws IOException {
259 // Create a new directory
260 createDirectory(dir);
261 for (String intface : mapIntfacePTH.keySet()) {
262 // Get the right EnumDecl
263 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
264 EnumDecl enumDecl = (EnumDecl) decHandler.getEnumDecl(intface);
265 Set<String> enumTypes = enumDecl.getEnumDeclarations();
266 // Iterate over enum declarations
267 for (String enType : enumTypes) {
268 // Open a new file to write into
269 FileWriter fw = new FileWriter(dir + "/" + enType + ".java");
270 pw = new PrintWriter(new BufferedWriter(fw));
271 println("public enum " + enType + " {");
272 List<String> enumMembers = enumDecl.getMembers(enType);
273 for (int i = 0; i < enumMembers.size(); i++) {
275 String member = enumMembers.get(i);
277 // Check if this is the last element (don't print a comma)
278 if (i != enumMembers.size() - 1)
285 System.out.println("IoTCompiler: Generated enum class " + enType + ".java...");
292 * HELPER: generateStructJava() writes the struct declaration
294 private void generateStructJava() throws IOException {
296 // Create a new directory
297 createDirectory(dir);
298 for (String intface : mapIntfacePTH.keySet()) {
299 // Get the right StructDecl
300 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
301 StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
302 List<String> structTypes = structDecl.getStructTypes();
303 // Iterate over enum declarations
304 for (String stType : structTypes) {
305 // Open a new file to write into
306 FileWriter fw = new FileWriter(dir + "/" + stType + ".java");
307 pw = new PrintWriter(new BufferedWriter(fw));
308 println("public class " + stType + " {");
309 List<String> structMemberTypes = structDecl.getMemberTypes(stType);
310 List<String> structMembers = structDecl.getMembers(stType);
311 for (int i = 0; i < structMembers.size(); i++) {
313 String memberType = structMemberTypes.get(i);
314 String member = structMembers.get(i);
315 println("public static " + memberType + " " + member + ";");
319 System.out.println("IoTCompiler: Generated struct class " + stType + ".java...");
326 * generateJavaLocalInterface() writes the local interface and provides type-checking.
328 * It needs to rewrite and exchange USERDEFINED types in input parameters of stub
329 * and original interfaces, e.g. exchange Camera and CameraWithVideoAndRecording.
330 * The local interface has to be the input parameter for the stub and the stub
331 * interface has to be the input parameter for the local class.
333 public void generateJavaLocalInterfaces() throws IOException {
335 // Create a new directory
336 createDirectory(dir);
337 for (String intface : mapIntfacePTH.keySet()) {
338 // Open a new file to write into
339 FileWriter fw = new FileWriter(dir + "/" + intface + ".java");
340 pw = new PrintWriter(new BufferedWriter(fw));
341 // Pass in set of methods and get import classes
342 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
343 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
344 List<String> methods = intDecl.getMethods();
345 Set<String> importClasses = getImportClasses(methods, intDecl);
346 List<String> stdImportClasses = getStandardJavaIntfaceImportClasses();
347 List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
348 printImportStatements(allImportClasses);
349 // Write interface header
351 println("public interface " + intface + " {");
353 writeMethodJavaLocalInterface(methods, intDecl);
356 System.out.println("IoTCompiler: Generated local interface " + intface + ".java...");
362 * HELPER: updateIntfaceObjIdMap() updates the mapping between new interface and object Id
364 private void updateIntfaceObjIdMap(String intface, String newIntface) {
366 Integer objId = mapIntfaceObjId.get(intface);
367 mapNewIntfaceObjId.put(newIntface, objId);
368 mapIntfaceObjId.put(intface, objId++);
373 * generateJavaInterfaces() generate stub interfaces based on the methods list in Java
375 public void generateJavaInterfaces() throws IOException {
377 // Create a new directory
378 String path = createDirectories(dir, subdir);
379 for (String intface : mapIntfacePTH.keySet()) {
381 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
382 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
384 // Open a new file to write into
385 String newIntface = intMeth.getKey();
386 FileWriter fw = new FileWriter(path + "/" + newIntface + ".java");
387 pw = new PrintWriter(new BufferedWriter(fw));
388 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
389 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
390 // Pass in set of methods and get import classes
391 Set<String> methods = intMeth.getValue();
392 Set<String> importClasses = getImportClasses(methods, intDecl);
393 List<String> stdImportClasses = getStandardJavaIntfaceImportClasses();
394 List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
395 printImportStatements(allImportClasses);
396 // Write interface header
398 println("public interface " + newIntface + " {\n");
399 updateIntfaceObjIdMap(intface, newIntface);
401 writeMethodJavaInterface(methods, intDecl);
404 System.out.println("IoTCompiler: Generated interface " + newIntface + ".java...");
411 * HELPER: writePropertiesJavaPermission() writes the permission in properties
413 private void writePropertiesJavaPermission(String intface, InterfaceDecl intDecl) {
415 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
416 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
417 String newIntface = intMeth.getKey();
418 int newObjectId = getNewIntfaceObjectId(newIntface);
419 println("private final static int object" + newObjectId + "Id = " +
420 newObjectId + ";\t//" + newIntface);
421 Set<String> methodIds = intMeth.getValue();
422 print("private static Integer[] object" + newObjectId + "Permission = { ");
424 for (String methodId : methodIds) {
425 int methodNumId = intDecl.getMethodNumId(methodId);
426 print(Integer.toString(methodNumId));
427 // Check if this is the last element (don't print a comma)
428 if (i != methodIds.size() - 1) {
434 println("private static List<Integer> set" + newObjectId + "Allowed;");
440 * HELPER: writePropertiesJavaStub() writes the properties of the stub class
442 private void writePropertiesJavaStub(String intface, Set<String> methods, InterfaceDecl intDecl) {
445 Integer objId = mapIntfaceObjId.get(intface);
446 println("private int objectId = " + objId + ";");
447 println("private IoTRMIComm rmiComm;");
448 // Write the list of AtomicBoolean variables
449 println("// Synchronization variables");
450 for (String method : methods) {
451 // Generate AtomicBooleans for methods that have return values
452 String returnType = intDecl.getMethodType(method);
453 int methodNumId = intDecl.getMethodNumId(method);
454 if (!returnType.equals("void")) {
455 println("private AtomicBoolean retValueReceived" + methodNumId + " = new AtomicBoolean(false);");
463 * HELPER: writeConstructorJavaPermission() writes the permission in constructor
465 private void writeConstructorJavaPermission(String intface) {
467 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
468 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
469 String newIntface = intMeth.getKey();
470 int newObjectId = getNewIntfaceObjectId(newIntface);
471 println("set" + newObjectId + "Allowed = new ArrayList<Integer>(Arrays.asList(object" + newObjectId +"Permission));");
477 * HELPER: writeConstructorJavaStub() writes the constructor of the stub class
479 private void writeConstructorJavaStub(String intface, String newStubClass, Set<String> methods, InterfaceDecl intDecl) {
481 println("public " + newStubClass + "(int _localPortSend, int _localPortRecv, int _portSend, int _portRecv, String _skeletonAddress, int _rev) throws Exception {");
482 println("if (_localPortSend != 0 && _localPortRecv != 0) {");
483 println("rmiComm = new IoTRMICommClient(_localPortSend, _localPortRecv, _portSend, _portRecv, _skeletonAddress, _rev);");
486 println("rmiComm = new IoTRMICommClient(_portSend, _portRecv, _skeletonAddress, _rev);");
488 // Register the AtomicBoolean variables
489 for (String method : methods) {
490 // Generate AtomicBooleans for methods that have return values
491 String returnType = intDecl.getMethodType(method);
492 int methodNumId = intDecl.getMethodNumId(method);
493 if (!returnType.equals("void")) {
494 println("rmiComm.registerStub(objectId, " + methodNumId + ", retValueReceived" + methodNumId + ");");
497 println("IoTRMIUtil.mapStub.put(objectId, this);");
503 * HELPER: writeCallbackConstructorJavaStub() writes the callback constructor of the stub class
505 private void writeCallbackConstructorJavaStub(String intface, String newStubClass, Set<String> methods, InterfaceDecl intDecl) {
507 println("public " + newStubClass + "(IoTRMIComm _rmiComm, int _objectId) throws Exception {");
508 println("rmiComm = _rmiComm;");
509 println("objectId = _objectId;");
510 // Register the AtomicBoolean variables
511 for (String method : methods) {
512 // Generate AtomicBooleans for methods that have return values
513 String returnType = intDecl.getMethodType(method);
514 int methodNumId = intDecl.getMethodNumId(method);
515 if (!returnType.equals("void")) {
516 println("rmiComm.registerStub(objectId, " + methodNumId + ", retValueReceived" + methodNumId + ");");
524 * HELPER: writeJavaMethodCallbackPermission() writes permission checks in stub for callbacks
526 private void writeJavaMethodCallbackPermission(String intface) {
528 println("int methodId = IoTRMIObject.getMethodId(method);");
529 // Get all the different stubs
530 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
531 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
532 String newIntface = intMeth.getKey();
533 int newObjectId = getNewIntfaceObjectId(newIntface);
534 println("if (!set" + newObjectId + "Allowed.contains(methodId)) {");
535 println("throw new Error(\"Callback object for " + intface + " is not allowed to access method: \" + methodId);");
542 * HELPER: writeJavaInitCallbackPermission() writes the permission for callback
544 private void writeJavaInitCallbackPermission(String intface, InterfaceDecl intDecl, boolean callbackExist) {
547 String method = "___initCallBack()";
548 int methodNumId = intDecl.getHelperMethodNumId(method);
549 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
550 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
551 String newIntface = intMeth.getKey();
552 int newObjectId = getNewIntfaceObjectId(newIntface);
553 println("set" + newObjectId + "Allowed.add(" + methodNumId + ");");
560 * HELPER: getPortCount() gets port count for different stubs and skeletons
562 private int getPortCount(String intface) {
564 if (!mapPortCount.containsKey(intface))
565 mapPortCount.put(intface, portCount++);
566 return mapPortCount.get(intface);
571 * HELPER: checkAndWriteEnumTypeJavaStub() writes the enum type (convert from enum to int)
573 private void checkAndWriteEnumTypeJavaStub(List<String> methParams, List<String> methPrmTypes) {
575 // Iterate and find enum declarations
576 for (int i = 0; i < methParams.size(); i++) {
577 String paramType = methPrmTypes.get(i);
578 String param = methParams.get(i);
579 String simpleType = getGenericType(paramType);
580 if (isEnumClass(simpleType)) {
581 // Check if this is enum type
582 if (isArray(param)) { // An array
583 println("int len" + i + " = " + getSimpleIdentifier(param) + ".length;");
584 println("int paramEnum" + i + "[] = new int[len" + i + "];");
585 println("for (int i = 0; i < len" + i + "; i++) {");
586 println("paramEnum" + i + "[i] = " + getSimpleIdentifier(param) + "[i].ordinal();");
588 } else if (isList(paramType)) { // A list
589 println("int len" + i + " = " + getSimpleIdentifier(param) + ".size();");
590 println("int paramEnum" + i + "[] = new int[len" + i + "];");
591 println("for (int i = 0; i < len" + i + "; i++) {");
592 println("paramEnum" + i + "[i] = " + getSimpleIdentifier(param) + ".get(i).ordinal();");
594 } else { // Just one element
595 println("int paramEnum" + i + "[] = new int[1];");
596 println("paramEnum" + i + "[0] = " + param + ".ordinal();");
604 * HELPER: checkAndWriteEnumRetTypeJavaStub() writes the enum return type (convert from enum to int)
606 private void checkAndWriteEnumRetTypeJavaStub(String retType, String method, InterfaceDecl intDecl) {
608 // Write the wait-for-return-value part
609 writeWaitForReturnValueJava(method, intDecl, "Object retObj = rmiComm.getReturnValue(retType, null);");
610 // Strips off array "[]" for return type
611 String pureType = getSimpleArrayType(getGenericType(retType));
612 // Take the inner type of generic
613 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
614 pureType = getGenericType(retType);
615 if (isEnumClass(pureType)) {
616 // Check if this is enum type
618 println("int[] retEnum = (int[]) retObj;");
619 println(pureType + "[] enumVals = " + pureType + ".values();");
620 if (isArray(retType)) { // An array
621 println("int retLen = retEnum.length;");
622 println(pureType + "[] enumRetVal = new " + pureType + "[retLen];");
623 println("for (int i = 0; i < retLen; i++) {");
624 println("enumRetVal[i] = enumVals[retEnum[i]];");
626 } else if (isList(retType)) { // A list
627 println("int retLen = retEnum.length;");
628 println("List<" + pureType + "> enumRetVal = new ArrayList<" + pureType + ">();");
629 println("for (int i = 0; i < retLen; i++) {");
630 println("enumRetVal.add(enumVals[retEnum[i]]);");
632 } else { // Just one element
633 println(pureType + " enumRetVal = enumVals[retEnum[0]];");
635 println("return enumRetVal;");
641 * HELPER: checkAndWriteStructSetupJavaStub() writes the struct type setup
643 private void checkAndWriteStructSetupJavaStub(List<String> methParams, List<String> methPrmTypes,
644 InterfaceDecl intDecl, String method) {
646 // Iterate and find struct declarations
647 for (int i = 0; i < methParams.size(); i++) {
648 String paramType = methPrmTypes.get(i);
649 String param = methParams.get(i);
650 String simpleType = getGenericType(paramType);
651 if (isStructClass(simpleType)) {
652 // Check if this is enum type
653 int methodNumId = intDecl.getMethodNumId(method);
654 String helperMethod = methodNumId + "struct" + i;
655 println("int methodIdStruct" + i + " = " + intDecl.getHelperMethodNumId(helperMethod) + ";");
656 println("Class<?>[] paramClsStruct" + i + " = new Class<?>[] { int.class };");
657 if (isArray(param)) { // An array
658 println("Object[] paramObjStruct" + i + " = new Object[] { " + getSimpleArrayType(param) + ".length };");
659 } else if (isList(paramType)) { // A list
660 println("Object[] paramObjStruct" + i + " = new Object[] { " + getSimpleArrayType(param) + ".size() };");
661 } else { // Just one element
662 println("Object[] paramObjStruct" + i + " = new Object[] { new Integer(1) };");
664 println("rmiComm.remoteCall(objectId, methodIdStruct" + i +
665 ", paramClsStruct" + i + ", paramObjStruct" + i + ");\n");
672 * HELPER: isStructPresent() checks presence of struct
674 private boolean isStructPresent(List<String> methParams, List<String> methPrmTypes) {
676 // Iterate and find enum declarations
677 for (int i = 0; i < methParams.size(); i++) {
678 String paramType = methPrmTypes.get(i);
679 String param = methParams.get(i);
680 String simpleType = getGenericType(paramType);
681 if (isStructClass(simpleType))
689 * HELPER: writeLengthStructParamClassJavaStub() writes lengths of parameters
691 private void writeLengthStructParamClassJavaStub(List<String> methParams, List<String> methPrmTypes) {
693 // Iterate and find struct declarations - count number of params
694 for (int i = 0; i < methParams.size(); i++) {
695 String paramType = methPrmTypes.get(i);
696 String param = methParams.get(i);
697 String simpleType = getGenericType(paramType);
698 if (isStructClass(simpleType)) {
699 int members = getNumOfMembers(simpleType);
700 if (isArray(param)) { // An array
701 String structLen = getSimpleArrayType(param) + ".length";
702 print(members + "*" + structLen);
703 } else if (isList(paramType)) { // A list
704 String structLen = getSimpleArrayType(param) + ".size()";
705 print(members + "*" + structLen);
707 print(Integer.toString(members));
710 if (i != methParams.size() - 1) {
718 * HELPER: writeStructMembersJavaStub() writes parameters of struct
720 private void writeStructMembersJavaStub(String simpleType, String paramType, String param) {
722 // Get the struct declaration for this struct and generate initialization code
723 StructDecl structDecl = getStructDecl(simpleType);
724 List<String> memTypes = structDecl.getMemberTypes(simpleType);
725 List<String> members = structDecl.getMembers(simpleType);
726 if (isArray(param)) { // An array
727 println("for(int i = 0; i < " + getSimpleIdentifier(param) + ".length; i++) {");
728 for (int i = 0; i < members.size(); i++) {
729 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
730 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
731 print("paramObj[pos++] = " + getSimpleIdentifier(param) + "[i].");
732 print(getSimpleIdentifier(members.get(i)));
736 } else if (isList(paramType)) { // A list
737 println("for(int i = 0; i < " + getSimpleIdentifier(param) + ".size(); i++) {");
738 for (int i = 0; i < members.size(); i++) {
739 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
740 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
741 print("paramObj[pos++] = " + getSimpleIdentifier(param) + ".get(i).");
742 print(getSimpleIdentifier(members.get(i)));
746 } else { // Just one struct element
747 for (int i = 0; i < members.size(); i++) {
748 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
749 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
750 print("paramObj[pos++] = " + getSimpleIdentifier(param) + ".");
751 print(getSimpleIdentifier(members.get(i)));
759 * HELPER: writeStructParamClassJavaStub() writes parameters if struct is present
761 private void writeStructParamClassJavaStub(List<String> methParams, List<String> methPrmTypes, String callbackType) {
763 print("int paramLen = ");
764 writeLengthStructParamClassJavaStub(methParams, methPrmTypes);
766 println("Object[] paramObj = new Object[paramLen];");
767 println("Class<?>[] paramCls = new Class<?>[paramLen];");
768 println("int pos = 0;");
769 // Iterate again over the parameters
770 for (int i = 0; i < methParams.size(); i++) {
771 String paramType = methPrmTypes.get(i);
772 String param = methParams.get(i);
773 String simpleType = getGenericType(paramType);
774 if (isStructClass(simpleType)) {
775 writeStructMembersJavaStub(simpleType, paramType, param);
776 } else if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
777 println("paramCls[pos] = int[].class;");
778 println("paramObj[pos++] = objIdSent" + i + ";");
780 String prmType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
781 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
782 print("paramObj[pos++] = ");
783 print(getEnumParam(methPrmTypes.get(i), getSimpleIdentifier(methParams.get(i)), i));
792 * HELPER: writeStructRetMembersJavaStub() writes parameters of struct for return statement
794 private void writeStructRetMembersJavaStub(String simpleType, String retType) {
796 // Get the struct declaration for this struct and generate initialization code
797 StructDecl structDecl = getStructDecl(simpleType);
798 List<String> memTypes = structDecl.getMemberTypes(simpleType);
799 List<String> members = structDecl.getMembers(simpleType);
800 if (isArrayOrList(retType, retType)) { // An array or list
801 println("for(int i = 0; i < retLen; i++) {");
803 if (isArray(retType)) { // An array
804 for (int i = 0; i < members.size(); i++) {
805 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
806 print("structRet[i]." + getSimpleIdentifier(members.get(i)));
807 println(" = (" + getSimpleType(getEnumType(prmType)) + ") retActualObj[retObjPos++];");
810 } else if (isList(retType)) { // A list
811 println(simpleType + " structRetMem = new " + simpleType + "();");
812 for (int i = 0; i < members.size(); i++) {
813 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
814 print("structRetMem." + getSimpleIdentifier(members.get(i)));
815 println(" = (" + getSimpleType(getEnumType(prmType)) + ") retActualObj[retObjPos++];");
817 println("structRet.add(structRetMem);");
819 } else { // Just one struct element
820 for (int i = 0; i < members.size(); i++) {
821 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
822 print("structRet." + getSimpleIdentifier(members.get(i)));
823 println(" = (" + getSimpleType(getEnumType(prmType)) + ") retActualObj[retObjPos++];");
826 println("return structRet;");
831 * HELPER: writeStructReturnJavaStub() writes parameters if struct is present for return statement
833 private void writeStructReturnJavaStub(String simpleType, String retType, String method, InterfaceDecl intDecl) {
835 // Handle the returned struct size
836 writeWaitForReturnValueJava(method, intDecl, "Object retObj = rmiComm.getReturnValue(retType, null);");
837 // Minimum retLen is 1 if this is a single struct object
838 println("int retLen = (int) retObj;");
839 int numMem = getNumOfMembers(simpleType);
840 println("Class<?>[] retCls = new Class<?>[" + numMem + "*retLen];");
841 println("Class<?>[] retClsVal = new Class<?>[" + numMem + "*retLen];");
842 println("int retPos = 0;");
843 // Get the struct declaration for this struct and generate initialization code
844 StructDecl structDecl = getStructDecl(simpleType);
845 List<String> memTypes = structDecl.getMemberTypes(simpleType);
846 List<String> members = structDecl.getMembers(simpleType);
847 if (isArrayOrList(retType, retType)) { // An array or list
848 println("for(int i = 0; i < retLen; i++) {");
849 for (int i = 0; i < members.size(); i++) {
850 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
851 println("retCls[retPos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
852 println("retClsVal[retPos++] = null;");
855 } else { // Just one struct element
856 for (int i = 0; i < members.size(); i++) {
857 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
858 println("retCls[retPos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
859 println("retClsVal[retPos++] = null;");
862 //println("Object[] retActualObj = rmiComm.getStructObjects(retCls, retClsVal);");
863 // Handle the actual returned struct
864 writeWaitForReturnValueJava(method, intDecl, "Object[] retActualObj = rmiComm.getStructObjects(retCls, retClsVal);");
865 if (isArray(retType)) { // An array
866 println(simpleType + "[] structRet = new " + simpleType + "[retLen];");
867 println("for(int i = 0; i < retLen; i++) {");
868 println("structRet[i] = new " + simpleType + "();");
870 } else if (isList(retType)) { // A list
871 println("List<" + simpleType + "> structRet = new ArrayList<" + simpleType + ">();");
873 println(simpleType + " structRet = new " + simpleType + "();");
874 println("int retObjPos = 0;");
875 writeStructRetMembersJavaStub(simpleType, retType);
880 * HELPER: writeWaitForReturnValueJava() writes the synchronization part for return values
882 private void writeWaitForReturnValueJava(String method, InterfaceDecl intDecl, String getReturnValue) {
884 println("// Waiting for return value");
885 int methodNumId = intDecl.getMethodNumId(method);
886 println("while (!retValueReceived" + methodNumId + ".get());");
887 println(getReturnValue);
888 println("retValueReceived" + methodNumId + ".set(false);");
889 println("rmiComm.setGetReturnBytes();\n");
894 * HELPER: writeStdMethodBodyJavaStub() writes the standard method body in the stub class
896 private void writeStdMethodBodyJavaStub(InterfaceDecl intDecl, List<String> methParams,
897 List<String> methPrmTypes, String method, String callbackType) {
899 checkAndWriteStructSetupJavaStub(methParams, methPrmTypes, intDecl, method);
900 println("int methodId = " + intDecl.getMethodNumId(method) + ";");
901 String retType = intDecl.getMethodType(method);
902 println("Class<?> retType = " + getSimpleType(getStructType(getEnumType(retType))) + ".class;");
903 checkAndWriteEnumTypeJavaStub(methParams, methPrmTypes);
904 // Generate array of parameter types
905 if (isStructPresent(methParams, methPrmTypes)) {
906 writeStructParamClassJavaStub(methParams, methPrmTypes, callbackType);
908 print("Class<?>[] paramCls = new Class<?>[] { ");
909 for (int i = 0; i < methParams.size(); i++) {
910 String prmType = methPrmTypes.get(i);
911 if (checkCallbackType(prmType, callbackType)) { // Check if this has callback object
912 print("int[].class");
913 } else { // Generate normal classes if it's not a callback object
914 String paramType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
915 print(getSimpleType(getEnumType(paramType)) + ".class");
917 // Check if this is the last element (don't print a comma)
918 if (i != methParams.size() - 1) {
923 // Generate array of parameter objects
924 print("Object[] paramObj = new Object[] { ");
925 for (int i = 0; i < methParams.size(); i++) {
926 String paramType = methPrmTypes.get(i);
927 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
928 print("objIdSent" + i);
930 print(getEnumParam(methPrmTypes.get(i), getSimpleIdentifier(methParams.get(i)), i));
931 // Check if this is the last element (don't print a comma)
932 if (i != methParams.size() - 1) {
938 // Send method call first and wait for return value separately
939 println("rmiComm.remoteCall(objectId, methodId, paramCls, paramObj);");
940 // Check if this is "void"
941 if (!retType.equals("void")) { // We do have a return value
942 // Generate array of parameter types
943 if (isStructClass(getGenericType(getSimpleArrayType(retType)))) {
944 writeStructReturnJavaStub(getGenericType(getSimpleArrayType(retType)), retType, method, intDecl);
946 // This is an enum type
947 if (getParamCategory(getGenericType(getSimpleArrayType(retType))) == ParamCategory.ENUM) {
948 //println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
949 checkAndWriteEnumRetTypeJavaStub(retType, method, intDecl);
950 } else if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES) {
951 // Check if the return value NONPRIMITIVES
952 String retGenValType = getGenericType(retType);
953 println("Class<?> retGenValType = " + retGenValType + ".class;");
954 writeWaitForReturnValueJava(method, intDecl, "Object retObj = rmiComm.getReturnValue(retType, retGenValType);");
955 println("return (" + retType + ")retObj;");
957 writeWaitForReturnValueJava(method, intDecl, "Object retObj = rmiComm.getReturnValue(retType, null);");
958 println("return (" + retType + ")retObj;");
966 * HELPER: returnGenericCallbackType() returns the callback type
968 private String returnGenericCallbackType(String paramType) {
970 if (getParamCategory(paramType) == ParamCategory.NONPRIMITIVES)
971 return getGenericType(paramType);
978 * HELPER: checkCallbackType() checks the callback type
980 private boolean checkCallbackType(String paramType, String callbackType) {
982 String prmType = returnGenericCallbackType(paramType);
983 if (callbackType == null) // If there is no callbackType it means not a callback method
986 return callbackType.equals(prmType);
991 * HELPER: writeCallbackInstantiationMethodBodyJavaStub() writes the callback object instantiation in the method of the stub class
993 private void writeCallbackInstantiationMethodBodyJavaStub(String paramIdent, String callbackType, int counter, boolean isMultipleCallbacks) {
995 println("if (!IoTRMIUtil.mapSkel.containsKey(" + paramIdent + ")) {");
996 println("int newObjIdSent = rmiComm.getObjectIdCounter();");
997 if (isMultipleCallbacks)
998 println("objIdSent" + counter + "[cnt" + counter + "++] = newObjIdSent;");
1000 println("objIdSent" + counter + "[0] = newObjIdSent;");
1001 println("rmiComm.decrementObjectIdCounter();");
1002 println(callbackType + "_Skeleton skel" + counter + " = new " + callbackType + "_Skeleton(" + paramIdent + ", rmiComm, newObjIdSent);");
1003 println("IoTRMIUtil.mapSkel.put(" + paramIdent + ", skel" + counter + ");");
1004 println("IoTRMIUtil.mapSkelId.put(" + paramIdent + ", newObjIdSent);");
1005 println("Thread thread = new Thread() {");
1006 println("public void run() {");
1008 println("skel" + counter + ".___waitRequestInvokeMethod();");
1009 println("} catch (Exception ex) {");
1010 println("ex.printStackTrace();");
1011 println("throw new Error(\"Exception when trying to run ___waitRequestInvokeMethod() for " +
1012 callbackType + "_Skeleton!\");");
1016 println("thread.start();");
1017 println("while(!skel" + counter + ".didAlreadyInitWaitInvoke());");
1021 println("int newObjIdSent = IoTRMIUtil.mapSkelId.get(" + paramIdent + ");");
1022 if (isMultipleCallbacks)
1023 println("objIdSent" + counter + "[cnt" + counter + "++] = newObjIdSent;");
1025 println("objIdSent" + counter + "[0] = newObjIdSent;");
1031 * HELPER: writeCallbackMethodBodyJavaStub() writes the callback method of the stub class
1033 private void writeCallbackMethodBodyJavaStub(InterfaceDecl intDecl, List<String> methParams,
1034 List<String> methPrmTypes, String method, String callbackType) {
1036 // Determine callback object counter type (List vs. single variable)
1037 for (int i = 0; i < methParams.size(); i++) {
1038 String paramType = methPrmTypes.get(i);
1039 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
1040 print("int[] objIdSent" + i + " = ");
1041 String param = methParams.get(i);
1042 if (isArray(methParams.get(i)))
1043 println("new int[" + getSimpleIdentifier(methParams.get(i)) + ".length];");
1044 else if (isList(methPrmTypes.get(i)))
1045 println("new int[" + getSimpleIdentifier(methParams.get(i)) + ".size()];");
1047 println("new int[1];");
1051 // Check if this is single object, array, or list of objects
1052 for (int i = 0; i < methParams.size(); i++) {
1053 String paramType = methPrmTypes.get(i);
1054 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
1055 String param = methParams.get(i);
1056 if (isArrayOrList(paramType, param)) { // Generate loop
1057 println("int cnt" + i + " = 0;");
1058 println("for (" + getGenericType(paramType) + " cb : " + getSimpleIdentifier(param) + ") {");
1059 writeCallbackInstantiationMethodBodyJavaStub("cb", callbackType, i, true);
1061 writeCallbackInstantiationMethodBodyJavaStub(getSimpleIdentifier(param), callbackType, i, false);
1062 if (isArrayOrList(paramType, param))
1067 println(" catch (Exception ex) {");
1068 println("ex.printStackTrace();");
1069 println("throw new Error(\"Exception when generating skeleton objects!\");");
1075 * HELPER: writeMethodJavaStub() writes the methods of the stub class
1077 private void writeMethodJavaStub(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses, String newStubClass) {
1079 for (String method : methods) {
1081 List<String> methParams = intDecl.getMethodParams(method);
1082 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1083 print("public " + intDecl.getMethodType(method) + " " +
1084 intDecl.getMethodId(method) + "(");
1085 boolean isCallbackMethod = false;
1086 String callbackType = null;
1087 for (int i = 0; i < methParams.size(); i++) {
1089 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
1090 // Check if this has callback object
1091 if (callbackClasses.contains(paramType)) {
1092 isCallbackMethod = true;
1093 callbackType = paramType;
1094 // Even if there're 2 callback arguments, we expect them to be of the same interface
1096 print(methPrmTypes.get(i) + " " + methParams.get(i));
1097 // Check if this is the last element (don't print a comma)
1098 if (i != methParams.size() - 1) {
1103 // Now, write the body of stub!
1104 if (isCallbackMethod)
1105 writeCallbackMethodBodyJavaStub(intDecl, methParams, methPrmTypes, method, callbackType);
1107 writeStdMethodBodyJavaStub(intDecl, methParams, methPrmTypes, method, callbackType);
1114 * HELPER: getStubInterface() gets stub interface name based on original interface
1116 public String getStubInterface(String intface) {
1118 return mapInt2NewIntName.get(intface);
1123 * generateJavaStubClasses() generate stubs based on the methods list in Java
1125 public void generateJavaStubClasses() throws IOException {
1127 // Create a new directory
1128 String path = createDirectories(dir, subdir);
1129 for (String intface : mapIntfacePTH.keySet()) {
1131 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
1132 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
1134 // Open a new file to write into
1135 String newIntface = intMeth.getKey();
1136 String newStubClass = newIntface + "_Stub";
1137 FileWriter fw = new FileWriter(path + "/" + newStubClass + ".java");
1138 pw = new PrintWriter(new BufferedWriter(fw));
1139 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
1140 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
1141 // Pass in set of methods and get import classes
1142 Set<String> methods = intMeth.getValue();
1143 Set<String> importClasses = getImportClasses(methods, intDecl);
1144 List<String> stdImportClasses = getStandardJavaImportClasses();
1145 List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
1146 printImportStatements(allImportClasses); println("");
1147 // Find out if there are callback objects
1148 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
1149 boolean callbackExist = !callbackClasses.isEmpty();
1150 // Write class header
1151 println("public class " + newStubClass + " implements " + newIntface + " {\n");
1153 writePropertiesJavaStub(intface, intMeth.getValue(), intDecl);
1154 // Write constructor
1155 writeConstructorJavaStub(intface, newStubClass, intMeth.getValue(), intDecl);
1156 // Write callback constructor (used if this stub is treated as a callback stub)
1157 writeCallbackConstructorJavaStub(intface, newStubClass, intMeth.getValue(), intDecl);
1159 writeMethodJavaStub(intMeth.getValue(), intDecl, callbackClasses, newStubClass);
1162 System.out.println("IoTCompiler: Generated stub class " + newStubClass + ".java...");
1169 * HELPER: writePropertiesJavaSkeleton() writes the properties of the skeleton class
1171 private void writePropertiesJavaSkeleton(String intface, InterfaceDecl intDecl) {
1173 println("private " + intface + " mainObj;");
1174 println("private int objectId = 0;");
1175 println("// Communications and synchronizations");
1176 println("private IoTRMIComm rmiComm;");
1177 println("private AtomicBoolean didAlreadyInitWaitInvoke;");
1178 println("private AtomicBoolean methodReceived;");
1179 println("private byte[] methodBytes = null;");
1180 println("// Permissions");
1181 writePropertiesJavaPermission(intface, intDecl);
1187 * HELPER: writeStructPermissionJavaSkeleton() writes permission for struct helper
1189 private void writeStructPermissionJavaSkeleton(Collection<String> methods, InterfaceDecl intDecl, String intface) {
1191 // Use this set to handle two same methodIds
1192 for (String method : methods) {
1193 List<String> methParams = intDecl.getMethodParams(method);
1194 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1195 // Check for params with structs
1196 for (int i = 0; i < methParams.size(); i++) {
1197 String paramType = methPrmTypes.get(i);
1198 String param = methParams.get(i);
1199 String simpleType = getGenericType(paramType);
1200 if (isStructClass(simpleType)) {
1201 int methodNumId = intDecl.getMethodNumId(method);
1202 String helperMethod = methodNumId + "struct" + i;
1203 int methodHelperNumId = intDecl.getHelperMethodNumId(helperMethod);
1204 // Iterate over interfaces to give permissions to
1205 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
1206 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
1207 String newIntface = intMeth.getKey();
1208 int newObjectId = getNewIntfaceObjectId(newIntface);
1209 println("set" + newObjectId + "Allowed.add(" + methodHelperNumId + ");");
1218 * HELPER: writeConstructorJavaSkeleton() writes the constructor of the skeleton class
1220 private void writeConstructorJavaSkeleton(String newSkelClass, String intface, InterfaceDecl intDecl,
1221 Collection<String> methods, boolean callbackExist) {
1223 println("public " + newSkelClass + "(" + intface + " _mainObj, int _portSend, int _portRecv) throws Exception {");
1224 println("mainObj = _mainObj;");
1225 println("rmiComm = new IoTRMICommServer(_portSend, _portRecv);");
1226 // Generate permission control initialization
1227 writeConstructorJavaPermission(intface);
1228 //writeJavaInitCallbackPermission(intface, intDecl, callbackExist);
1229 writeStructPermissionJavaSkeleton(methods, intDecl, intface);
1230 println("IoTRMIUtil.mapSkel.put(_mainObj, this);");
1231 println("IoTRMIUtil.mapSkelId.put(_mainObj, objectId);");
1232 println("didAlreadyInitWaitInvoke = new AtomicBoolean(false);");
1233 println("methodReceived = new AtomicBoolean(false);");
1234 println("rmiComm.registerSkeleton(objectId, methodReceived);");
1235 println("Thread thread1 = new Thread() {");
1236 println("public void run() {");
1238 println("___waitRequestInvokeMethod();");
1240 println("catch (Exception ex)");
1242 println("ex.printStackTrace();");
1246 println("thread1.start();");
1252 * HELPER: writeCallbackConstructorJavaSkeleton() writes the constructor of the skeleton class
1254 private void writeCallbackConstructorJavaSkeleton(String newSkelClass, String intface, InterfaceDecl intDecl,
1255 Collection<String> methods, boolean callbackExist) {
1257 println("public " + newSkelClass + "(" + intface + " _mainObj, IoTRMIComm _rmiComm, int _objectId) throws Exception {");
1258 println("mainObj = _mainObj;");
1259 println("rmiComm = _rmiComm;");
1260 println("objectId = _objectId;");
1261 // Generate permission control initialization
1262 writeConstructorJavaPermission(intface);
1263 writeStructPermissionJavaSkeleton(methods, intDecl, intface);
1264 println("didAlreadyInitWaitInvoke = new AtomicBoolean(false);");
1265 println("methodReceived = new AtomicBoolean(false);");
1266 println("rmiComm.registerSkeleton(objectId, methodReceived);");
1272 * HELPER: writeStdMethodBodyJavaSkeleton() writes the standard method body in the skeleton class
1274 private void writeStdMethodBodyJavaSkeleton(List<String> methParams, String methodId, String methodType) {
1276 if (methodType.equals("void"))
1277 print("mainObj." + methodId + "(");
1279 print("return mainObj." + methodId + "(");
1280 for (int i = 0; i < methParams.size(); i++) {
1282 print(getSimpleIdentifier(methParams.get(i)));
1283 // Check if this is the last element (don't print a comma)
1284 if (i != methParams.size() - 1) {
1293 * HELPER: writeMethodJavaSkeleton() writes the method of the skeleton class
1295 private void writeMethodJavaSkeleton(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses,
1296 boolean callbackSkeleton, String intface) {
1298 for (String method : methods) {
1300 List<String> methParams = intDecl.getMethodParams(method);
1301 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1302 String methodId = intDecl.getMethodId(method);
1303 print("public " + intDecl.getMethodType(method) + " " + methodId + "(");
1304 boolean isCallbackMethod = false;
1305 String callbackType = null;
1306 for (int i = 0; i < methParams.size(); i++) {
1308 String origParamType = methPrmTypes.get(i);
1309 String paramType = checkAndGetParamClass(origParamType);
1310 if (callbackClasses.contains(origParamType)) { // Check if this has callback object
1311 isCallbackMethod = true;
1312 callbackType = origParamType;
1314 print(paramType + " " + methParams.get(i));
1315 // Check if this is the last element (don't print a comma)
1316 if (i != methParams.size() - 1) {
1321 // Now, write the body of skeleton!
1322 writeStdMethodBodyJavaSkeleton(methParams, methodId, intDecl.getMethodType(method));
1329 * HELPER: writeCallbackInstantiationJavaStubGeneration() writes the instantiation of callback stubs
1331 private void writeCallbackInstantiationJavaStubGeneration(String exchParamType) {
1333 //println("int objIdRecv = (int[]) paramObj[0];");
1334 println(exchParamType + " newStub = null;");
1335 println("if(!IoTRMIUtil.mapStub.containsKey(objIdRecv)) {");
1336 println("newStub = new " + exchParamType + "_Stub(rmiComm, objIdRecv);");
1337 println("IoTRMIUtil.mapStub.put(objIdRecv, newStub);");
1338 println("rmiComm.setObjectIdCounter(objIdRecv);");
1339 println("rmiComm.decrementObjectIdCounter();");
1342 println("newStub = (" + exchParamType + "_Stub) IoTRMIUtil.mapStub.get(objIdRecv);");
1348 * HELPER: writeCallbackJavaStubGeneration() writes the callback stub generation part
1350 private Map<Integer,String> writeCallbackJavaStubGeneration(List<String> methParams, List<String> methPrmTypes,
1351 String callbackType, boolean isStructMethod) {
1353 Map<Integer,String> mapStubParam = new HashMap<Integer,String>();
1354 String offsetPfx = "";
1356 offsetPfx = "offset";
1357 // Iterate over callback objects
1358 for (int i = 0; i < methParams.size(); i++) {
1359 String paramType = methPrmTypes.get(i);
1360 String param = methParams.get(i);
1361 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
1362 String exchParamType = checkAndGetParamClass(getGenericType(paramType));
1363 // Print array if this is array or list if this is a list of callback objects
1364 println("int[] stubIdArray" + i + " = (int[]) paramObj[" + offsetPfx + i + "];");
1365 if (isArray(param)) {
1366 println("int numStubs" + i + " = stubIdArray" + i + ".length;");
1367 println(exchParamType + "[] stub" + i + " = new " + exchParamType + "[numStubs" + i + "];");
1368 } else if (isList(paramType)) {
1369 println("int numStubs" + i + " = stubIdArray" + i + ".length;");
1370 println("List<" + exchParamType + "> stub" + i + " = new ArrayList<" + exchParamType + ">();");
1372 println("int objIdRecv = stubIdArray" + i + "[0];");
1373 writeCallbackInstantiationJavaStubGeneration(exchParamType);
1376 // Generate a loop if needed
1377 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
1378 String exchParamType = checkAndGetParamClass(getGenericType(paramType));
1379 if (isArray(param)) {
1380 println("for (int i = 0; i < numStubs" + i + "; i++) {");
1381 println("int objIdRecv = stubIdArray" + i + "[i];");
1382 writeCallbackInstantiationJavaStubGeneration(exchParamType);
1383 println("stub" + i + "[i] = newStub;");
1385 } else if (isList(paramType)) {
1386 println("for (int i = 0; i < numStubs" + i + "; i++) {");
1387 println("int objIdRecv = stubIdArray" + i + "[i];");
1388 writeCallbackInstantiationJavaStubGeneration(exchParamType);
1389 println("stub" + i + ".add(newStub);");
1392 println(exchParamType + " stub" + i + " = newStub;");
1393 mapStubParam.put(i, "stub" + i); // List of all stub parameters
1396 return mapStubParam;
1401 * HELPER: checkAndWriteEnumTypeJavaSkeleton() writes the enum type (convert from enum to int)
1403 private void checkAndWriteEnumTypeJavaSkeleton(List<String> methParams, List<String> methPrmTypes, boolean isStructMethod) {
1405 String offsetPfx = "";
1407 offsetPfx = "offset";
1408 // Iterate and find enum declarations
1409 boolean printed = false;
1410 for (int i = 0; i < methParams.size(); i++) {
1411 String paramType = methPrmTypes.get(i);
1412 String param = methParams.get(i);
1413 String simpleType = getGenericType(paramType);
1414 if (isEnumClass(simpleType)) {
1415 // Check if this is enum type
1416 println("int paramInt" + i + "[] = (int[]) paramObj[" + offsetPfx + i + "];");
1418 println(simpleType + "[] enumVals = " + simpleType + ".values();");
1421 if (isArray(param)) { // An array
1422 println("int len" + i + " = paramInt" + i + ".length;");
1423 println(simpleType + "[] paramEnum" + i + " = new " + simpleType + "[len" + i + "];");
1424 println("for (int i = 0; i < len" + i + "; i++) {");
1425 println("paramEnum" + i + "[i] = enumVals[paramInt" + i + "[i]];");
1427 } else if (isList(paramType)) { // A list
1428 println("int len" + i + " = paramInt" + i + ".length;");
1429 println("List<" + simpleType + "> paramEnum" + i + " = new ArrayList<" + simpleType + ">();");
1430 println("for (int i = 0; i < len" + i + "; i++) {");
1431 println("paramEnum" + i + ".add(enumVals[paramInt" + i + "[i]]);");
1433 } else { // Just one element
1434 println(simpleType + " paramEnum" + i + " = enumVals[paramInt" + i + "[0]];");
1442 * HELPER: checkAndWriteEnumRetTypeJavaSkeleton() writes the enum return type (convert from enum to int)
1444 private void checkAndWriteEnumRetTypeJavaSkeleton(String retType, String methodId) {
1446 // Strips off array "[]" for return type
1447 String pureType = getSimpleArrayType(getGenericType(retType));
1448 // Take the inner type of generic
1449 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
1450 pureType = getGenericType(retType);
1451 if (isEnumClass(pureType)) {
1452 // Check if this is enum type
1454 if (isArray(retType)) { // An array
1455 print(pureType + "[] retEnum = " + methodId + "(");
1456 } else if (isList(retType)) { // A list
1457 print("List<" + pureType + "> retEnum = " + methodId + "(");
1458 } else { // Just one element
1459 print(pureType + " retEnum = " + methodId + "(");
1466 * HELPER: checkAndWriteEnumRetConvJavaSkeleton() writes the enum return type (convert from enum to int)
1468 private void checkAndWriteEnumRetConvJavaSkeleton(String retType) {
1470 // Strips off array "[]" for return type
1471 String pureType = getSimpleArrayType(getGenericType(retType));
1472 // Take the inner type of generic
1473 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
1474 pureType = getGenericType(retType);
1475 if (isEnumClass(pureType)) {
1476 // Check if this is enum type
1477 if (isArray(retType)) { // An array
1478 println("int retLen = retEnum.length;");
1479 println("int[] retEnumVal = new int[retLen];");
1480 println("for (int i = 0; i < retLen; i++) {");
1481 println("retEnumVal[i] = retEnum[i].ordinal();");
1483 } else if (isList(retType)) { // A list
1484 println("int retLen = retEnum.size();");
1485 println("int[] retEnumVal = new int[retLen];");
1486 println("for (int i = 0; i < retLen; i++) {");
1487 println("retEnumVal[i] = retEnum.get(i).ordinal();");
1489 } else { // Just one element
1490 println("int[] retEnumVal = new int[1];");
1491 println("retEnumVal[0] = retEnum.ordinal();");
1493 println("Object retObj = retEnumVal;");
1499 * HELPER: writeLengthStructParamClassSkeleton() writes lengths of params
1501 private void writeLengthStructParamClassSkeleton(List<String> methParams, List<String> methPrmTypes,
1502 String method, InterfaceDecl intDecl) {
1504 // Iterate and find struct declarations - count number of params
1505 for (int i = 0; i < methParams.size(); i++) {
1506 String paramType = methPrmTypes.get(i);
1507 String param = methParams.get(i);
1508 String simpleType = getGenericType(paramType);
1509 if (isStructClass(simpleType)) {
1510 int members = getNumOfMembers(simpleType);
1511 print(Integer.toString(members) + "*");
1512 int methodNumId = intDecl.getMethodNumId(method);
1513 print("struct" + methodNumId + "Size" + i);
1516 if (i != methParams.size() - 1) {
1524 * HELPER: writeStructMembersJavaSkeleton() writes member parameters of struct
1526 private void writeStructMembersJavaSkeleton(String simpleType, String paramType,
1527 String param, String method, InterfaceDecl intDecl, int iVar) {
1529 // Get the struct declaration for this struct and generate initialization code
1530 StructDecl structDecl = getStructDecl(simpleType);
1531 List<String> memTypes = structDecl.getMemberTypes(simpleType);
1532 List<String> members = structDecl.getMembers(simpleType);
1533 if (isArrayOrList(paramType, param)) { // An array or list
1534 int methodNumId = intDecl.getMethodNumId(method);
1535 String counter = "struct" + methodNumId + "Size" + iVar;
1536 println("for(int i = 0; i < " + counter + "; i++) {");
1538 if (isArrayOrList(paramType, param)) { // An array or list
1539 for (int i = 0; i < members.size(); i++) {
1540 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
1541 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
1542 println("paramClsGen[pos++] = null;");
1545 } else { // Just one struct element
1546 for (int i = 0; i < members.size(); i++) {
1547 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
1548 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
1549 println("paramClsGen[pos++] = null;");
1556 * HELPER: writeStructMembersInitJavaSkeleton() writes member parameters initialization of struct
1558 private void writeStructMembersInitJavaSkeleton(InterfaceDecl intDecl, List<String> methParams,
1559 List<String> methPrmTypes, String method) {
1561 println("int objPos = 0;");
1562 for (int i = 0; i < methParams.size(); i++) {
1563 String paramType = methPrmTypes.get(i);
1564 String param = methParams.get(i);
1565 String simpleType = getGenericType(paramType);
1566 if (isStructClass(simpleType)) {
1567 int methodNumId = intDecl.getMethodNumId(method);
1568 String counter = "struct" + methodNumId + "Size" + i;
1570 if (isArray(param)) { // An array
1571 println(simpleType + "[] paramStruct" + i + " = new " + simpleType + "[" + counter + "];");
1572 println("for(int i = 0; i < " + counter + "; i++) {");
1573 println("paramStruct" + i + "[i] = new " + simpleType + "();");
1575 } else if (isList(paramType)) { // A list
1576 println("List<" + simpleType + "> paramStruct" + i + " = new ArrayList<" + simpleType + ">();");
1578 println(simpleType + " paramStruct" + i + " = new " + simpleType + "();");
1579 // Initialize members
1580 StructDecl structDecl = getStructDecl(simpleType);
1581 List<String> members = structDecl.getMembers(simpleType);
1582 List<String> memTypes = structDecl.getMemberTypes(simpleType);
1583 if (isArrayOrList(paramType, param)) { // An array or list
1584 println("for(int i = 0; i < " + counter + "; i++) {");
1586 if (isArray(param)) { // An array
1587 for (int j = 0; j < members.size(); j++) {
1588 String prmType = checkAndGetArray(memTypes.get(j), members.get(j));
1589 print("paramStruct" + i + "[i]." + getSimpleIdentifier(members.get(j)));
1590 println(" = (" + getSimpleType(getEnumType(prmType)) + ") paramObj[objPos++];");
1593 } else if (isList(paramType)) { // A list
1594 println(simpleType + " paramStructMem = new " + simpleType + "();");
1595 for (int j = 0; j < members.size(); j++) {
1596 String prmType = checkAndGetArray(memTypes.get(j), members.get(j));
1597 print("paramStructMem." + getSimpleIdentifier(members.get(j)));
1598 println(" = (" + getSimpleType(getEnumType(prmType)) + ") paramObj[objPos++];");
1600 println("paramStruct" + i + ".add(paramStructMem);");
1602 } else { // Just one struct element
1603 for (int j = 0; j < members.size(); j++) {
1604 String prmType = checkAndGetArray(memTypes.get(j), members.get(j));
1605 print("paramStruct" + i + "." + getSimpleIdentifier(members.get(j)));
1606 println(" = (" + getSimpleType(getEnumType(prmType)) + ") paramObj[objPos++];");
1610 // Take offsets of parameters
1611 println("int offset" + i +" = objPos++;");
1618 * HELPER: writeStructReturnJavaSkeleton() writes struct for return statement
1620 private void writeStructReturnJavaSkeleton(String simpleType, String retType) {
1622 // Minimum retLen is 1 if this is a single struct object
1623 if (isArray(retType))
1624 println("int retLen = retStruct.length;");
1625 else if (isList(retType))
1626 println("int retLen = retStruct.size();");
1627 else // Just single struct object
1628 println("int retLen = 1;");
1629 println("Object retLenObj = retLen;");
1630 println("rmiComm.sendReturnObj(retLenObj, localMethodBytes);");
1631 int numMem = getNumOfMembers(simpleType);
1632 println("Class<?>[] retCls = new Class<?>[" + numMem + "*retLen];");
1633 println("Object[] retObj = new Object[" + numMem + "*retLen];");
1634 println("int retPos = 0;");
1635 // Get the struct declaration for this struct and generate initialization code
1636 StructDecl structDecl = getStructDecl(simpleType);
1637 List<String> memTypes = structDecl.getMemberTypes(simpleType);
1638 List<String> members = structDecl.getMembers(simpleType);
1639 if (isArray(retType)) { // An array or list
1640 println("for(int i = 0; i < retLen; i++) {");
1641 for (int i = 0; i < members.size(); i++) {
1642 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
1643 println("retCls[retPos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
1644 print("retObj[retPos++] = retStruct[i].");
1645 print(getEnumParam(memTypes.get(i), getSimpleIdentifier(members.get(i)), i));
1649 } else if (isList(retType)) { // An array or list
1650 println("for(int i = 0; i < retLen; i++) {");
1651 for (int i = 0; i < members.size(); i++) {
1652 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
1653 println("retCls[retPos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
1654 print("retObj[retPos++] = retStruct.get(i).");
1655 print(getEnumParam(memTypes.get(i), getSimpleIdentifier(members.get(i)), i));
1659 } else { // Just one struct element
1660 for (int i = 0; i < members.size(); i++) {
1661 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
1662 println("retCls[retPos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
1663 print("retObj[retPos++] = retStruct.");
1664 print(getEnumParam(memTypes.get(i), getSimpleIdentifier(members.get(i)), i));
1673 * HELPER: writeMethodHelperReturnJavaSkeleton() writes return statement part in skeleton
1675 private void writeMethodHelperReturnJavaSkeleton(InterfaceDecl intDecl, List<String> methParams,
1676 List<String> methPrmTypes, String method, boolean isCallbackMethod, String callbackType,
1677 boolean isStructMethod) {
1679 checkAndWriteEnumTypeJavaSkeleton(methParams, methPrmTypes, isStructMethod);
1680 Map<Integer,String> mapStubParam = null;
1681 if (isCallbackMethod) {
1683 mapStubParam = writeCallbackJavaStubGeneration(methParams, methPrmTypes, callbackType, isStructMethod);
1685 // Check if this is "void"
1686 String retType = intDecl.getMethodType(method);
1687 if (retType.equals("void")) {
1688 print(intDecl.getMethodId(method) + "(");
1689 } else if (isEnumClass(getSimpleArrayType(getGenericType(retType)))) { // Enum type
1690 checkAndWriteEnumRetTypeJavaSkeleton(retType, intDecl.getMethodId(method));
1691 } else if (isStructClass(getSimpleArrayType(getGenericType(retType)))) { // Struct type
1692 print(retType + " retStruct = " + intDecl.getMethodId(method) + "(");
1693 } else { // We do have a return value
1694 print("Object retObj = " + intDecl.getMethodId(method) + "(");
1696 for (int i = 0; i < methParams.size(); i++) {
1698 String paramType = methPrmTypes.get(i);
1699 if (isCallbackMethod && checkCallbackType(paramType, callbackType)) {
1700 print(mapStubParam.get(i)); // Get the callback parameter
1701 } else if (isEnumClass(getGenericType(paramType))) { // Enum class
1702 print(getEnumParam(paramType, methParams.get(i), i));
1703 } else if (isStructClass(getGenericType(paramType))) {
1704 print("paramStruct" + i);
1706 String prmType = checkAndGetArray(paramType, methParams.get(i));
1708 print("(" + prmType + ") paramObj[offset" + i + "]");
1710 print("(" + prmType + ") paramObj[" + i + "]");
1712 if (i != methParams.size() - 1)
1716 if (!retType.equals("void")) {
1717 if (isEnumClass(getSimpleArrayType(getGenericType(retType)))) { // Enum type
1718 checkAndWriteEnumRetConvJavaSkeleton(retType);
1719 println("rmiComm.sendReturnObj(retObj, localMethodBytes);");
1720 } else if (isStructClass(getSimpleArrayType(getGenericType(retType)))) { // Struct type
1721 writeStructReturnJavaSkeleton(getSimpleArrayType(getGenericType(retType)), retType);
1722 println("rmiComm.sendReturnObj(retCls, retObj, localMethodBytes);");
1724 println("rmiComm.sendReturnObj(retObj, localMethodBytes);");
1726 if (isCallbackMethod) { // Catch exception if this is callback
1728 println(" catch(Exception ex) {");
1729 println("ex.printStackTrace();");
1730 println("throw new Error(\"Exception from callback object instantiation!\");");
1737 * HELPER: writeMethodHelperStructJavaSkeleton() writes the struct in skeleton
1739 private void writeMethodHelperStructJavaSkeleton(InterfaceDecl intDecl, List<String> methParams,
1740 List<String> methPrmTypes, String method, Set<String> callbackClasses) {
1742 // Generate array of parameter objects
1743 boolean isCallbackMethod = false;
1744 String callbackType = null;
1745 println("byte[] localMethodBytes = methodBytes;");
1746 println("rmiComm.setGetMethodBytes();");
1747 print("int paramLen = ");
1748 writeLengthStructParamClassSkeleton(methParams, methPrmTypes, method, intDecl);
1750 println("Class<?>[] paramCls = new Class<?>[paramLen];");
1751 println("Class<?>[] paramClsGen = new Class<?>[paramLen];");
1752 println("int pos = 0;");
1753 // Iterate again over the parameters
1754 for (int i = 0; i < methParams.size(); i++) {
1755 String paramType = methPrmTypes.get(i);
1756 String param = methParams.get(i);
1757 String simpleType = getGenericType(paramType);
1758 if (isStructClass(simpleType)) {
1759 writeStructMembersJavaSkeleton(simpleType, paramType, param, method, intDecl, i);
1761 String prmType = returnGenericCallbackType(methPrmTypes.get(i));
1762 if (callbackClasses.contains(prmType)) {
1763 isCallbackMethod = true;
1764 callbackType = prmType;
1765 println("paramCls[pos] = int[].class;");
1766 println("paramClsGen[pos++] = null;");
1767 } else { // Generate normal classes if it's not a callback object
1768 String paramTypeOth = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
1769 println("paramCls[pos] = " + getSimpleType(getEnumType(paramTypeOth)) + ".class;");
1770 print("paramClsGen[pos++] = ");
1771 String prmTypeOth = methPrmTypes.get(i);
1772 if (getParamCategory(prmTypeOth) == ParamCategory.NONPRIMITIVES)
1773 println(getTypeOfGeneric(prmType)[0] + ".class;");
1779 println("Object[] paramObj = rmiComm.getMethodParams(paramCls, paramClsGen, localMethodBytes);");
1780 writeStructMembersInitJavaSkeleton(intDecl, methParams, methPrmTypes, method);
1781 // Write the return value part
1782 writeMethodHelperReturnJavaSkeleton(intDecl, methParams, methPrmTypes, method, isCallbackMethod, callbackType, true);
1787 * HELPER: writeStdMethodHelperBodyJavaSkeleton() writes the standard method body helper in the skeleton class
1789 private void writeStdMethodHelperBodyJavaSkeleton(InterfaceDecl intDecl, List<String> methParams,
1790 List<String> methPrmTypes, String method, Set<String> callbackClasses) {
1792 // Generate array of parameter objects
1793 boolean isCallbackMethod = false;
1794 String callbackType = null;
1795 println("byte[] localMethodBytes = methodBytes;");
1796 println("rmiComm.setGetMethodBytes();");
1797 print("Object[] paramObj = rmiComm.getMethodParams(new Class<?>[] { ");
1798 for (int i = 0; i < methParams.size(); i++) {
1800 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
1801 if (callbackClasses.contains(paramType)) {
1802 isCallbackMethod = true;
1803 callbackType = paramType;
1804 print("int[].class");
1805 } else { // Generate normal classes if it's not a callback object
1806 String prmType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
1807 print(getSimpleType(getEnumType(prmType)) + ".class");
1809 if (i != methParams.size() - 1)
1813 // Generate generic class if it's a generic type.. null otherwise
1814 print(" }, new Class<?>[] { ");
1815 for (int i = 0; i < methParams.size(); i++) {
1816 String prmType = methPrmTypes.get(i);
1817 if ((getParamCategory(prmType) == ParamCategory.NONPRIMITIVES) &&
1818 !isEnumClass(getGenericType(prmType)) &&
1819 !callbackClasses.contains(getGenericType(prmType)))
1820 print(getGenericType(prmType) + ".class");
1823 if (i != methParams.size() - 1)
1826 println(" }, localMethodBytes);");
1827 // Write the return value part
1828 writeMethodHelperReturnJavaSkeleton(intDecl, methParams, methPrmTypes, method, isCallbackMethod, callbackType, false);
1833 * HELPER: writeMethodHelperJavaSkeleton() writes the method helper of the skeleton class
1835 private void writeMethodHelperJavaSkeleton(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
1837 // Use this set to handle two same methodIds
1838 Set<String> uniqueMethodIds = new HashSet<String>();
1839 for (String method : methods) {
1841 List<String> methParams = intDecl.getMethodParams(method);
1842 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1843 if (isStructPresent(methParams, methPrmTypes)) { // Treat struct differently
1844 String methodId = intDecl.getMethodId(method);
1845 print("public void ___");
1846 String helperMethod = methodId;
1847 if (uniqueMethodIds.contains(methodId))
1848 helperMethod = helperMethod + intDecl.getMethodNumId(method);
1850 uniqueMethodIds.add(methodId);
1851 String retType = intDecl.getMethodType(method);
1852 print(helperMethod + "(");
1853 boolean begin = true;
1854 for (int i = 0; i < methParams.size(); i++) { // Print size variables
1855 String paramType = methPrmTypes.get(i);
1856 String param = methParams.get(i);
1857 String simpleType = getGenericType(paramType);
1858 if (isStructClass(simpleType)) {
1859 if (!begin) // Generate comma for not the beginning variable
1863 int methodNumId = intDecl.getMethodNumId(method);
1864 print("int struct" + methodNumId + "Size" + i);
1867 // Check if this is "void"
1868 if (retType.equals("void"))
1871 println(") throws IOException {");
1872 writeMethodHelperStructJavaSkeleton(intDecl, methParams, methPrmTypes, method, callbackClasses);
1875 String methodId = intDecl.getMethodId(method);
1876 print("public void ___");
1877 String helperMethod = methodId;
1878 if (uniqueMethodIds.contains(methodId))
1879 helperMethod = helperMethod + intDecl.getMethodNumId(method);
1881 uniqueMethodIds.add(methodId);
1882 // Check if this is "void"
1883 String retType = intDecl.getMethodType(method);
1884 if (retType.equals("void"))
1885 println(helperMethod + "() {");
1887 println(helperMethod + "() throws IOException {");
1888 // Now, write the helper body of skeleton!
1889 writeStdMethodHelperBodyJavaSkeleton(intDecl, methParams, methPrmTypes, method, callbackClasses);
1893 // Write method helper for structs
1894 writeMethodHelperStructSetupJavaSkeleton(methods, intDecl);
1899 * HELPER: writeMethodHelperStructSetupJavaSkeleton() writes the method helper of struct setup in skeleton class
1901 private void writeMethodHelperStructSetupJavaSkeleton(Collection<String> methods,
1902 InterfaceDecl intDecl) {
1904 // Use this set to handle two same methodIds
1905 for (String method : methods) {
1907 List<String> methParams = intDecl.getMethodParams(method);
1908 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1909 // Check for params with structs
1910 for (int i = 0; i < methParams.size(); i++) {
1911 String paramType = methPrmTypes.get(i);
1912 String param = methParams.get(i);
1913 String simpleType = getGenericType(paramType);
1914 if (isStructClass(simpleType)) {
1915 int methodNumId = intDecl.getMethodNumId(method);
1916 print("public int ___");
1917 String helperMethod = methodNumId + "struct" + i;
1918 println(helperMethod + "() {");
1919 // Now, write the helper body of skeleton!
1920 println("byte[] localMethodBytes = methodBytes;");
1921 println("rmiComm.setGetMethodBytes();");
1922 println("Object[] paramObj = rmiComm.getMethodParams(new Class<?>[] { int.class }, new Class<?>[] { null }, localMethodBytes);");
1923 println("return (int) paramObj[0];");
1932 * HELPER: writeMethodHelperStructSetupJavaCallbackSkeleton() writes the method helper of struct setup in callback skeleton class
1934 private void writeMethodHelperStructSetupJavaCallbackSkeleton(Collection<String> methods,
1935 InterfaceDecl intDecl) {
1937 // Use this set to handle two same methodIds
1938 for (String method : methods) {
1940 List<String> methParams = intDecl.getMethodParams(method);
1941 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1942 // Check for params with structs
1943 for (int i = 0; i < methParams.size(); i++) {
1944 String paramType = methPrmTypes.get(i);
1945 String param = methParams.get(i);
1946 String simpleType = getGenericType(paramType);
1947 if (isStructClass(simpleType)) {
1948 int methodNumId = intDecl.getMethodNumId(method);
1949 print("public int ___");
1950 String helperMethod = methodNumId + "struct" + i;
1951 println(helperMethod + "(IoTRMIObject rmiObj) {");
1952 // Now, write the helper body of skeleton!
1953 println("Object[] paramObj = rmiComm.getMethodParams(new Class<?>[] { int.class }, new Class<?>[] { null });");
1954 println("return (int) paramObj[0];");
1963 * HELPER: writeCountVarStructSkeleton() writes counter variable of struct for skeleton
1965 private void writeCountVarStructSkeleton(Collection<String> methods, InterfaceDecl intDecl) {
1967 // Use this set to handle two same methodIds
1968 for (String method : methods) {
1970 List<String> methParams = intDecl.getMethodParams(method);
1971 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1972 // Check for params with structs
1973 for (int i = 0; i < methParams.size(); i++) {
1974 String paramType = methPrmTypes.get(i);
1975 String param = methParams.get(i);
1976 String simpleType = getGenericType(paramType);
1977 if (isStructClass(simpleType)) {
1978 int methodNumId = intDecl.getMethodNumId(method);
1979 println("int struct" + methodNumId + "Size" + i + " = 0;");
1987 * HELPER: writeInputCountVarStructJavaSkeleton() writes input counter variable of struct for skeleton
1989 private boolean writeInputCountVarStructJavaSkeleton(String method, InterfaceDecl intDecl) {
1991 List<String> methParams = intDecl.getMethodParams(method);
1992 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1993 boolean structExist = false;
1994 boolean begin = true;
1995 // Check for params with structs
1996 for (int i = 0; i < methParams.size(); i++) {
1997 String paramType = methPrmTypes.get(i);
1998 String param = methParams.get(i);
1999 String simpleType = getGenericType(paramType);
2000 if (isStructClass(simpleType)) {
2006 int methodNumId = intDecl.getMethodNumId(method);
2007 print("struct" + methodNumId + "Size" + i + "Final");
2015 * HELPER: writeInputCountVarStructCplusSkeleton() writes input counter variable of struct for skeleton
2017 private boolean writeInputCountVarStructCplusSkeleton(String method, InterfaceDecl intDecl) {
2019 List<String> methParams = intDecl.getMethodParams(method);
2020 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2021 boolean structExist = false;
2022 boolean begin = true;
2023 // Check for params with structs
2024 for (int i = 0; i < methParams.size(); i++) {
2025 String paramType = methPrmTypes.get(i);
2026 String param = methParams.get(i);
2027 String simpleType = getGenericType(paramType);
2028 if (isStructClass(simpleType)) {
2034 int methodNumId = intDecl.getMethodNumId(method);
2035 print("struct" + methodNumId + "Size" + i);
2043 * HELPER: writeMethodCallStructJavaSkeleton() writes method call for wait invoke in skeleton
2045 private void writeMethodCallStructJavaSkeleton(Collection<String> methods, InterfaceDecl intDecl) {
2047 // Use this set to handle two same methodIds
2048 for (String method : methods) {
2050 List<String> methParams = intDecl.getMethodParams(method);
2051 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2052 // Check for params with structs
2053 for (int i = 0; i < methParams.size(); i++) {
2054 String paramType = methPrmTypes.get(i);
2055 String param = methParams.get(i);
2056 String simpleType = getGenericType(paramType);
2057 if (isStructClass(simpleType)) {
2058 int methodNumId = intDecl.getMethodNumId(method);
2060 String helperMethod = methodNumId + "struct" + i;
2061 String tempVar = "struct" + methodNumId + "Size" + i;
2062 print(intDecl.getHelperMethodNumId(helperMethod) + ": ");
2063 print(tempVar + " = ___");
2064 println(helperMethod + "(); break;");
2072 * HELPER: writeMethodCallStructCplusSkeleton() writes method call for wait invoke in skeleton
2074 private void writeMethodCallStructCplusSkeleton(Collection<String> methods, InterfaceDecl intDecl) {
2076 // Use this set to handle two same methodIds
2077 for (String method : methods) {
2079 List<String> methParams = intDecl.getMethodParams(method);
2080 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2081 // Check for params with structs
2082 for (int i = 0; i < methParams.size(); i++) {
2083 String paramType = methPrmTypes.get(i);
2084 String param = methParams.get(i);
2085 String simpleType = getGenericType(paramType);
2086 if (isStructClass(simpleType)) {
2087 int methodNumId = intDecl.getMethodNumId(method);
2089 String helperMethod = methodNumId + "struct" + i;
2090 String tempVar = "struct" + methodNumId + "Size" + i;
2091 print(intDecl.getHelperMethodNumId(helperMethod) + ": ");
2092 print(tempVar + " = ___");
2093 println(helperMethod + "(skel); break;");
2101 * HELPER: writeMethodCallStructCallbackSkeleton() writes method call for wait invoke in skeleton
2103 private void writeMethodCallStructCallbackSkeleton(Collection<String> methods, InterfaceDecl intDecl) {
2105 // Use this set to handle two same methodIds
2106 for (String method : methods) {
2108 List<String> methParams = intDecl.getMethodParams(method);
2109 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2110 // Check for params with structs
2111 for (int i = 0; i < methParams.size(); i++) {
2112 String paramType = methPrmTypes.get(i);
2113 String param = methParams.get(i);
2114 String simpleType = getGenericType(paramType);
2115 if (isStructClass(simpleType)) {
2116 int methodNumId = intDecl.getMethodNumId(method);
2118 String helperMethod = methodNumId + "struct" + i;
2119 String tempVar = "struct" + methodNumId + "Size" + i;
2120 print(intDecl.getHelperMethodNumId(helperMethod) + ": ");
2121 print(tempVar + " = ___");
2122 println(helperMethod + "(rmiObj); break;");
2130 * HELPER: writeJavaMethodPermission() writes permission checks in skeleton
2132 private void writeJavaMethodPermission(String intface) {
2134 // Get all the different stubs
2135 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
2136 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
2137 String newIntface = intMeth.getKey();
2138 int newObjectId = getNewIntfaceObjectId(newIntface);
2139 println("if (_objectId == objectId) {");
2140 println("if (!set" + newObjectId + "Allowed.contains(methodId)) {");
2141 println("throw new Error(\"Object with object Id: \" + _objectId + \" is not allowed to access method: \" + methodId);");
2145 println("continue;");
2152 * HELPER: writeFinalInputCountVarStructSkeleton() writes the final version of input counter variable of struct for skeleton
2154 private boolean writeFinalInputCountVarStructSkeleton(String method, InterfaceDecl intDecl) {
2156 List<String> methParams = intDecl.getMethodParams(method);
2157 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2158 boolean structExist = false;
2159 boolean begin = true;
2160 // Check for params with structs
2161 for (int i = 0; i < methParams.size(); i++) {
2162 String paramType = methPrmTypes.get(i);
2163 String param = methParams.get(i);
2164 String simpleType = getGenericType(paramType);
2165 if (isStructClass(simpleType)) {
2167 int methodNumId = intDecl.getMethodNumId(method);
2168 println("final int struct" + methodNumId + "Size" + i +
2169 "Final = struct" + methodNumId + "Size" + i + ";");
2177 * HELPER: writeJavaWaitRequestInvokeMethod() writes the main loop of the skeleton class
2179 private void writeJavaWaitRequestInvokeMethod(Collection<String> methods, InterfaceDecl intDecl, String intface) {
2181 // Use this set to handle two same methodIds
2182 Set<String> uniqueMethodIds = new HashSet<String>();
2183 println("public void ___waitRequestInvokeMethod() throws IOException {");
2184 // Write variables here if we have callbacks or enums or structs
2185 writeCountVarStructSkeleton(methods, intDecl);
2186 println("didAlreadyInitWaitInvoke.compareAndSet(false, true);");
2187 println("while (true) {");
2188 println("if (!methodReceived.get()) {");
2189 println("continue;");
2191 println("methodBytes = rmiComm.getMethodBytes();");
2192 println("methodReceived.set(false);");
2193 println("int _objectId = IoTRMIComm.getObjectId(methodBytes);");
2194 println("int methodId = IoTRMIComm.getMethodId(methodBytes);");
2195 // Generate permission check
2196 writeJavaMethodPermission(intface);
2197 println("switch (methodId) {");
2198 // Print methods and method Ids
2199 for (String method : methods) {
2200 String methodId = intDecl.getMethodId(method);
2201 int methodNumId = intDecl.getMethodNumId(method);
2202 println("case " + methodNumId + ":");
2203 // Check for stuct counters
2204 writeFinalInputCountVarStructSkeleton(method, intDecl);
2205 println("new Thread() {");
2206 println("public void run() {");
2209 String helperMethod = methodId;
2210 if (uniqueMethodIds.contains(methodId))
2211 helperMethod = helperMethod + methodNumId;
2213 uniqueMethodIds.add(methodId);
2214 print(helperMethod + "(");
2215 writeInputCountVarStructJavaSkeleton(method, intDecl);
2218 println("catch (Exception ex) {");
2219 println("ex.printStackTrace();");
2222 println("}.start();");
2225 String method = "___initCallBack()";
2226 writeMethodCallStructJavaSkeleton(methods, intDecl);
2227 println("default: ");
2228 println("throw new Error(\"Method Id \" + methodId + \" not recognized!\");");
2236 * HELPER: writeReturnDidAlreadyInitWaitInvoke() writes the function to return didAlreadyInitWaitInvoke
2238 private void writeReturnDidAlreadyInitWaitInvoke() {
2240 println("public boolean didAlreadyInitWaitInvoke() {");
2241 println("return didAlreadyInitWaitInvoke.get();");
2247 * generateJavaSkeletonClass() generate skeletons based on the methods list in Java
2249 public void generateJavaSkeletonClass() throws IOException {
2251 // Create a new directory
2252 String path = createDirectories(dir, subdir);
2253 for (String intface : mapIntfacePTH.keySet()) {
2254 // Open a new file to write into
2255 String newSkelClass = intface + "_Skeleton";
2256 FileWriter fw = new FileWriter(path + "/" + newSkelClass + ".java");
2257 pw = new PrintWriter(new BufferedWriter(fw));
2258 // Pass in set of methods and get import classes
2259 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2260 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
2261 List<String> methods = intDecl.getMethods();
2262 Set<String> importClasses = getImportClasses(methods, intDecl);
2263 List<String> stdImportClasses = getStandardJavaImportClasses();
2264 List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
2265 printImportStatements(allImportClasses);
2266 // Find out if there are callback objects
2267 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
2268 boolean callbackExist = !callbackClasses.isEmpty();
2269 // Write class header
2271 println("public class " + newSkelClass + " implements " + intface + " {\n");
2273 writePropertiesJavaSkeleton(intface, intDecl);
2274 // Write constructor
2275 writeConstructorJavaSkeleton(newSkelClass, intface, intDecl, methods, callbackExist);
2276 // Write constructor that is called when this object is a callback object
2277 writeCallbackConstructorJavaSkeleton(newSkelClass, intface, intDecl, methods, callbackExist);
2278 // Write function to return didAlreadyInitWaitInvoke
2279 writeReturnDidAlreadyInitWaitInvoke();
2281 writeMethodJavaSkeleton(methods, intDecl, callbackClasses, false, intface);
2282 // Write method helper
2283 writeMethodHelperJavaSkeleton(methods, intDecl, callbackClasses);
2284 // Write waitRequestInvokeMethod() - main loop
2285 writeJavaWaitRequestInvokeMethod(methods, intDecl, intface);
2288 System.out.println("IoTCompiler: Generated skeleton class " + newSkelClass + ".java...");
2293 /*================================================================================
2297 *================================================================================/
2300 * HELPER: writeMethodCplusLocalInterface() writes the method of the local interface
2302 private void writeMethodCplusLocalInterface(Collection<String> methods, InterfaceDecl intDecl) {
2304 for (String method : methods) {
2306 List<String> methParams = intDecl.getMethodParams(method);
2307 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2308 print("virtual " + checkAndGetCplusType(intDecl.getMethodType(method)) + " " +
2309 intDecl.getMethodId(method) + "(");
2310 for (int i = 0; i < methParams.size(); i++) {
2311 // Check for params with driver class types and exchange it
2312 // with its remote interface
2313 String paramType = checkAndGetParamClass(methPrmTypes.get(i));
2314 paramType = checkAndGetCplusType(paramType);
2315 // Check for arrays - translate into vector in C++
2316 String paramComplete = checkAndGetCplusArray(paramType, methParams.get(i));
2317 print(paramComplete);
2318 // Check if this is the last element (don't print a comma)
2319 if (i != methParams.size() - 1) {
2329 * HELPER: writeMethodCplusInterface() writes the method of the interface
2331 private void writeMethodCplusInterface(Collection<String> methods, InterfaceDecl intDecl) {
2333 for (String method : methods) {
2335 List<String> methParams = intDecl.getMethodParams(method);
2336 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2337 print("virtual " + checkAndGetCplusType(intDecl.getMethodType(method)) + " " +
2338 intDecl.getMethodId(method) + "(");
2339 for (int i = 0; i < methParams.size(); i++) {
2340 // Check for params with driver class types and exchange it
2341 // with its remote interface
2342 String paramType = methPrmTypes.get(i);
2343 paramType = checkAndGetCplusType(paramType);
2344 // Check for arrays - translate into vector in C++
2345 String paramComplete = checkAndGetCplusArray(paramType, methParams.get(i));
2346 print(paramComplete);
2347 // Check if this is the last element (don't print a comma)
2348 if (i != methParams.size() - 1) {
2358 * HELPER: generateEnumCplus() writes the enumeration declaration
2360 public void generateEnumCplus() throws IOException {
2362 // Create a new directory
2363 createDirectory(dir);
2364 for (String intface : mapIntfacePTH.keySet()) {
2365 // Get the right StructDecl
2366 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2367 EnumDecl enumDecl = (EnumDecl) decHandler.getEnumDecl(intface);
2368 Set<String> enumTypes = enumDecl.getEnumDeclarations();
2369 // Iterate over enum declarations
2370 for (String enType : enumTypes) {
2371 // Open a new file to write into
2372 FileWriter fw = new FileWriter(dir + "/" + enType + ".hpp");
2373 pw = new PrintWriter(new BufferedWriter(fw));
2374 // Write file headers
2375 println("#ifndef _" + enType.toUpperCase() + "_HPP__");
2376 println("#define _" + enType.toUpperCase() + "_HPP__");
2377 println("enum " + enType + " {");
2378 List<String> enumMembers = enumDecl.getMembers(enType);
2379 for (int i = 0; i < enumMembers.size(); i++) {
2381 String member = enumMembers.get(i);
2383 // Check if this is the last element (don't print a comma)
2384 if (i != enumMembers.size() - 1)
2392 System.out.println("IoTCompiler: Generated enum " + enType + ".hpp...");
2399 * HELPER: generateStructCplus() writes the struct declaration
2401 public void generateStructCplus() throws IOException {
2403 // Create a new directory
2404 createDirectory(dir);
2405 for (String intface : mapIntfacePTH.keySet()) {
2406 // Get the right StructDecl
2407 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2408 StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
2409 List<String> structTypes = structDecl.getStructTypes();
2410 // Iterate over enum declarations
2411 for (String stType : structTypes) {
2412 // Open a new file to write into
2413 FileWriter fw = new FileWriter(dir + "/" + stType + ".hpp");
2414 pw = new PrintWriter(new BufferedWriter(fw));
2415 // Write file headers
2416 println("#ifndef _" + stType.toUpperCase() + "_HPP__");
2417 println("#define _" + stType.toUpperCase() + "_HPP__");
2418 println("using namespace std;");
2419 println("struct " + stType + " {");
2420 List<String> structMemberTypes = structDecl.getMemberTypes(stType);
2421 List<String> structMembers = structDecl.getMembers(stType);
2422 for (int i = 0; i < structMembers.size(); i++) {
2424 String memberType = structMemberTypes.get(i);
2425 String member = structMembers.get(i);
2426 String structTypeC = checkAndGetCplusType(memberType);
2427 String structComplete = checkAndGetCplusArray(structTypeC, member);
2428 println(structComplete + ";");
2433 System.out.println("IoTCompiler: Generated struct " + stType + ".hpp...");
2440 * generateCplusLocalInterfaces() writes the local interfaces and provides type-checking.
2442 * It needs to rewrite and exchange USERDEFINED types in input parameters of stub
2443 * and original interfaces, e.g. exchange Camera and CameraWithVideoAndRecording.
2444 * The local interface has to be the input parameter for the stub and the stub
2445 * interface has to be the input parameter for the local class.
2447 public void generateCplusLocalInterfaces() throws IOException {
2449 // Create a new directory
2450 createDirectory(dir);
2451 for (String intface : mapIntfacePTH.keySet()) {
2452 // Open a new file to write into
2453 FileWriter fw = new FileWriter(dir + "/" + intface + ".hpp");
2454 pw = new PrintWriter(new BufferedWriter(fw));
2455 // Write file headers
2456 println("#ifndef _" + intface.toUpperCase() + "_HPP__");
2457 println("#define _" + intface.toUpperCase() + "_HPP__");
2458 println("#include <iostream>");
2459 // Pass in set of methods and get include classes
2460 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2461 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
2462 List<String> methods = intDecl.getMethods();
2463 Set<String> includeClasses = getIncludeClasses(methods, intDecl, intface, true);
2464 printIncludeStatements(includeClasses); println("");
2465 println("using namespace std;\n");
2466 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
2467 if (!intface.equals(mainClass)) // Forward declare if not main class
2468 writeMethodCplusInterfaceForwardDecl(methods, intDecl, callbackClasses, true);
2469 println("class " + intface); println("{");
2472 writeMethodCplusLocalInterface(methods, intDecl);
2476 System.out.println("IoTCompiler: Generated local interface " + intface + ".hpp...");
2482 * HELPER: writeMethodCplusInterfaceForwardDecl() writes the forward declaration of the interface
2484 private void writeMethodCplusInterfaceForwardDecl(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses, boolean needNewIntface) {
2486 Set<String> isDefined = new HashSet<String>();
2487 for (String method : methods) {
2489 List<String> methParams = intDecl.getMethodParams(method);
2490 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2491 for (int i = 0; i < methParams.size(); i++) {
2492 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
2493 // Check if this has callback object
2494 if (callbackClasses.contains(paramType)) {
2495 if (!isDefined.contains(paramType)) {
2497 println("class " + getStubInterface(paramType) + ";\n");
2499 println("class " + paramType + ";\n");
2500 isDefined.add(paramType);
2509 * generateCPlusInterfaces() generate stub interfaces based on the methods list in C++
2511 * For C++ we use virtual classe as interface
2513 public void generateCPlusInterfaces() throws IOException {
2515 // Create a new directory
2516 String path = createDirectories(dir, subdir);
2517 for (String intface : mapIntfacePTH.keySet()) {
2519 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
2520 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
2522 // Open a new file to write into
2523 String newIntface = intMeth.getKey();
2524 FileWriter fw = new FileWriter(path + "/" + newIntface + ".hpp");
2525 pw = new PrintWriter(new BufferedWriter(fw));
2526 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2527 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
2528 // Write file headers
2529 println("#ifndef _" + newIntface.toUpperCase() + "_HPP__");
2530 println("#define _" + newIntface.toUpperCase() + "_HPP__");
2531 println("#include <iostream>");
2532 updateIntfaceObjIdMap(intface, newIntface);
2533 // Pass in set of methods and get import classes
2534 Set<String> methods = intMeth.getValue();
2535 Set<String> includeClasses = getIncludeClasses(methods, intDecl, intface, false);
2536 printIncludeStatements(includeClasses); println("");
2537 println("using namespace std;\n");
2538 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
2539 writeMethodCplusInterfaceForwardDecl(methods, intDecl, callbackClasses, false);
2540 println("class " + newIntface);
2544 writeMethodCplusInterface(methods, intDecl);
2548 System.out.println("IoTCompiler: Generated interface " + newIntface + ".hpp...");
2555 * HELPER: writeMethodDeclCplusStub() writes the method declarations of the stub
2557 private void writeMethodDeclCplusStub(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses, String newStubClass) {
2559 for (String method : methods) {
2561 List<String> methParams = intDecl.getMethodParams(method);
2562 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2563 print(checkAndGetCplusType(intDecl.getMethodType(method)) + " " +
2564 intDecl.getMethodId(method) + "(");
2565 boolean isCallbackMethod = false;
2566 String callbackType = null;
2567 for (int i = 0; i < methParams.size(); i++) {
2569 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
2570 // Check if this has callback object
2571 if (callbackClasses.contains(paramType)) {
2572 isCallbackMethod = true;
2573 callbackType = paramType;
2574 // Even if there're 2 callback arguments, we expect them to be of the same interface
2576 String methPrmType = checkAndGetCplusType(methPrmTypes.get(i));
2577 String methParamComplete = checkAndGetCplusArray(methPrmType, methParams.get(i));
2578 print(methParamComplete);
2579 // Check if this is the last element (don't print a comma)
2580 if (i != methParams.size() - 1) {
2590 * HELPER: writeMethodCplusStub() writes the methods of the stub
2592 private void writeMethodCplusStub(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses, String newStubClass) {
2594 for (String method : methods) {
2596 List<String> methParams = intDecl.getMethodParams(method);
2597 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2598 // Print the mutex lock first
2599 int methodNumId = intDecl.getMethodNumId(method);
2600 String mutexVar = "mtx" + newStubClass + "MethodExec" + methodNumId;
2601 println("mutex " + mutexVar + ";");
2602 print(checkAndGetCplusType(intDecl.getMethodType(method)) + " " + newStubClass + "::" +
2603 intDecl.getMethodId(method) + "(");
2604 boolean isCallbackMethod = false;
2605 String callbackType = null;
2606 for (int i = 0; i < methParams.size(); i++) {
2608 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
2609 // Check if this has callback object
2610 if (callbackClasses.contains(paramType)) {
2611 isCallbackMethod = true;
2612 callbackType = paramType;
2613 // Even if there're 2 callback arguments, we expect them to be of the same interface
2615 String methPrmType = checkAndGetCplusType(methPrmTypes.get(i));
2616 String methParamComplete = checkAndGetCplusArray(methPrmType, methParams.get(i));
2617 print(methParamComplete);
2618 // Check if this is the last element (don't print a comma)
2619 if (i != methParams.size() - 1) {
2624 println("lock_guard<mutex> guard(" + mutexVar + ");");
2625 if (isCallbackMethod)
2626 writeCallbackMethodBodyCplusStub(intDecl, methParams, methPrmTypes, method, callbackType);
2627 writeStdMethodBodyCplusStub(intDecl, methParams, methPrmTypes, method, callbackType, isCallbackMethod);
2635 * HELPER: writeCallbackInstantiationMethodBodyCplusStub() writes the callback object instantiation in the method of the stub class
2637 private void writeCallbackInstantiationMethodBodyCplusStub(String paramIdent, String callbackType, int counter) {
2639 println("auto it = IoTRMIUtil::mapSkel->find(" + paramIdent + ");");
2640 println("if (it == IoTRMIUtil::mapSkel->end()) {");
2641 println("int newObjIdSent = rmiComm->getObjectIdCounter();");
2642 println("objIdSent" + counter + ".push_back(newObjIdSent);");
2643 println("rmiComm->decrementObjectIdCounter();");
2644 println(callbackType + "_Skeleton* skel" + counter + " = new " + callbackType + "_Skeleton(" + paramIdent + ", rmiComm, newObjIdSent);");
2645 println("vecCallbackObj.push_back(skel" + counter + ");");
2646 println("IoTRMIUtil::mapSkel->insert(make_pair(" + paramIdent + ", skel" + counter + "));");
2647 println("IoTRMIUtil::mapSkelId->insert(make_pair(" + paramIdent + ", newObjIdSent));");
2648 println("thread th" + counter + " (&" + callbackType + "_Skeleton::___waitRequestInvokeMethod, std::ref(skel" + counter +
2649 "), std::ref(skel" + counter +"));");
2650 println("th" + counter + ".detach();");
2651 println("while(!skel" + counter + "->didInitWaitInvoke());");
2655 println("auto itId = IoTRMIUtil::mapSkelId->find(" + paramIdent + ");");
2656 println("objIdSent" + counter + ".push_back(itId->second);");
2662 * HELPER: writeCallbackMethodBodyCplusStub() writes the callback method of the stub class
2664 private void writeCallbackMethodBodyCplusStub(InterfaceDecl intDecl, List<String> methParams,
2665 List<String> methPrmTypes, String method, String callbackType) {
2667 // Check if this is single object, array, or list of objects
2668 boolean isArrayOrList = false;
2669 String callbackParam = null;
2670 for (int i = 0; i < methParams.size(); i++) {
2671 String paramType = methPrmTypes.get(i);
2672 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
2673 println("vector<int> objIdSent" + i + ";");
2674 String param = methParams.get(i);
2675 if (isArrayOrList(paramType, param)) { // Generate loop
2676 println("for (" + getGenericType(paramType) + "* cb : " + getSimpleIdentifier(param) + ") {");
2677 writeCallbackInstantiationMethodBodyCplusStub("cb", callbackType, i);
2678 isArrayOrList = true;
2679 callbackParam = getSimpleIdentifier(param);
2681 writeCallbackInstantiationMethodBodyCplusStub(getSimpleIdentifier(param), callbackType, i);
2685 println("vector<int> ___paramCB" + i + " = objIdSent" + i + ";");
2692 * HELPER: checkAndWriteEnumTypeCplusStub() writes the enum type (convert from enum to int)
2694 private void checkAndWriteEnumTypeCplusStub(List<String> methParams, List<String> methPrmTypes) {
2696 // Iterate and find enum declarations
2697 for (int i = 0; i < methParams.size(); i++) {
2698 String paramType = methPrmTypes.get(i);
2699 String param = methParams.get(i);
2700 if (isEnumClass(getGenericType(paramType))) {
2701 // Check if this is enum type
2702 if (isArrayOrList(paramType, param)) { // An array or vector
2703 println("int len" + i + " = " + getSimpleIdentifier(param) + ".size();");
2704 println("vector<int> paramEnum" + i + "(len" + i + ");");
2705 println("for (int i = 0; i < len" + i + "; i++) {");
2706 println("paramEnum" + i + "[i] = (int) " + getSimpleIdentifier(param) + "[i];");
2708 } else { // Just one element
2709 println("vector<int> paramEnum" + i + "(1);");
2710 println("paramEnum" + i + "[0] = (int) " + param + ";");
2718 * HELPER: checkAndWriteEnumRetTypeCplusStub() writes the enum return type (convert from enum to int)
2720 private void checkAndWriteEnumRetTypeCplusStub(String retType, String method, InterfaceDecl intDecl) {
2722 // Strips off array "[]" for return type
2723 String pureType = getSimpleArrayType(getGenericType(retType));
2724 // Take the inner type of generic
2725 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
2726 pureType = getGenericType(retType);
2727 if (isEnumClass(pureType)) {
2728 // Check if this is enum type
2729 println("vector<int> retEnumInt;");
2730 println("void* retObj = &retEnumInt;");
2731 println("rmiComm->remoteCall(objectId, methodId, paramCls, paramObj, numParam);");
2732 writeWaitForReturnValueCplus(method, intDecl, "rmiComm->getReturnValue(retType, retObj);");
2733 if (isArrayOrList(retType, retType)) { // An array or vector
2734 println("int retLen = retEnumInt.size();");
2735 println("vector<" + pureType + "> retVal(retLen);");
2736 println("for (int i = 0; i < retLen; i++) {");
2737 println("retVal[i] = (" + pureType + ") retEnumInt[i];");
2739 } else { // Just one element
2740 println(pureType + " retVal = (" + pureType + ") retEnumInt[0];");
2742 println("return retVal;");
2748 * HELPER: checkAndWriteStructSetupCplusStub() writes the struct type setup
2750 private void checkAndWriteStructSetupCplusStub(List<String> methParams, List<String> methPrmTypes,
2751 InterfaceDecl intDecl, String method) {
2753 // Iterate and find struct declarations
2754 for (int i = 0; i < methParams.size(); i++) {
2755 String paramType = methPrmTypes.get(i);
2756 String param = methParams.get(i);
2757 String simpleType = getGenericType(paramType);
2758 if (isStructClass(simpleType)) {
2759 // Check if this is enum type
2760 println("int numParam" + i + " = 1;");
2761 int methodNumId = intDecl.getMethodNumId(method);
2762 String helperMethod = methodNumId + "struct" + i;
2763 println("int methodIdStruct" + i + " = " + intDecl.getHelperMethodNumId(helperMethod) + ";");
2764 //println("string retTypeStruct" + i + " = \"void\";");
2765 println("string paramClsStruct" + i + "[] = { \"int\" };");
2766 print("int structLen" + i + " = ");
2767 if (isArrayOrList(paramType, param)) { // An array
2768 println(getSimpleArrayType(param) + ".size();");
2769 } else { // Just one element
2772 println("void* paramObjStruct" + i + "[] = { &structLen" + i + " };");
2773 //println("void* retStructLen" + i + " = NULL;");
2774 println("rmiComm->remoteCall(objectId, methodIdStruct" + i +
2775 ", paramClsStruct" + i + ", paramObjStruct" + i +
2776 ", numParam" + i + ");\n");
2783 * HELPER: writeLengthStructParamClassCplusStub() writes lengths of params
2785 private void writeLengthStructParamClassCplusStub(List<String> methParams, List<String> methPrmTypes) {
2787 // Iterate and find struct declarations - count number of params
2788 for (int i = 0; i < methParams.size(); i++) {
2789 String paramType = methPrmTypes.get(i);
2790 String param = methParams.get(i);
2791 String simpleType = getGenericType(paramType);
2792 if (isStructClass(simpleType)) {
2793 int members = getNumOfMembers(simpleType);
2794 if (isArrayOrList(paramType, param)) { // An array or list
2795 String structLen = getSimpleIdentifier(param) + ".size()";
2796 print(members + "*" + structLen);
2798 print(Integer.toString(members));
2801 if (i != methParams.size() - 1) {
2809 * HELPER: writeStructMembersCplusStub() writes member parameters of struct
2811 private void writeStructMembersCplusStub(String simpleType, String paramType, String param) {
2813 // Get the struct declaration for this struct and generate initialization code
2814 StructDecl structDecl = getStructDecl(simpleType);
2815 List<String> memTypes = structDecl.getMemberTypes(simpleType);
2816 List<String> members = structDecl.getMembers(simpleType);
2817 if (isArrayOrList(paramType, param)) { // An array or list
2818 println("for(int i = 0; i < " + getSimpleIdentifier(param) + ".size(); i++) {");
2820 if (isArrayOrList(paramType, param)) { // An array or list
2821 for (int i = 0; i < members.size(); i++) {
2822 String prmTypeC = checkAndGetCplusArgClsType(memTypes.get(i), members.get(i));
2823 println("paramCls[pos] = \"" + prmTypeC + "\";");
2824 print("paramObj[pos++] = &" + getSimpleIdentifier(param) + "[i].");
2825 print(getSimpleIdentifier(members.get(i)));
2829 } else { // Just one struct element
2830 for (int i = 0; i < members.size(); i++) {
2831 String prmTypeC = checkAndGetCplusArgClsType(memTypes.get(i), members.get(i));
2832 println("paramCls[pos] = \"" + prmTypeC + "\";");
2833 print("paramObj[pos++] = &" + param + ".");
2834 print(getSimpleIdentifier(members.get(i)));
2842 * HELPER: writeStructParamClassCplusStub() writes member parameters of struct
2844 private void writeStructParamClassCplusStub(List<String> methParams, List<String> methPrmTypes, String callbackType) {
2846 print("int numParam = ");
2847 writeLengthStructParamClassCplusStub(methParams, methPrmTypes);
2849 println("void* paramObj[numParam];");
2850 println("string paramCls[numParam];");
2851 println("int pos = 0;");
2852 // Iterate again over the parameters
2853 for (int i = 0; i < methParams.size(); i++) {
2854 String paramType = methPrmTypes.get(i);
2855 String param = methParams.get(i);
2856 String simpleType = getGenericType(paramType);
2857 if (isStructClass(simpleType)) {
2858 writeStructMembersCplusStub(simpleType, paramType, param);
2859 } else if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
2860 println("paramCls[pos] = \"int\";");
2861 println("paramObj[pos++] = &___paramCB" + i + ";");
2863 String prmTypeC = checkAndGetCplusArgClsType(methPrmTypes.get(i), methParams.get(i));
2864 println("paramCls[pos] = \"" + prmTypeC + "\";");
2865 print("paramObj[pos++] = &");
2866 print(getEnumParam(methPrmTypes.get(i), getSimpleIdentifier(methParams.get(i)), i));
2875 * HELPER: writeStructRetMembersCplusStub() writes member parameters of struct for return statement
2877 private void writeStructRetMembersCplusStub(String simpleType, String retType) {
2879 // Get the struct declaration for this struct and generate initialization code
2880 StructDecl structDecl = getStructDecl(simpleType);
2881 List<String> memTypes = structDecl.getMemberTypes(simpleType);
2882 List<String> members = structDecl.getMembers(simpleType);
2883 if (isArrayOrList(retType, retType)) { // An array or list
2884 println("for(int i = 0; i < retLen; i++) {");
2886 if (isArrayOrList(retType, retType)) { // An array or list
2887 for (int i = 0; i < members.size(); i++) {
2888 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
2889 print("structRet[i]." + getSimpleIdentifier(members.get(i)));
2890 println(" = retParam" + i + "[i];");
2893 } else { // Just one struct element
2894 for (int i = 0; i < members.size(); i++) {
2895 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
2896 print("structRet." + getSimpleIdentifier(members.get(i)));
2897 println(" = retParam" + i + ";");
2900 println("return structRet;");
2905 * HELPER: writeStructReturnCplusStub() writes member parameters of struct for return statement
2907 private void writeStructReturnCplusStub(String simpleType, String retType, String method, InterfaceDecl intDecl) {
2909 // Minimum retLen is 1 if this is a single struct object
2910 println("int retLen = 0;");
2911 println("void* retLenObj = { &retLen };");
2912 // Handle the returned struct!!!
2913 println("rmiComm->remoteCall(objectId, methodId, paramCls, paramObj, numParam);");
2914 writeWaitForReturnValueCplus(method, intDecl, "rmiComm->getReturnValue(retType, retLenObj);");
2915 int numMem = getNumOfMembers(simpleType);
2916 println("int numRet = " + numMem + "*retLen;");
2917 println("string retCls[numRet];");
2918 println("void* retObj[numRet];");
2919 StructDecl structDecl = getStructDecl(simpleType);
2920 List<String> memTypes = structDecl.getMemberTypes(simpleType);
2921 List<String> members = structDecl.getMembers(simpleType);
2923 if (isArrayOrList(retType, retType)) { // An array or list
2924 for (int i = 0; i < members.size(); i++) {
2925 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
2926 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
2927 println(getSimpleType(getEnumType(prmType)) + " retParam" + i + "[retLen];");
2929 } else { // Just one struct element
2930 for (int i = 0; i < members.size(); i++) {
2931 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
2932 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
2933 println(getSimpleType(getEnumType(prmType)) + " retParam" + i + ";");
2936 println("int retPos = 0;");
2937 // Get the struct declaration for this struct and generate initialization code
2938 if (isArrayOrList(retType, retType)) { // An array or list
2939 println("for(int i = 0; i < retLen; i++) {");
2940 for (int i = 0; i < members.size(); i++) {
2941 String prmTypeC = checkAndGetCplusArgClsType(memTypes.get(i), members.get(i));
2942 println("retCls[retPos] = \"" + prmTypeC + "\";");
2943 println("retObj[retPos++] = &retParam" + i + "[i];");
2946 } else { // Just one struct element
2947 for (int i = 0; i < members.size(); i++) {
2948 String prmTypeC = checkAndGetCplusArgClsType(memTypes.get(i), members.get(i));
2949 println("retCls[retPos] = \"" + prmTypeC + "\";");
2950 println("retObj[retPos++] = &retParam" + i + ";");
2953 //println("rmiComm->getStructObjects(retCls, numRet, retObj);");
2954 writeWaitForReturnValueCplus(method, intDecl, "rmiComm->getStructObjects(retCls, numRet, retObj);");
2955 if (isArrayOrList(retType, retType)) { // An array or list
2956 println("vector<" + simpleType + "> structRet(retLen);");
2958 println(simpleType + " structRet;");
2959 writeStructRetMembersCplusStub(simpleType, retType);
2964 * HELPER: writeWaitForReturnValueCplus() writes the synchronization part for return values
2966 private void writeWaitForReturnValueCplus(String method, InterfaceDecl intDecl, String getReturnValue) {
2968 println("// Waiting for return value");
2969 int methodNumId = intDecl.getMethodNumId(method);
2970 println("while (!retValueReceived" + methodNumId + ");");
2971 println(getReturnValue);
2972 println("retValueReceived" + methodNumId + " = false;");
2973 println("didGetReturnBytes.exchange(true);\n");
2978 * HELPER: writeStdMethodBodyCplusStub() writes the standard method body in the stub class
2980 private void writeStdMethodBodyCplusStub(InterfaceDecl intDecl, List<String> methParams,
2981 List<String> methPrmTypes, String method, String callbackType, boolean isCallbackMethod) {
2983 checkAndWriteStructSetupCplusStub(methParams, methPrmTypes, intDecl, method);
2984 println("int methodId = " + intDecl.getMethodNumId(method) + ";");
2985 String retType = intDecl.getMethodType(method);
2986 println("string retType = \"" + checkAndGetCplusRetClsType(getStructType(getEnumType(retType))) + "\";");
2987 checkAndWriteEnumTypeCplusStub(methParams, methPrmTypes);
2988 // Generate array of parameter types
2989 if (isStructPresent(methParams, methPrmTypes)) {
2990 writeStructParamClassCplusStub(methParams, methPrmTypes, callbackType);
2992 println("int numParam = " + methParams.size() + ";");
2993 print("string paramCls[] = { ");
2994 for (int i = 0; i < methParams.size(); i++) {
2995 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
2996 if (checkCallbackType(paramType, callbackType)) {
2999 String paramTypeC = checkAndGetCplusArgClsType(methPrmTypes.get(i), methParams.get(i));
3000 print("\"" + paramTypeC + "\"");
3002 // Check if this is the last element (don't print a comma)
3003 if (i != methParams.size() - 1) {
3008 // Generate array of parameter objects
3009 print("void* paramObj[] = { ");
3010 for (int i = 0; i < methParams.size(); i++) {
3011 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
3012 if (checkCallbackType(paramType, callbackType)) // Check if this has callback object
3013 print("&___paramCB" + i);
3015 print("&" + getEnumParam(methPrmTypes.get(i), getSimpleIdentifier(methParams.get(i)), i));
3016 // Check if this is the last element (don't print a comma)
3017 if (i != methParams.size() - 1) {
3023 // Check if this is "void"
3024 if (retType.equals("void")) {
3025 println("rmiComm->remoteCall(objectId, methodId, paramCls, paramObj, numParam);");
3026 } else { // We do have a return value
3027 // Generate array of parameter types
3028 if (isStructClass(getGenericType(getSimpleArrayType(retType)))) {
3029 writeStructReturnCplusStub(getGenericType(getSimpleArrayType(retType)), retType, method, intDecl);
3031 // Check if the return value NONPRIMITIVES
3032 if (isEnumClass(getSimpleArrayType(getGenericType(retType)))) {
3033 checkAndWriteEnumRetTypeCplusStub(retType, method, intDecl);
3035 //if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
3036 if (isArrayOrList(retType,retType))
3037 println(checkAndGetCplusType(retType) + " retVal;");
3039 println(checkAndGetCplusType(retType) + " retVal = " + generateCplusInitializer(retType) + ";");
3041 println("void* retObj = &retVal;");
3042 println("rmiComm->remoteCall(objectId, methodId, paramCls, paramObj, numParam);");
3043 writeWaitForReturnValueCplus(method, intDecl, "rmiComm->getReturnValue(retType, retObj);");
3044 println("return retVal;");
3052 * HELPER: writePropertiesCplusPermission() writes the properties of the stub class
3054 private void writePropertiesCplusPermission(String intface) {
3056 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3057 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3058 String newIntface = intMeth.getKey();
3059 int newObjectId = getNewIntfaceObjectId(newIntface);
3060 println("int objectId = " + newObjectId + ";");
3061 println("static set<int> set" + newObjectId + "Allowed;");
3066 * HELPER: writePropertiesCplusStub() writes the properties of the stub class
3068 private void writePropertiesCplusStub(String intface, String newIntface, boolean callbackExist,
3069 Set<String> callbackClasses, Set<String> methods, InterfaceDecl intDecl) {
3071 println("IoTRMIComm *rmiComm;");
3072 // Get the object Id
3073 Integer objId = mapIntfaceObjId.get(intface);
3074 println("int objectId = " + objId + ";");
3075 if (callbackExist) {
3076 // We assume that each class only has one callback interface for now
3077 Iterator it = callbackClasses.iterator();
3078 String callbackType = (String) it.next();
3079 println("// Callback properties");
3080 println("vector<" + callbackType + "*> vecCallbackObj;");
3082 println("// Synchronization variables");
3083 for (String method : methods) {
3084 // Generate AtomicBooleans for methods that have return values
3085 String returnType = intDecl.getMethodType(method);
3086 int methodNumId = intDecl.getMethodNumId(method);
3087 if (!returnType.equals("void")) {
3088 println("bool retValueReceived" + methodNumId + " = false;");
3096 * HELPER: writeConstructorCplusStub() writes the constructor of the stub class
3098 private void writeConstructorCplusStub(String newStubClass, boolean callbackExist,
3099 Set<String> callbackClasses, Set<String> methods, InterfaceDecl intDecl) {
3101 println(newStubClass + "::" + newStubClass +
3102 "(int _portSend, int _portRecv, const char* _skeletonAddress, int _rev, bool* _bResult) {");
3103 println("rmiComm = new IoTRMICommClient(_portSend, _portRecv, _skeletonAddress, _rev, _bResult);");
3104 // Register the AtomicBoolean variables
3105 for (String method : methods) {
3106 // Generate AtomicBooleans for methods that have return values
3107 String returnType = intDecl.getMethodType(method);
3108 int methodNumId = intDecl.getMethodNumId(method);
3109 if (!returnType.equals("void")) {
3110 println("rmiComm->registerStub(objectId, " + methodNumId + ", &retValueReceived" + methodNumId + ");");
3113 println("IoTRMIUtil::mapStub->insert(make_pair(objectId, this));");
3119 * HELPER: writeCallbackConstructorCplusStub() writes the callback constructor of the stub class
3121 private void writeCallbackConstructorCplusStub(String newStubClass, boolean callbackExist,
3122 Set<String> callbackClasses, Set<String> methods, InterfaceDecl intDecl) {
3124 println(newStubClass + "::" + newStubClass + "(IoTRMIComm* _rmiComm, int _objectId) {");
3125 println("rmiComm = _rmiComm;");
3126 println("objectId = _objectId;");
3127 // Register the AtomicBoolean variables
3128 for (String method : methods) {
3129 // Generate AtomicBooleans for methods that have return values
3130 String returnType = intDecl.getMethodType(method);
3131 int methodNumId = intDecl.getMethodNumId(method);
3132 if (!returnType.equals("void")) {
3133 println("rmiComm->registerStub(objectId, " + methodNumId + ", &retValueReceived" + methodNumId + ");");
3141 * HELPER: writeDeconstructorCplusStub() writes the deconstructor of the stub class
3143 private void writeDeconstructorCplusStub(String newStubClass, boolean callbackExist, Set<String> callbackClasses) {
3145 println(newStubClass + "::~" + newStubClass + "() {");
3146 println("if (rmiComm != NULL) {");
3147 println("delete rmiComm;");
3148 println("rmiComm = NULL;");
3150 if (callbackExist) {
3151 // We assume that each class only has one callback interface for now
3152 //Iterator it = callbackClasses.iterator();
3153 //String callbackType = (String) it.next();
3154 for (String callbackType : callbackClasses) {
3155 println("for(" + callbackType + "* cb : vecCallbackObj) {");
3156 println("delete cb;");
3157 println("cb = NULL;");
3167 * HELPER: writeCplusMethodCallbackPermission() writes permission checks in stub for callbacks
3169 private void writeCplusMethodCallbackPermission(String intface) {
3171 println("int methodId = IoTRMIObject::getMethodId(method);");
3172 // Get all the different stubs
3173 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3174 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3175 String newIntface = intMeth.getKey();
3176 int newObjectId = getNewIntfaceObjectId(newIntface);
3177 println("if (set" + newObjectId + "Allowed.find(methodId) == set" + newObjectId + "Allowed.end()) {");
3178 println("cerr << \"Callback object for " + intface + " is not allowed to access method: \" << methodId;");
3186 * generateCPlusStubClassesHpp() generate stubs based on the methods list in C++ (.hpp file)
3188 public void generateCPlusStubClassesHpp() throws IOException {
3190 // Create a new directory
3191 String path = createDirectories(dir, subdir);
3192 for (String intface : mapIntfacePTH.keySet()) {
3194 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3195 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3196 // Open a new file to write into
3197 String newIntface = intMeth.getKey();
3198 String newStubClass = newIntface + "_Stub";
3199 FileWriter fw = new FileWriter(path + "/" + newStubClass + ".hpp");
3200 pw = new PrintWriter(new BufferedWriter(fw));
3201 // Write file headers
3202 println("#ifndef _" + newStubClass.toUpperCase() + "_HPP__");
3203 println("#define _" + newStubClass.toUpperCase() + "_HPP__");
3204 println("#include <iostream>");
3205 // Find out if there are callback objects
3206 Set<String> methods = intMeth.getValue();
3207 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
3208 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
3209 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
3210 boolean callbackExist = !callbackClasses.isEmpty();
3211 println("#include <thread>");
3212 println("#include <mutex>");
3213 List<String> stdIncludeClasses = getStandardCplusIncludeClasses();
3214 printIncludeStatements(stdIncludeClasses); println("");
3215 println("#include \"" + newIntface + ".hpp\""); println("");
3216 println("using namespace std;"); println("");
3217 println("class " + newStubClass + " : public " + newIntface); println("{");
3218 println("private:\n");
3219 writePropertiesCplusStub(intface, newIntface, callbackExist, callbackClasses, methods, intDecl);
3220 println("public:\n");
3221 // Add default constructor and destructor
3222 println(newStubClass + "();");
3224 println(newStubClass + "(int _portSend, int _portRecv, const char* _skeletonAddress, int _rev, bool* _bResult);");
3225 println(newStubClass + "(IoTRMIComm* _rmiComm, int _objectId);");
3226 println("~" + newStubClass + "();");
3228 writeMethodDeclCplusStub(methods, intDecl, callbackClasses, newStubClass);
3229 print("}"); println(";");
3232 System.out.println("IoTCompiler: Generated stub class " + newStubClass + ".hpp...");
3239 * writeStubExternalCFunctions() generate external functions for .so file
3241 public void writeStubExternalCFunctions(String newStubClass) throws IOException {
3243 println("extern \"C\" void* create" + newStubClass + "(void** params) {");
3244 println("// Args: int _portSend, int _portRecv, const char* _skeletonAddress, int _rev, bool* _bResult");
3245 println("return new " + newStubClass + "(*((int*) params[0]), *((int*) params[1]), ((string*) params[2])->c_str(), " +
3246 "*((int*) params[3]), (bool*) params[4]);");
3248 println("extern \"C\" void destroy" + newStubClass + "(void* t) {");
3249 println(newStubClass + "* obj = (" + newStubClass + "*) t;");
3250 println("delete obj;");
3252 //println("extern \"C\" void init" + newStubClass + "(void* t) {");
3253 //println(newStubClass + "* obj = (" + newStubClass + "*) t;");
3254 //println("obj->init();");
3255 //println("while(true);");
3261 * generateCPlusStubClassesCpp() generate stubs based on the methods list in C++ (.cpp file)
3263 public void generateCPlusStubClassesCpp() throws IOException {
3265 // Create a new directory
3266 String path = createDirectories(dir, subdir);
3267 for (String intface : mapIntfacePTH.keySet()) {
3269 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3270 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3271 // Open a new file to write into
3272 String newIntface = intMeth.getKey();
3273 String newStubClass = newIntface + "_Stub";
3274 FileWriter fw = new FileWriter(path + "/" + newStubClass + ".cpp");
3275 pw = new PrintWriter(new BufferedWriter(fw));
3276 // Write file headers
3277 println("#include <iostream>");
3278 // Find out if there are callback objects
3279 Set<String> methods = intMeth.getValue();
3280 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
3281 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
3282 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
3283 boolean callbackExist = !callbackClasses.isEmpty();
3284 println("#include \"" + newStubClass + ".hpp\""); println("");
3285 for(String str: callbackClasses) {
3286 if (intface.equals(mainClass))
3287 println("#include \"" + str + "_Skeleton.cpp\"\n");
3289 println("#include \"" + str + "_Skeleton.hpp\"\n");
3291 println("using namespace std;"); println("");
3292 // Add default constructor and destructor
3293 //println(newStubClass + "() { }"); println("");
3294 writeConstructorCplusStub(newStubClass, callbackExist, callbackClasses, methods, intDecl);
3295 writeCallbackConstructorCplusStub(newStubClass, callbackExist, callbackClasses, methods, intDecl);
3296 writeDeconstructorCplusStub(newStubClass, callbackExist, callbackClasses);
3298 writeMethodCplusStub(methods, intDecl, callbackClasses, newStubClass);
3299 // Write external functions for .so file
3300 writeStubExternalCFunctions(newStubClass);
3301 // TODO: Remove this later
3302 if (intface.equals(mainClass)) {
3303 println("int main() {");
3304 println("return 0;");
3308 System.out.println("IoTCompiler: Generated stub class " + newStubClass + ".cpp...");
3315 * HELPER: writePropertiesCplusSkeleton() writes the properties of the skeleton class
3317 private void writePropertiesCplusSkeleton(String intface, boolean callbackExist, Set<String> callbackClasses) {
3319 println(intface + " *mainObj;");
3321 if (callbackExist) {
3322 Iterator it = callbackClasses.iterator();
3323 String callbackType = (String) it.next();
3324 String exchangeType = checkAndGetParamClass(callbackType);
3325 println("// Callback properties");
3326 println("vector<" + exchangeType + "*> vecCallbackObj;");
3328 println("IoTRMIComm *rmiComm;");
3329 println("char* methodBytes;");
3330 println("int methodLen;");
3331 // Keep track of object Ids of all stubs registered to this interface
3332 writePropertiesCplusPermission(intface);
3333 println("// Synchronization variables");
3334 println("bool methodReceived = false;");
3335 println("bool didAlreadyInitWaitInvoke = false;");
3341 * HELPER: writeObjectIdCountInitializationCplus() writes the initialization of objIdCnt variable
3343 private void writeObjectIdCountInitializationCplus(String newSkelClass, boolean callbackExist) {
3346 println("int " + newSkelClass + "::objIdCnt = 0;");
3351 * HELPER: writePermissionInitializationCplus() writes the initialization of permission set
3353 private void writePermissionInitializationCplus(String intface, String newSkelClass, InterfaceDecl intDecl) {
3355 // Keep track of object Ids of all stubs registered to this interface
3356 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3357 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3358 String newIntface = intMeth.getKey();
3359 int newObjectId = getNewIntfaceObjectId(newIntface);
3360 print("set<int> " + newSkelClass + "::set" + newObjectId + "Allowed { ");
3361 Set<String> methodIds = intMeth.getValue();
3363 for (String methodId : methodIds) {
3364 int methodNumId = intDecl.getMethodNumId(methodId);
3365 print(Integer.toString(methodNumId));
3366 // Check if this is the last element (don't print a comma)
3367 if (i != methodIds.size() - 1) {
3378 * HELPER: writeStructPermissionCplusSkeleton() writes permission for struct helper
3380 private void writeStructPermissionCplusSkeleton(Collection<String> methods, InterfaceDecl intDecl, String intface) {
3382 // Use this set to handle two same methodIds
3383 for (String method : methods) {
3384 List<String> methParams = intDecl.getMethodParams(method);
3385 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
3386 // Check for params with structs
3387 for (int i = 0; i < methParams.size(); i++) {
3388 String paramType = methPrmTypes.get(i);
3389 String param = methParams.get(i);
3390 String simpleType = getGenericType(paramType);
3391 if (isStructClass(simpleType)) {
3392 int methodNumId = intDecl.getMethodNumId(method);
3393 String helperMethod = methodNumId + "struct" + i;
3394 int helperMethodNumId = intDecl.getHelperMethodNumId(helperMethod);
3395 // Iterate over interfaces to give permissions to
3396 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3397 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3398 String newIntface = intMeth.getKey();
3399 int newObjectId = getNewIntfaceObjectId(newIntface);
3400 println("set" + newObjectId + "Allowed.insert(" + helperMethodNumId + ");");
3409 * HELPER: writeConstructorCplusSkeleton() writes the constructor of the skeleton class
3411 private void writeConstructorCplusSkeleton(String newSkelClass, String intface, boolean callbackExist, InterfaceDecl intDecl, Collection<String> methods) {
3413 println(newSkelClass + "::" + newSkelClass + "(" + intface + " *_mainObj, int _portSend, int _portRecv) {");
3414 println("bool _bResult = false;");
3415 println("mainObj = _mainObj;");
3416 println("rmiComm = new IoTRMICommServer(_portSend, _portRecv, &_bResult);");
3417 println("IoTRMIUtil::mapSkel->insert(make_pair(_mainObj, this));");
3418 println("IoTRMIUtil::mapSkelId->insert(make_pair(_mainObj, objectId));");
3419 println("rmiComm->registerSkeleton(objectId, &methodReceived);");
3420 writeStructPermissionCplusSkeleton(methods, intDecl, intface);
3421 println("thread th1 (&" + newSkelClass + "::___waitRequestInvokeMethod, this, this);");
3422 println("th1.join();");
3428 * HELPER: writeCallbackConstructorCplusSkeleton() writes the callback constructor of the skeleton class
3430 private void writeCallbackConstructorCplusSkeleton(String newSkelClass, String intface, boolean callbackExist, InterfaceDecl intDecl, Collection<String> methods) {
3432 println(newSkelClass + "::" + newSkelClass + "(" + intface + " *_mainObj, IoTRMIComm *_rmiComm, int _objectId) {");
3433 println("bool _bResult = false;");
3434 println("mainObj = _mainObj;");
3435 println("rmiComm = _rmiComm;");
3436 println("objectId = _objectId;");
3437 println("rmiComm->registerSkeleton(objectId, &methodReceived);");
3438 writeStructPermissionCplusSkeleton(methods, intDecl, intface);
3444 * HELPER: writeDeconstructorCplusSkeleton() writes the deconstructor of the skeleton class
3446 private void writeDeconstructorCplusSkeleton(String newSkelClass, boolean callbackExist, Set<String> callbackClasses) {
3448 println(newSkelClass + "::~" + newSkelClass + "() {");
3449 println("if (rmiComm != NULL) {");
3450 println("delete rmiComm;");
3451 println("rmiComm = NULL;");
3453 if (callbackExist) {
3454 // We assume that each class only has one callback interface for now
3455 //Iterator it = callbackClasses.iterator();
3456 //String callbackType = (String) it.next();
3457 for (String callbackType : callbackClasses) {
3458 String exchangeType = checkAndGetParamClass(callbackType);
3459 println("for(" + exchangeType + "* cb : vecCallbackObj) {");
3460 println("delete cb;");
3461 println("cb = NULL;");
3471 * HELPER: writeStdMethodBodyCplusSkeleton() writes the standard method body in the skeleton class
3473 private void writeStdMethodBodyCplusSkeleton(List<String> methParams, String methodId, String methodType) {
3475 if (methodType.equals("void"))
3476 print("mainObj->" + methodId + "(");
3478 print("return mainObj->" + methodId + "(");
3479 for (int i = 0; i < methParams.size(); i++) {
3481 print(getSimpleIdentifier(methParams.get(i)));
3482 // Check if this is the last element (don't print a comma)
3483 if (i != methParams.size() - 1) {
3492 * HELPER: writeMethodDeclCplusSkeleton() writes the method declaration of the skeleton class
3494 private void writeMethodDeclCplusSkeleton(Collection<String> methods, InterfaceDecl intDecl,
3495 Set<String> callbackClasses) {
3497 for (String method : methods) {
3499 List<String> methParams = intDecl.getMethodParams(method);
3500 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
3501 String methodId = intDecl.getMethodId(method);
3502 String methodType = checkAndGetCplusType(intDecl.getMethodType(method));
3503 print(methodType + " " + methodId + "(");
3504 boolean isCallbackMethod = false;
3505 String callbackType = null;
3506 for (int i = 0; i < methParams.size(); i++) {
3508 String origParamType = methPrmTypes.get(i);
3509 if (callbackClasses.contains(origParamType)) { // Check if this has callback object
3510 isCallbackMethod = true;
3511 callbackType = origParamType;
3513 String paramType = checkAndGetParamClass(methPrmTypes.get(i));
3514 String methPrmType = checkAndGetCplusType(paramType);
3515 String methParamComplete = checkAndGetCplusArray(methPrmType, methParams.get(i));
3516 print(methParamComplete);
3517 // Check if this is the last element (don't print a comma)
3518 if (i != methParams.size() - 1) {
3528 * HELPER: writeMethodCplusSkeleton() writes the method of the skeleton class
3530 private void writeMethodCplusSkeleton(Collection<String> methods, InterfaceDecl intDecl,
3531 Set<String> callbackClasses, boolean callbackSkeleton, String intface, String newSkelClass) {
3533 for (String method : methods) {
3535 List<String> methParams = intDecl.getMethodParams(method);
3536 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
3537 String methodId = intDecl.getMethodId(method);
3538 String methodType = checkAndGetCplusType(intDecl.getMethodType(method));
3539 print(methodType + " " + newSkelClass + "::" + methodId + "(");
3540 boolean isCallbackMethod = false;
3541 String callbackType = null;
3542 for (int i = 0; i < methParams.size(); i++) {
3544 String origParamType = methPrmTypes.get(i);
3545 if (callbackClasses.contains(origParamType)) { // Check if this has callback object
3546 isCallbackMethod = true;
3547 callbackType = origParamType;
3549 String paramType = checkAndGetParamClass(methPrmTypes.get(i));
3550 String methPrmType = checkAndGetCplusType(paramType);
3551 String methParamComplete = checkAndGetCplusArray(methPrmType, methParams.get(i));
3552 print(methParamComplete);
3553 // Check if this is the last element (don't print a comma)
3554 if (i != methParams.size() - 1) {
3559 // Now, write the body of skeleton!
3560 writeStdMethodBodyCplusSkeleton(methParams, methodId, intDecl.getMethodType(method));
3567 * HELPER: writeCallbackCplusNumStubs() writes the numStubs variable
3569 private void writeCallbackCplusNumStubs(List<String> methParams, List<String> methPrmTypes, String callbackType) {
3571 for (int i = 0; i < methParams.size(); i++) {
3572 String paramType = methPrmTypes.get(i);
3573 String param = methParams.get(i);
3574 //if (callbackType.equals(paramType)) {
3575 if (checkCallbackType(paramType, callbackType)) // Check if this has callback object
3576 //println("int numStubs" + i + " = 0;");
3577 println("vector<int> numStubIdArray" + i + ";");
3583 * HELPER: writeCallbackInstantiationCplusStubGeneration() writes the instantiation of callback stubs
3585 private void writeCallbackInstantiationCplusStubGeneration(String exchParamType) {
3587 //println("int objIdRecv = (int[]) paramObj[0];");
3588 println(exchParamType + "* newStub = NULL;");
3589 println("auto it = IoTRMIUtil::mapStub->find(objIdRecv);");
3590 println("if (it == IoTRMIUtil::mapStub->end()) {");
3591 println("newStub = new " + exchParamType + "_Stub(rmiComm, objIdRecv);");
3592 println("IoTRMIUtil::mapStub->insert(make_pair(objIdRecv, newStub));");
3593 println("rmiComm->setObjectIdCounter(objIdRecv);");
3594 println("rmiComm->decrementObjectIdCounter();");
3595 println("skel->vecCallbackObj.push_back(newStub);");
3598 println("newStub = (" + exchParamType + "_Stub*) it->second;");
3604 * HELPER: writeCallbackCplusStubGeneration() writes the callback stub generation part
3606 private void writeCallbackCplusStubGeneration(List<String> methParams, List<String> methPrmTypes, String callbackType) {
3608 // Iterate over callback objects
3609 for (int i = 0; i < methParams.size(); i++) {
3610 String paramType = methPrmTypes.get(i);
3611 String param = methParams.get(i);
3612 // Generate a loop if needed
3613 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
3614 String exchParamType = checkAndGetParamClass(getGenericType(paramType));
3615 if (isArrayOrList(paramType, param)) {
3616 println("vector<" + exchParamType + "*> stub" + i + ";");
3617 println("for (int i = 0; i < numStubIdArray" + i + ".size(); i++) {");
3618 println("int objIdRecv = numStubIdArray" + i + "[i];");
3619 writeCallbackInstantiationCplusStubGeneration(exchParamType);
3620 println("stub" + i + ".push_back(newStub);");
3623 println("int objIdRecv = numStubIdArray" + i + "[0];");
3624 writeCallbackInstantiationCplusStubGeneration(exchParamType);
3625 println(exchParamType + "* stub" + i + " = newStub;");
3633 * HELPER: checkAndWriteEnumTypeCplusSkeleton() writes the enum type (convert from enum to int)
3635 private void checkAndWriteEnumTypeCplusSkeleton(List<String> methParams, List<String> methPrmTypes) {
3637 // Iterate and find enum declarations
3638 for (int i = 0; i < methParams.size(); i++) {
3639 String paramType = methPrmTypes.get(i);
3640 String param = methParams.get(i);
3641 String simpleType = getGenericType(paramType);
3642 if (isEnumClass(simpleType)) {
3643 // Check if this is enum type
3644 if (isArrayOrList(paramType, param)) { // An array
3645 println("int len" + i + " = paramEnumInt" + i + ".size();");
3646 println("vector<" + simpleType + "> paramEnum" + i + "(len" + i + ");");
3647 println("for (int i=0; i < len" + i + "; i++) {");
3648 println("paramEnum" + i + "[i] = (" + simpleType + ") paramEnumInt" + i + "[i];");
3650 } else { // Just one element
3651 println(simpleType + " paramEnum" + i + ";");
3652 println("paramEnum" + i + " = (" + simpleType + ") paramEnumInt" + i + "[0];");
3660 * HELPER: checkAndWriteEnumRetTypeCplusSkeleton() writes the enum return type (convert from enum to int)
3662 private void checkAndWriteEnumRetTypeCplusSkeleton(String retType) {
3664 // Strips off array "[]" for return type
3665 String pureType = getSimpleArrayType(getGenericType(retType));
3666 // Take the inner type of generic
3667 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
3668 pureType = getGenericType(retType);
3669 if (isEnumClass(pureType)) {
3670 // Check if this is enum type
3672 if (isArrayOrList(retType, retType)) { // An array
3673 println("int retLen = retEnum.size();");
3674 println("vector<int> retEnumInt(retLen);");
3675 println("for (int i=0; i < retLen; i++) {");
3676 println("retEnumInt[i] = (int) retEnum[i];");
3678 } else { // Just one element
3679 println("vector<int> retEnumInt(1);");
3680 println("retEnumInt[0] = (int) retEnum;");
3687 * HELPER: writeMethodInputParameters() writes the parameter variables for C++ skeleton
3689 private void writeMethodInputParameters(List<String> methParams, List<String> methPrmTypes,
3690 Set<String> callbackClasses, String methodId) {
3692 print(methodId + "(");
3693 for (int i = 0; i < methParams.size(); i++) {
3694 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
3695 if (callbackClasses.contains(paramType))
3697 else if (isEnumClass(getGenericType(paramType))) // Check if this is enum type
3698 print("paramEnum" + i);
3699 else if (isStructClass(getGenericType(paramType))) // Struct type
3700 print("paramStruct" + i);
3702 print(getSimpleIdentifier(methParams.get(i)));
3703 if (i != methParams.size() - 1) {
3712 * HELPER: writeMethodHelperReturnCplusSkeleton() writes the return statement part in skeleton
3714 private void writeMethodHelperReturnCplusSkeleton(InterfaceDecl intDecl, List<String> methParams,
3715 List<String> methPrmTypes, String method, boolean isCallbackMethod, String callbackType,
3716 String methodId, Set<String> callbackClasses) {
3718 println("rmiComm->getMethodParams(paramCls, numParam, paramObj, localMethodBytes);");
3719 if (isCallbackMethod)
3720 writeCallbackCplusStubGeneration(methParams, methPrmTypes, callbackType);
3721 checkAndWriteEnumTypeCplusSkeleton(methParams, methPrmTypes);
3722 writeStructMembersInitCplusSkeleton(intDecl, methParams, methPrmTypes, method);
3723 // Check if this is "void"
3724 String retType = intDecl.getMethodType(method);
3725 // Check if this is "void"
3726 if (retType.equals("void")) {
3727 writeMethodInputParameters(methParams, methPrmTypes, callbackClasses, methodId);
3728 } else { // We do have a return value
3729 if (isEnumClass(getSimpleArrayType(getGenericType(retType)))) // Enum type
3730 print(checkAndGetCplusType(retType) + " retEnum = ");
3731 else if (isStructClass(getSimpleArrayType(getGenericType(retType)))) // Struct type
3732 print(checkAndGetCplusType(retType) + " retStruct = ");
3734 print(checkAndGetCplusType(retType) + " retVal = ");
3735 writeMethodInputParameters(methParams, methPrmTypes, callbackClasses, methodId);
3736 checkAndWriteEnumRetTypeCplusSkeleton(retType);
3737 if (isStructClass(getSimpleArrayType(getGenericType(retType)))) // Struct type
3738 writeStructReturnCplusSkeleton(getSimpleArrayType(getGenericType(retType)), retType);
3739 if (isEnumClass(getSimpleArrayType(getGenericType(retType)))) // Enum type
3740 println("void* retObj = &retEnumInt;");
3742 if (!isStructClass(getSimpleArrayType(getGenericType(retType)))) // Struct type
3743 println("void* retObj = &retVal;");
3744 String retTypeC = checkAndGetCplusType(retType);
3745 if (isStructClass(getSimpleArrayType(getGenericType(retType)))) // Struct type
3746 println("rmiComm->sendReturnObj(retObj, retCls, numRetObj, localMethodBytes);");
3748 println("rmiComm->sendReturnObj(retObj, \"" + checkAndGetCplusRetClsType(getEnumType(retType)) + "\", localMethodBytes);");
3754 * HELPER: writeStdMethodHelperBodyCplusSkeleton() writes the standard method body helper in the skeleton class
3756 private void writeStdMethodHelperBodyCplusSkeleton(InterfaceDecl intDecl, List<String> methParams,
3757 List<String> methPrmTypes, String method, String methodId, Set<String> callbackClasses) {
3759 // Generate array of parameter types
3760 boolean isCallbackMethod = false;
3761 String callbackType = null;
3762 print("string paramCls[] = { ");
3763 for (int i = 0; i < methParams.size(); i++) {
3764 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
3765 if (callbackClasses.contains(paramType)) {
3766 isCallbackMethod = true;
3767 callbackType = paramType;
3769 } else { // Generate normal classes if it's not a callback object
3770 String paramTypeC = checkAndGetCplusArgClsType(methPrmTypes.get(i), methParams.get(i));
3771 print("\"" + paramTypeC + "\"");
3773 if (i != methParams.size() - 1) {
3778 println("int numParam = " + methParams.size() + ";");
3779 if (isCallbackMethod)
3780 writeCallbackCplusNumStubs(methParams, methPrmTypes, callbackType);
3781 // Generate parameters
3782 for (int i = 0; i < methParams.size(); i++) {
3783 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
3784 if (!callbackClasses.contains(paramType)) {
3785 String methParamType = methPrmTypes.get(i);
3786 if (isEnumClass(getSimpleArrayType(getGenericType(methParamType)))) {
3787 // Check if this is enum type
3788 println("vector<int> paramEnumInt" + i + ";");
3790 String methPrmType = checkAndGetCplusType(methParamType);
3791 String methParamComplete = checkAndGetCplusArray(methPrmType, methParams.get(i));
3792 println(methParamComplete + ";");
3796 // Generate array of parameter objects
3797 print("void* paramObj[] = { ");
3798 for (int i = 0; i < methParams.size(); i++) {
3799 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
3800 if (callbackClasses.contains(paramType))
3801 print("&numStubIdArray" + i);
3802 else if (isEnumClass(getGenericType(paramType))) // Check if this is enum type
3803 print("¶mEnumInt" + i);
3805 print("&" + getSimpleIdentifier(methParams.get(i)));
3806 if (i != methParams.size() - 1) {
3811 // Write the return value part
3812 writeMethodHelperReturnCplusSkeleton(intDecl, methParams, methPrmTypes, method, isCallbackMethod,
3813 callbackType, methodId, callbackClasses);
3818 * HELPER: writeStructMembersCplusSkeleton() writes member parameters of struct
3820 private void writeStructMembersCplusSkeleton(String simpleType, String paramType,
3821 String param, String method, InterfaceDecl intDecl, int iVar) {
3823 // Get the struct declaration for this struct and generate initialization code
3824 StructDecl structDecl = getStructDecl(simpleType);
3825 List<String> memTypes = structDecl.getMemberTypes(simpleType);
3826 List<String> members = structDecl.getMembers(simpleType);
3827 int methodNumId = intDecl.getMethodNumId(method);
3828 String counter = "struct" + methodNumId + "Size" + iVar;
3830 if (isArrayOrList(paramType, param)) { // An array or list
3831 for (int i = 0; i < members.size(); i++) {
3832 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
3833 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
3834 println(getSimpleType(getEnumType(prmType)) + " param" + iVar + i + "[" + counter + "];");
3836 } else { // Just one struct element
3837 for (int i = 0; i < members.size(); i++) {
3838 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
3839 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
3840 println(getSimpleType(getEnumType(prmType)) + " param" + iVar + i + ";");
3843 if (isArrayOrList(paramType, param)) { // An array or list
3844 println("for(int i = 0; i < " + counter + "; i++) {");
3846 if (isArrayOrList(paramType, param)) { // An array or list
3847 for (int i = 0; i < members.size(); i++) {
3848 String prmTypeC = checkAndGetCplusArgClsType(memTypes.get(i), members.get(i));
3849 println("paramCls[pos] = \"" + prmTypeC + "\";");
3850 println("paramObj[pos++] = ¶m" + iVar + i + "[i];");
3853 } else { // Just one struct element
3854 for (int i = 0; i < members.size(); i++) {
3855 String prmTypeC = checkAndGetCplusArgClsType(memTypes.get(i), members.get(i));
3856 println("paramCls[pos] = \"" + prmTypeC + "\";");
3857 println("paramObj[pos++] = ¶m" + iVar + i + ";");
3864 * HELPER: writeStructMembersInitCplusSkeleton() writes member parameters initialization of struct
3866 private void writeStructMembersInitCplusSkeleton(InterfaceDecl intDecl, List<String> methParams,
3867 List<String> methPrmTypes, String method) {
3869 for (int i = 0; i < methParams.size(); i++) {
3870 String paramType = methPrmTypes.get(i);
3871 String param = methParams.get(i);
3872 String simpleType = getGenericType(paramType);
3873 if (isStructClass(simpleType)) {
3874 int methodNumId = intDecl.getMethodNumId(method);
3875 String counter = "struct" + methodNumId + "Size" + i;
3877 if (isArrayOrList(paramType, param)) { // An array or list
3878 println("vector<" + simpleType + "> paramStruct" + i + "(" + counter + ");");
3880 println(simpleType + " paramStruct" + i + ";");
3881 // Initialize members
3882 StructDecl structDecl = getStructDecl(simpleType);
3883 List<String> members = structDecl.getMembers(simpleType);
3884 List<String> memTypes = structDecl.getMemberTypes(simpleType);
3885 if (isArrayOrList(paramType, param)) { // An array or list
3886 println("for(int i = 0; i < " + counter + "; i++) {");
3887 for (int j = 0; j < members.size(); j++) {
3888 print("paramStruct" + i + "[i]." + getSimpleIdentifier(members.get(j)));
3889 println(" = param" + i + j + "[i];");
3892 } else { // Just one struct element
3893 for (int j = 0; j < members.size(); j++) {
3894 print("paramStruct" + i + "." + getSimpleIdentifier(members.get(j)));
3895 println(" = param" + i + j + ";");
3904 * HELPER: writeStructReturnCplusSkeleton() writes parameters of struct for return statement
3906 private void writeStructReturnCplusSkeleton(String simpleType, String retType) {
3908 // Minimum retLen is 1 if this is a single struct object
3909 if (isArrayOrList(retType, retType))
3910 println("int retLen = retStruct.size();");
3911 else // Just single struct object
3912 println("int retLen = 1;");
3913 println("void* retLenObj = &retLen;");
3914 println("rmiComm->sendReturnObj(retLenObj, \"int\", localMethodBytes);");
3915 int numMem = getNumOfMembers(simpleType);
3916 println("int numRetObj = " + numMem + "*retLen;");
3917 println("string retCls[numRetObj];");
3918 println("void* retObj[numRetObj];");
3919 println("int retPos = 0;");
3920 // Get the struct declaration for this struct and generate initialization code
3921 StructDecl structDecl = getStructDecl(simpleType);
3922 List<String> memTypes = structDecl.getMemberTypes(simpleType);
3923 List<String> members = structDecl.getMembers(simpleType);
3924 if (isArrayOrList(retType, retType)) { // An array or list
3925 println("for(int i = 0; i < retLen; i++) {");
3926 for (int i = 0; i < members.size(); i++) {
3927 String prmTypeC = checkAndGetCplusArgClsType(memTypes.get(i), members.get(i));
3928 println("retCls[retPos] = \"" + prmTypeC + "\";");
3929 print("retObj[retPos++] = &retStruct[i].");
3930 print(getEnumParam(memTypes.get(i), getSimpleIdentifier(members.get(i)), i));
3934 } else { // Just one struct element
3935 for (int i = 0; i < members.size(); i++) {
3936 String prmTypeC = checkAndGetCplusArgClsType(memTypes.get(i), members.get(i));
3937 println("retCls[retPos] = \"" + prmTypeC + "\";");
3938 print("retObj[retPos++] = &retStruct.");
3939 print(getEnumParam(memTypes.get(i), getSimpleIdentifier(members.get(i)), i));
3948 * HELPER: writeMethodHelperStructCplusSkeleton() writes the struct in skeleton
3950 private void writeMethodHelperStructCplusSkeleton(InterfaceDecl intDecl, List<String> methParams,
3951 List<String> methPrmTypes, String method, String methodId, Set<String> callbackClasses) {
3953 // Generate array of parameter objects
3954 boolean isCallbackMethod = false;
3955 String callbackType = null;
3956 print("int numParam = ");
3957 writeLengthStructParamClassSkeleton(methParams, methPrmTypes, method, intDecl);
3959 println("string paramCls[numParam];");
3960 println("void* paramObj[numParam];");
3961 println("int pos = 0;");
3962 // Iterate again over the parameters
3963 for (int i = 0; i < methParams.size(); i++) {
3964 String paramType = methPrmTypes.get(i);
3965 String param = methParams.get(i);
3966 String simpleType = getGenericType(paramType);
3967 if (isStructClass(simpleType)) {
3968 writeStructMembersCplusSkeleton(simpleType, paramType, param, method, intDecl, i);
3970 String prmType = returnGenericCallbackType(methPrmTypes.get(i));
3971 if (callbackClasses.contains(prmType)) {
3972 isCallbackMethod = true;
3973 callbackType = prmType;
3974 //println("int numStubs" + i + " = 0;");
3975 println("vector<int> numStubIdArray" + i + ";");
3976 println("paramCls[pos] = \"int*\";");
3977 println("paramObj[pos++] = &numStubIdArray" + i + ";");
3978 } else { // Generate normal classes if it's not a callback object
3979 String paramTypeC = checkAndGetCplusType(methPrmTypes.get(i));
3980 if (isEnumClass(getGenericType(paramTypeC))) { // Check if this is enum type
3981 println("vector<int> paramEnumInt" + i + ";");
3983 String methParamComplete = checkAndGetCplusArray(paramTypeC, methParams.get(i));
3984 println(methParamComplete + ";");
3986 String prmTypeC = checkAndGetCplusArgClsType(methPrmTypes.get(i), methParams.get(i));
3987 println("paramCls[pos] = \"" + prmTypeC + "\";");
3988 if (isEnumClass(getGenericType(paramType))) // Check if this is enum type
3989 println("paramObj[pos++] = ¶mEnumInt" + i + ";");
3991 println("paramObj[pos++] = &" + getSimpleIdentifier(methParams.get(i)) + ";");
3995 // Write the return value part
3996 writeMethodHelperReturnCplusSkeleton(intDecl, methParams, methPrmTypes, method, isCallbackMethod,
3997 callbackType, methodId, callbackClasses);
4002 * HELPER: writeMethodHelperDeclCplusSkeleton() writes the method helper declarations of the skeleton class
4004 private void writeMethodHelperDeclCplusSkeleton(Collection<String> methods, InterfaceDecl intDecl,
4005 Set<String> callbackClasses, String newSkelClass) {
4007 // Use this set to handle two same methodIds
4008 Set<String> uniqueMethodIds = new HashSet<String>();
4009 for (String method : methods) {
4011 List<String> methParams = intDecl.getMethodParams(method);
4012 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4013 if (isStructPresent(methParams, methPrmTypes)) { // Treat struct differently
4014 String methodId = intDecl.getMethodId(method);
4016 String helperMethod = methodId;
4017 if (uniqueMethodIds.contains(methodId))
4018 helperMethod = helperMethod + intDecl.getMethodNumId(method);
4020 uniqueMethodIds.add(methodId);
4021 String retType = intDecl.getMethodType(method);
4022 print(helperMethod + "(");
4023 boolean begin = true;
4024 for (int i = 0; i < methParams.size(); i++) { // Print size variables
4025 String paramType = methPrmTypes.get(i);
4026 String param = methParams.get(i);
4027 String simpleType = getGenericType(paramType);
4028 if (isStructClass(simpleType)) {
4029 if (!begin) // Generate comma for not the beginning variable
4033 int methodNumId = intDecl.getMethodNumId(method);
4034 print("int struct" + methodNumId + "Size" + i);
4037 println(", " + newSkelClass + "* skel);");
4039 String methodId = intDecl.getMethodId(method);
4041 String helperMethod = methodId;
4042 if (uniqueMethodIds.contains(methodId))
4043 helperMethod = helperMethod + intDecl.getMethodNumId(method);
4045 uniqueMethodIds.add(methodId);
4046 // Check if this is "void"
4047 String retType = intDecl.getMethodType(method);
4048 println(helperMethod + "(" + newSkelClass + "* skel);");
4051 // Write method helper for structs
4052 writeMethodHelperStructDeclSetupCplusSkeleton(methods, intDecl, newSkelClass);
4057 * HELPER: writeMethodHelperStructDeclSetupCplusSkeleton() writes the struct method helper declaration in skeleton class
4059 private void writeMethodHelperStructDeclSetupCplusSkeleton(Collection<String> methods,
4060 InterfaceDecl intDecl, String newSkelClass) {
4062 // Use this set to handle two same methodIds
4063 for (String method : methods) {
4065 List<String> methParams = intDecl.getMethodParams(method);
4066 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4067 // Check for params with structs
4068 for (int i = 0; i < methParams.size(); i++) {
4069 String paramType = methPrmTypes.get(i);
4070 String param = methParams.get(i);
4071 String simpleType = getGenericType(paramType);
4072 if (isStructClass(simpleType)) {
4073 int methodNumId = intDecl.getMethodNumId(method);
4075 String helperMethod = methodNumId + "struct" + i;
4076 println(helperMethod + "(" + newSkelClass + "* skel);");
4084 * HELPER: writeMethodBytesCopy() writes the methodBytes copy part in C++ skeleton
4086 private void writeMethodBytesCopy() {
4088 println("char* localMethodBytes = new char[methodLen];");
4089 println("memcpy(localMethodBytes, skel->methodBytes, methodLen);");
4090 println("didGetMethodBytes.exchange(true);");
4095 * HELPER: writeMethodHelperCplusSkeleton() writes the method helper of the skeleton class
4097 private void writeMethodHelperCplusSkeleton(Collection<String> methods, InterfaceDecl intDecl,
4098 Set<String> callbackClasses, String newSkelClass) {
4100 // Use this set to handle two same methodIds
4101 Set<String> uniqueMethodIds = new HashSet<String>();
4102 for (String method : methods) {
4104 List<String> methParams = intDecl.getMethodParams(method);
4105 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4106 if (isStructPresent(methParams, methPrmTypes)) { // Treat struct differently
4107 String methodId = intDecl.getMethodId(method);
4108 print("void " + newSkelClass + "::___");
4109 String helperMethod = methodId;
4110 if (uniqueMethodIds.contains(methodId))
4111 helperMethod = helperMethod + intDecl.getMethodNumId(method);
4113 uniqueMethodIds.add(methodId);
4114 String retType = intDecl.getMethodType(method);
4115 print(helperMethod + "(");
4116 boolean begin = true;
4117 for (int i = 0; i < methParams.size(); i++) { // Print size variables
4118 String paramType = methPrmTypes.get(i);
4119 String param = methParams.get(i);
4120 String simpleType = getGenericType(paramType);
4121 if (isStructClass(simpleType)) {
4122 if (!begin) // Generate comma for not the beginning variable
4126 int methodNumId = intDecl.getMethodNumId(method);
4127 print("int struct" + methodNumId + "Size" + i);
4130 println(", " + newSkelClass + "* skel) {");
4131 writeMethodBytesCopy();
4132 writeMethodHelperStructCplusSkeleton(intDecl, methParams, methPrmTypes, method, methodId, callbackClasses);
4133 println("delete[] localMethodBytes;");
4136 String methodId = intDecl.getMethodId(method);
4137 print("void " + newSkelClass + "::___");
4138 String helperMethod = methodId;
4139 if (uniqueMethodIds.contains(methodId))
4140 helperMethod = helperMethod + intDecl.getMethodNumId(method);
4142 uniqueMethodIds.add(methodId);
4143 // Check if this is "void"
4144 String retType = intDecl.getMethodType(method);
4145 println(helperMethod + "(" + newSkelClass + "* skel) {");
4146 writeMethodBytesCopy();
4147 // Now, write the helper body of skeleton!
4148 writeStdMethodHelperBodyCplusSkeleton(intDecl, methParams, methPrmTypes, method, methodId, callbackClasses);
4149 println("delete[] localMethodBytes;");
4153 // Write method helper for structs
4154 writeMethodHelperStructSetupCplusSkeleton(methods, intDecl, newSkelClass);
4159 * HELPER: writeMethodHelperStructSetupCplusSkeleton() writes the method helper of struct in skeleton class
4161 private void writeMethodHelperStructSetupCplusSkeleton(Collection<String> methods,
4162 InterfaceDecl intDecl, String newSkelClass) {
4164 // Use this set to handle two same methodIds
4165 for (String method : methods) {
4167 List<String> methParams = intDecl.getMethodParams(method);
4168 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4169 // Check for params with structs
4170 for (int i = 0; i < methParams.size(); i++) {
4171 String paramType = methPrmTypes.get(i);
4172 String param = methParams.get(i);
4173 String simpleType = getGenericType(paramType);
4174 if (isStructClass(simpleType)) {
4175 int methodNumId = intDecl.getMethodNumId(method);
4176 print("int " + newSkelClass + "::___");
4177 String helperMethod = methodNumId + "struct" + i;
4178 println(helperMethod + "(" + newSkelClass + "* skel) {");
4179 // Now, write the helper body of skeleton!
4180 writeMethodBytesCopy();
4181 println("string paramCls[] = { \"int\" };");
4182 println("int numParam = 1;");
4183 println("int param0 = 0;");
4184 println("void* paramObj[] = { ¶m0 };");
4185 println("rmiComm->getMethodParams(paramCls, numParam, paramObj, localMethodBytes);");
4186 println("return param0;");
4187 println("delete[] localMethodBytes;");
4196 * HELPER: writeMethodHelperStructSetupCplusCallbackSkeleton() writes the method helper of struct in skeleton class
4198 private void writeMethodHelperStructSetupCplusCallbackSkeleton(Collection<String> methods,
4199 InterfaceDecl intDecl) {
4201 // Use this set to handle two same methodIds
4202 for (String method : methods) {
4204 List<String> methParams = intDecl.getMethodParams(method);
4205 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4206 // Check for params with structs
4207 for (int i = 0; i < methParams.size(); i++) {
4208 String paramType = methPrmTypes.get(i);
4209 String param = methParams.get(i);
4210 String simpleType = getGenericType(paramType);
4211 if (isStructClass(simpleType)) {
4212 int methodNumId = intDecl.getMethodNumId(method);
4214 String helperMethod = methodNumId + "struct" + i;
4215 println(helperMethod + "(IoTRMIObject* rmiObj) {");
4216 // Now, write the helper body of skeleton!
4217 println("string paramCls[] = { \"int\" };");
4218 println("int numParam = 1;");
4219 println("int param0 = 0;");
4220 println("void* paramObj[] = { ¶m0 };");
4221 println("rmiComm->getMethodParams(paramCls, numParam, paramObj, localMethodBytes);");
4222 println("return param0;");
4231 * HELPER: writeCplusMethodPermission() writes permission checks in skeleton
4233 private void writeCplusMethodPermission(String intface) {
4235 // Get all the different stubs
4236 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
4237 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
4238 String newIntface = intMeth.getKey();
4239 int newObjectId = getNewIntfaceObjectId(newIntface);
4240 println("if (_objectId == objectId) {");
4241 println("if (set" + newObjectId + "Allowed.find(methodId) == set" + newObjectId + "Allowed.end()) {");
4242 println("cerr << \"Object with object Id: \" << _objectId << \" is not allowed to access method: \" << methodId << endl;");
4247 println("continue;");
4254 * HELPER: writeCplusWaitRequestInvokeMethod() writes the main loop of the skeleton class
4256 private void writeCplusWaitRequestInvokeMethod(Collection<String> methods, InterfaceDecl intDecl,
4257 boolean callbackExist, String intface, String newSkelClass) {
4259 // Use this set to handle two same methodIds
4260 Set<String> uniqueMethodIds = new HashSet<String>();
4261 println("void " + newSkelClass + "::___waitRequestInvokeMethod(" + newSkelClass + "* skel) {");
4262 // Write variables here if we have callbacks or enums or structs
4263 writeCountVarStructSkeleton(methods, intDecl);
4264 println("skel->didAlreadyInitWaitInvoke = true;");
4265 println("while (true) {");
4266 println("if (!methodReceived) {");
4267 println("continue;");
4269 println("skel->methodBytes = skel->rmiComm->getMethodBytes();");
4270 println("skel->methodLen = skel->rmiComm->getMethodLength();");
4271 println("methodReceived = false;");
4272 println("int _objectId = skel->rmiComm->getObjectId(skel->methodBytes);");
4273 println("int methodId = skel->rmiComm->getMethodId(skel->methodBytes);");
4274 // Generate permission check
4275 writeCplusMethodPermission(intface);
4276 println("switch (methodId) {");
4277 // Print methods and method Ids
4278 for (String method : methods) {
4279 String methodId = intDecl.getMethodId(method);
4280 int methodNumId = intDecl.getMethodNumId(method);
4281 println("case " + methodNumId + ": {");
4282 print("thread th" + methodNumId + " (&" + newSkelClass + "::___");
4283 String helperMethod = methodId;
4284 if (uniqueMethodIds.contains(methodId))
4285 helperMethod = helperMethod + methodNumId;
4287 uniqueMethodIds.add(methodId);
4288 print(helperMethod + ", std::ref(skel), ");
4289 boolean structExists = writeInputCountVarStructCplusSkeleton(method, intDecl);
4293 println("th" + methodNumId + ".detach(); break;");
4296 writeMethodCallStructCplusSkeleton(methods, intDecl);
4297 println("default: ");
4298 println("cerr << \"Method Id \" << methodId << \" not recognized!\" << endl;");
4307 * generateCplusSkeletonClassHpp() generate skeletons based on the methods list in C++ (.hpp file)
4309 public void generateCplusSkeletonClassHpp() throws IOException {
4311 // Create a new directory
4312 String path = createDirectories(dir, subdir);
4313 for (String intface : mapIntfacePTH.keySet()) {
4314 // Open a new file to write into
4315 String newSkelClass = intface + "_Skeleton";
4316 FileWriter fw = new FileWriter(path + "/" + newSkelClass + ".hpp");
4317 pw = new PrintWriter(new BufferedWriter(fw));
4318 // Write file headers
4319 println("#ifndef _" + newSkelClass.toUpperCase() + "_HPP__");
4320 println("#define _" + newSkelClass.toUpperCase() + "_HPP__");
4321 println("#include <iostream>");
4322 println("#include \"" + intface + ".hpp\"\n");
4323 // Pass in set of methods and get import classes
4324 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4325 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
4326 List<String> methods = intDecl.getMethods();
4327 List<String> stdIncludeClasses = getStandardCplusIncludeClasses();
4328 printIncludeStatements(stdIncludeClasses); println("");
4329 println("using namespace std;\n");
4330 // Find out if there are callback objects
4331 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
4332 boolean callbackExist = !callbackClasses.isEmpty();
4333 // Write class header
4334 println("class " + newSkelClass + " : public " + intface); println("{");
4335 println("private:\n");
4337 writePropertiesCplusSkeleton(intface, callbackExist, callbackClasses);
4338 println("public:\n");
4339 // Write constructors
4340 println(newSkelClass + "();");
4341 println(newSkelClass + "(" + intface + "*_mainObj, int _portSend, int _portRecv);");
4342 println(newSkelClass + "(" + intface + "*_mainObj, IoTRMIComm *rmiComm, int _objectId);");
4343 // Write deconstructor
4344 println("~" + newSkelClass + "();");
4345 // Write method declarations
4346 println("bool didInitWaitInvoke();");
4347 writeMethodDeclCplusSkeleton(methods, intDecl, callbackClasses);
4348 // Write method helper declarations
4349 writeMethodHelperDeclCplusSkeleton(methods, intDecl, callbackClasses, newSkelClass);
4350 // Write waitRequestInvokeMethod() declaration - main loop
4351 println("void ___waitRequestInvokeMethod(" + newSkelClass + "* skel);");
4353 writePermissionInitializationCplus(intface, newSkelClass, intDecl);
4356 System.out.println("IoTCompiler: Generated skeleton class " + newSkelClass + ".hpp...");
4361 * HELPER: writeReturnDidAlreadyInitWaitInvoke() writes the function to return didAlreadyInitWaitInvoke
4363 private void writeReturnDidAlreadyInitWaitInvoke(String newSkelClass) {
4365 println("bool " + newSkelClass + "::didInitWaitInvoke() {");
4366 println("return didAlreadyInitWaitInvoke;");
4372 * writeSkelExternalCFunctions() generate external functions for .so file
4374 public void writeSkelExternalCFunctions(String newSkelClass, String intface) throws IOException {
4376 println("extern \"C\" void* create" + newSkelClass + "(void** params) {");
4377 println("// Args: *_mainObj, int _portSend, int _portRecv");
4378 println("return new " + newSkelClass + "((" + intface + "*) params[0], *((int*) params[0]), *((int*) params[1]));");
4380 println("extern \"C\" void destroy" + newSkelClass + "(void* t) {");
4381 println(newSkelClass + "* obj = (" + newSkelClass + "*) t;");
4382 println("delete obj;");
4384 //println("extern \"C\" void init" + newSkelClass + "(void* t) {");
4385 //println(newSkelClass + "* obj = (" + newSkelClass + "*) t;");
4386 //println("obj->init();");
4387 //println("while(true);");
4393 * generateCplusSkeletonClassCpp() generate skeletons based on the methods list in C++ (.cpp file)
4395 public void generateCplusSkeletonClassCpp() throws IOException {
4397 // Create a new directory
4398 String path = createDirectories(dir, subdir);
4399 for (String intface : mapIntfacePTH.keySet()) {
4400 // Open a new file to write into
4401 String newSkelClass = intface + "_Skeleton";
4402 FileWriter fw = new FileWriter(path + "/" + newSkelClass + ".cpp");
4403 pw = new PrintWriter(new BufferedWriter(fw));
4404 // Write file headers
4405 println("#include <iostream>");
4406 println("#include \"" + newSkelClass + ".hpp\"\n");
4407 // Pass in set of methods and get import classes
4408 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4409 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
4410 List<String> methods = intDecl.getMethods();
4411 // Find out if there are callback objects
4412 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
4413 boolean callbackExist = !callbackClasses.isEmpty();
4414 for(String str: callbackClasses) {
4415 if (intface.equals(mainClass))
4416 println("#include \"" + getStubInterface(str) + "_Stub.cpp\"\n");
4418 println("#include \"" + getStubInterface(str) + "_Stub.hpp\"\n");
4420 println("using namespace std;\n");
4421 // Write constructor
4422 writeConstructorCplusSkeleton(newSkelClass, intface, callbackExist, intDecl, methods);
4423 // Write callback constructor
4424 writeCallbackConstructorCplusSkeleton(newSkelClass, intface, callbackExist, intDecl, methods);
4425 // Write deconstructor
4426 writeDeconstructorCplusSkeleton(newSkelClass, callbackExist, callbackClasses);
4427 // Write didInitWaitInvoke() to return bool
4428 writeReturnDidAlreadyInitWaitInvoke(newSkelClass);
4430 writeMethodCplusSkeleton(methods, intDecl, callbackClasses, false, intface, newSkelClass);
4431 // Write method helper
4432 writeMethodHelperCplusSkeleton(methods, intDecl, callbackClasses, newSkelClass);
4433 // Write waitRequestInvokeMethod() - main loop
4434 writeCplusWaitRequestInvokeMethod(methods, intDecl, callbackExist, intface, newSkelClass);
4435 // Write external functions for .so file
4436 writeSkelExternalCFunctions(newSkelClass, intface);
4437 // TODO: Remove this later
4438 if (intface.equals(mainClass)) {
4439 println("int main() {");
4440 println("return 0;");
4444 System.out.println("IoTCompiler: Generated skeleton class " + newSkelClass + ".cpp...");
4450 * generateInitializer() generate initializer based on type
4452 public String generateCplusInitializer(String type) {
4454 // Generate dummy returns for now
4455 if (type.equals("short")||
4456 type.equals("int") ||
4457 type.equals("long") ||
4458 type.equals("float")||
4459 type.equals("double")) {
4462 } else if ( type.equals("String") ||
4463 type.equals("string")) {
4466 } else if ( type.equals("char") ||
4467 type.equals("byte")) {
4470 } else if ( type.equals("boolean")) {
4480 * setDirectory() sets a new directory for stub files
4482 public void setDirectory(String _subdir) {
4489 * printUsage() prints the usage of this compiler
4491 public static void printUsage() {
4493 System.out.println();
4494 System.out.println("Sentinel interface and stub compiler version 1.0");
4495 System.out.println("Copyright (c) 2015-2016 University of California, Irvine - Programming Language Group.");
4496 System.out.println("All rights reserved.");
4497 System.out.println("Usage:");
4498 System.out.println("\tjava IoTCompiler -help / --help / -h\n");
4499 System.out.println("\t\tDisplay this help texts\n\n");
4500 System.out.println("\tjava IoTCompiler [<main-policy-file> <req-policy-file>]");
4501 System.out.println("\tjava IoTCompiler [<main-policy-file> <req-policy-file>] [options]\n");
4502 System.out.println("\t\tTake one or more pairs of main-req policy files, and generate Java and/or C++ files\n");
4503 System.out.println("Options:");
4504 System.out.println("\t-java\t<directory>\tGenerate Java stub files");
4505 System.out.println("\t-cplus\t<directory>\tGenerate C++ stub files");
4506 System.out.println();
4511 * parseFile() prepares Lexer and Parser objects, then parses the file
4513 public static ParseNode parseFile(String file) {
4515 ParseNode pn = null;
4517 ComplexSymbolFactory csf = new ComplexSymbolFactory();
4518 ScannerBuffer lexer =
4519 new ScannerBuffer(new Lexer(new BufferedReader(new FileReader(file)),csf));
4520 Parser parse = new Parser(lexer,csf);
4521 pn = (ParseNode) parse.parse().value;
4522 } catch (Exception e) {
4523 e.printStackTrace();
4524 throw new Error("IoTCompiler: ERROR parsing policy file or wrong command line option: " + file + "\n");
4532 * Basic helper functions
4535 boolean newline=true;
4538 private void print(String str) {
4541 if (str.equals("}"))
4543 for(int i=0; i<tab; i++)
4553 * This function converts Java to C++ type for compilation
4555 private String convertType(String type) {
4557 if (mapPrimitives.containsKey(type))
4558 return mapPrimitives.get(type);
4565 * A collection of methods with print-to-file functionality
4567 private void println(String str) {
4570 if (str.contains("}") && !str.contains("{"))
4572 for(int i=0; i<tab; i++)
4581 private void updatetabbing(String str) {
4583 tablevel+=count(str,'{')-count(str,'}');
4587 private int count(String str, char key) {
4588 char[] array = str.toCharArray();
4590 for(int i=0; i<array.length; i++) {
4591 if (array[i] == key)
4598 private void createDirectory(String dirName) {
4600 File file = new File(dirName);
4601 if (!file.exists()) {
4603 System.out.println("IoTCompiler: Directory " + dirName + " has been created!");
4605 System.out.println("IoTCompiler: Failed to create directory " + dirName + "!");
4608 System.out.println("IoTCompiler: Directory " + dirName + " exists...");
4613 // Create a directory and possibly a sub directory
4614 private String createDirectories(String dir, String subdir) {
4617 createDirectory(path);
4618 if (subdir != null) {
4619 path = path + "/" + subdir;
4620 createDirectory(path);
4626 // Inserting array members into a Map object
4627 // that maps arrKey to arrVal objects
4628 private void arraysToMap(Map map, Object[] arrKey, Object[] arrVal) {
4630 for(int i = 0; i < arrKey.length; i++) {
4632 map.put(arrKey[i], arrVal[i]);
4637 // Check and find object Id for new interface in mapNewIntfaceObjId (callbacks)
4638 // Throw an error if the new interface is not found!
4639 // Basically the compiler needs to parse the policy (and requires) files for callback class first
4640 private int getNewIntfaceObjectId(String newIntface) {
4642 // if (!mapNewIntfaceObjId.containsKey(newIntface)) {
4643 // throw new Error("IoTCompiler: Need to parse policy and requires files for callback class first! " +
4644 // "Please place the two files for callback class in front...\n");
4647 int retObjId = mapNewIntfaceObjId.get(newIntface);
4653 // Return parameter category, i.e. PRIMITIVES, NONPRIMITIVES, USERDEFINED, ENUM, or STRUCT
4654 private ParamCategory getParamCategory(String paramType) {
4656 if (mapPrimitives.containsKey(paramType)) {
4657 return ParamCategory.PRIMITIVES;
4658 // We can either use mapNonPrimitivesJava or mapNonPrimitivesCplus here
4659 } else if (mapNonPrimitivesJava.containsKey(getSimpleType(paramType))) {
4660 return ParamCategory.NONPRIMITIVES;
4661 } else if (isEnumClass(paramType)) {
4662 return ParamCategory.ENUM;
4663 } else if (isStructClass(paramType)) {
4664 return ParamCategory.STRUCT;
4666 return ParamCategory.USERDEFINED;
4670 // Return full class name for non-primitives to generate Java import statements
4671 // e.g. java.util.Set for Set
4672 private String getNonPrimitiveJavaClass(String paramNonPrimitives) {
4674 return mapNonPrimitivesJava.get(paramNonPrimitives);
4678 // Return full class name for non-primitives to generate Cplus include statements
4679 // e.g. #include <set> for Set
4680 private String getNonPrimitiveCplusClass(String paramNonPrimitives) {
4682 return mapNonPrimitivesCplus.get(paramNonPrimitives);
4686 // Get simple types, e.g. HashSet for HashSet<...>
4687 // Basically strip off the "<...>"
4688 private String getSimpleType(String paramType) {
4690 // Check if this is generics
4691 if(paramType.contains("<")) {
4692 String[] type = paramType.split("<");
4699 // Generate a set of standard classes for import statements
4700 private List<String> getStandardJavaIntfaceImportClasses() {
4702 List<String> importClasses = new ArrayList<String>();
4703 // Add the standard list first
4704 importClasses.add("java.util.List");
4705 importClasses.add("java.util.ArrayList");
4707 return importClasses;
4711 // Generate a set of standard classes for import statements
4712 private List<String> getStandardJavaImportClasses() {
4714 List<String> importClasses = new ArrayList<String>();
4715 // Add the standard list first
4716 importClasses.add("java.io.IOException");
4717 importClasses.add("java.util.List");
4718 importClasses.add("java.util.ArrayList");
4719 importClasses.add("java.util.Arrays");
4720 importClasses.add("java.util.Map");
4721 importClasses.add("java.util.HashMap");
4722 importClasses.add("java.util.concurrent.atomic.AtomicBoolean");
4723 importClasses.add("iotrmi.Java.IoTRMIComm");
4724 importClasses.add("iotrmi.Java.IoTRMICommClient");
4725 importClasses.add("iotrmi.Java.IoTRMICommServer");
4726 importClasses.add("iotrmi.Java.IoTRMIUtil");
4728 return importClasses;
4732 // Generate a set of standard classes for import statements
4733 private List<String> getStandardCplusIncludeClasses() {
4735 List<String> importClasses = new ArrayList<String>();
4736 // Add the standard list first
4737 importClasses.add("<vector>");
4738 importClasses.add("<set>");
4739 //importClasses.add("\"IoTRMICall.hpp\"");
4740 //importClasses.add("\"IoTRMIObject.hpp\"");
4741 importClasses.add("\"IoTRMIComm.hpp\"");
4742 importClasses.add("\"IoTRMICommClient.hpp\"");
4743 importClasses.add("\"IoTRMICommServer.hpp\"");
4745 return importClasses;
4749 // Combine all classes for import statements
4750 private List<String> getAllLibClasses(Collection<String> stdLibClasses, Collection<String> libClasses) {
4752 List<String> allLibClasses = new ArrayList<String>(stdLibClasses);
4753 // Iterate over the list of import classes
4754 for (String str : libClasses) {
4755 if (!allLibClasses.contains(str)) {
4756 allLibClasses.add(str);
4759 return allLibClasses;
4764 // Generate a set of classes for import statements
4765 private Set<String> getImportClasses(Collection<String> methods, InterfaceDecl intDecl) {
4767 Set<String> importClasses = new HashSet<String>();
4768 for (String method : methods) {
4769 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4770 for (String paramType : methPrmTypes) {
4772 String simpleType = getSimpleType(paramType);
4773 if (getParamCategory(simpleType) == ParamCategory.NONPRIMITIVES) {
4774 importClasses.add(getNonPrimitiveJavaClass(simpleType));
4778 return importClasses;
4782 // Handle and return the correct enum declaration
4783 // In Java, if we declare enum in Camera interface, then it becomes "Camera.<enum>"
4784 private String getEnumParamDecl(String type, InterfaceDecl intDecl) {
4786 // Strips off array "[]" for return type
4787 String pureType = getSimpleArrayType(type);
4788 // Take the inner type of generic
4789 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
4790 pureType = getTypeOfGeneric(type)[0];
4791 if (isEnumClass(pureType)) {
4792 String enumType = intDecl.getInterface() + "." + type;
4799 // Handle and return the correct type
4800 private String getEnumParam(String type, String param, int i) {
4802 // Strips off array "[]" for return type
4803 String pureType = getSimpleArrayType(type);
4804 // Take the inner type of generic
4805 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
4806 pureType = getTypeOfGeneric(type)[0];
4807 if (isEnumClass(pureType)) {
4808 String enumParam = "paramEnum" + i;
4815 // Handle and return the correct enum declaration translate into int[]
4816 private String getEnumType(String type) {
4818 // Strips off array "[]" for return type
4819 String pureType = getSimpleArrayType(type);
4820 // Take the inner type of generic
4821 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
4822 pureType = getGenericType(type);
4823 if (isEnumClass(pureType)) {
4824 String enumType = "int[]";
4830 // Handle and return the correct enum declaration translate into int* for C
4831 private String getEnumCplusClsType(String type) {
4833 // Strips off array "[]" for return type
4834 String pureType = getSimpleArrayType(type);
4835 // Take the inner type of generic
4836 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
4837 pureType = getGenericType(type);
4838 if (isEnumClass(pureType)) {
4839 String enumType = "int*";
4846 // Handle and return the correct struct declaration
4847 private String getStructType(String type) {
4849 // Strips off array "[]" for return type
4850 String pureType = getSimpleArrayType(type);
4851 // Take the inner type of generic
4852 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
4853 pureType = getGenericType(type);
4854 if (isStructClass(pureType)) {
4855 String structType = "int";
4862 // Check if this an enum declaration
4863 private boolean isEnumClass(String type) {
4865 // Just iterate over the set of interfaces
4866 for (String intface : mapIntfacePTH.keySet()) {
4867 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4868 EnumDecl enumDecl = (EnumDecl) decHandler.getEnumDecl(intface);
4869 Set<String> setEnumDecl = enumDecl.getEnumDeclarations();
4870 if (setEnumDecl.contains(type))
4877 // Check if this an struct declaration
4878 private boolean isStructClass(String type) {
4880 // Just iterate over the set of interfaces
4881 for (String intface : mapIntfacePTH.keySet()) {
4882 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4883 StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
4884 List<String> listStructDecl = structDecl.getStructTypes();
4885 if (listStructDecl.contains(type))
4892 // Return a struct declaration
4893 private StructDecl getStructDecl(String type) {
4895 // Just iterate over the set of interfaces
4896 for (String intface : mapIntfacePTH.keySet()) {
4897 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4898 StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
4899 List<String> listStructDecl = structDecl.getStructTypes();
4900 if (listStructDecl.contains(type))
4907 // Return number of members (-1 if not found)
4908 private int getNumOfMembers(String type) {
4910 // Just iterate over the set of interfaces
4911 for (String intface : mapIntfacePTH.keySet()) {
4912 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4913 StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
4914 List<String> listStructDecl = structDecl.getStructTypes();
4915 if (listStructDecl.contains(type))
4916 return structDecl.getNumOfMembers(type);
4922 // Generate a set of classes for include statements
4923 private Set<String> getIncludeClasses(Collection<String> methods, InterfaceDecl intDecl, String intface, boolean needExchange) {
4925 Set<String> includeClasses = new HashSet<String>();
4926 for (String method : methods) {
4928 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4929 List<String> methParams = intDecl.getMethodParams(method);
4930 for (int i = 0; i < methPrmTypes.size(); i++) {
4932 String genericType = getGenericType(methPrmTypes.get(i));
4933 String simpleType = getSimpleType(methPrmTypes.get(i));
4934 String param = methParams.get(i);
4935 if (getParamCategory(simpleType) == ParamCategory.NONPRIMITIVES) {
4936 includeClasses.add("<" + getNonPrimitiveCplusClass(simpleType) + ">");
4937 //} else if (getParamCategory(simpleType) == ParamCategory.USERDEFINED) {
4939 if (getParamCategory(getSimpleArrayType(genericType)) == ParamCategory.USERDEFINED) {
4940 // For original interface, we need it exchanged... not for stub interfaces
4942 //includeClasses.add("\"" + exchangeParamType(simpleType) + ".hpp\"");
4943 includeClasses.add("\"" + exchangeParamType(getSimpleArrayType(genericType)) + ".hpp\"");
4945 //includeClasses.add("\"" + simpleType + ".hpp\"");
4946 includeClasses.add("\"" + getSimpleArrayType(genericType) + ".hpp\"");
4949 if (getParamCategory(getSimpleArrayType(genericType)) == ParamCategory.ENUM) {
4950 includeClasses.add("\"" + genericType + ".hpp\"");
4952 if (getParamCategory(getSimpleArrayType(genericType)) == ParamCategory.STRUCT) {
4953 includeClasses.add("\"" + genericType + ".hpp\"");
4955 if (param.contains("[]")) {
4956 // Check if this is array for C++; translate into vector
4957 includeClasses.add("<vector>");
4961 return includeClasses;
4965 // Generate a set of callback classes
4966 private Set<String> getCallbackClasses(Collection<String> methods, InterfaceDecl intDecl) {
4968 Set<String> callbackClasses = new HashSet<String>();
4969 for (String method : methods) {
4971 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4972 List<String> methParams = intDecl.getMethodParams(method);
4973 for (int i = 0; i < methPrmTypes.size(); i++) {
4975 String type = methPrmTypes.get(i);
4976 if (getParamCategory(type) == ParamCategory.USERDEFINED) {
4977 callbackClasses.add(type);
4978 } else if (getParamCategory(type) == ParamCategory.NONPRIMITIVES) {
4979 // Can be a List<...> of callback objects ...
4980 String genericType = getTypeOfGeneric(type)[0];
4981 if (getParamCategory(type) == ParamCategory.USERDEFINED) {
4982 callbackClasses.add(type);
4987 return callbackClasses;
4991 // Print import statements into file
4992 private void printImportStatements(Collection<String> importClasses) {
4994 for(String cls : importClasses) {
4995 println("import " + cls + ";");
5000 // Print include statements into file
5001 private void printIncludeStatements(Collection<String> includeClasses) {
5003 for(String cls : includeClasses) {
5004 println("#include " + cls);
5009 // Get the C++ version of a non-primitive type
5010 // e.g. set for Set and map for Map
5011 // Input nonPrimitiveType has to be generics in format
5012 private String[] getTypeOfGeneric(String nonPrimitiveType) {
5014 // Handle <, >, and , for 2-type generic/template
5015 String[] substr = nonPrimitiveType.split("<")[1].split(">")[0].split(",");
5020 // Gets generic type inside "<" and ">"
5021 private String getGenericType(String type) {
5023 // Handle <, >, and , for 2-type generic/template
5024 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES) {
5025 String[] substr = type.split("<")[1].split(">")[0].split(",");
5032 // This helper function strips off array declaration, e.g. int[] becomes int
5033 private String getSimpleArrayType(String type) {
5035 // Handle [ for array declaration
5036 String substr = type;
5037 if (type.contains("[]")) {
5038 substr = type.split("\\[\\]")[0];
5044 // This helper function strips off array declaration, e.g. D[] becomes D
5045 private String getSimpleIdentifier(String ident) {
5047 // Handle [ for array declaration
5048 String substr = ident;
5049 if (ident.contains("[]")) {
5050 substr = ident.split("\\[\\]")[0];
5056 // Checks and gets type in C++
5057 private String checkAndGetCplusType(String paramType) {
5059 if (getParamCategory(paramType) == ParamCategory.PRIMITIVES) {
5060 return convertType(paramType);
5061 } else if (getParamCategory(paramType) == ParamCategory.NONPRIMITIVES) {
5063 // Check for generic/template format
5064 if (paramType.contains("<") && paramType.contains(">")) {
5066 String genericClass = getSimpleType(paramType);
5067 String genericType = getGenericType(paramType);
5068 String cplusTemplate = null;
5069 cplusTemplate = getNonPrimitiveCplusClass(genericClass);
5070 if(getParamCategory(getGenericType(paramType)) == ParamCategory.USERDEFINED) {
5071 cplusTemplate = cplusTemplate + "<" + genericType + "*>";
5073 cplusTemplate = cplusTemplate + "<" + convertType(genericType) + ">";
5075 return cplusTemplate;
5077 return getNonPrimitiveCplusClass(paramType);
5078 } else if(paramType.contains("[]")) { // Array type (used for return type only)
5079 String cArray = "vector<" + convertType(getSimpleArrayType(paramType)) + ">";
5081 } else if(getParamCategory(paramType) == ParamCategory.USERDEFINED) {
5082 return paramType + "*";
5084 // Just return it as is if it's not non-primitives
5089 // Detect array declaration, e.g. int A[],
5090 // then generate "int A[]" in C++ as "vector<int> A"
5091 private String checkAndGetCplusArray(String paramType, String param) {
5093 String paramComplete = null;
5094 // Check for array declaration
5095 if (param.contains("[]")) {
5096 paramComplete = "vector<" + paramType + "> " + param.replace("[]","");
5098 // Just return it as is if it's not an array
5099 paramComplete = paramType + " " + param;
5101 return paramComplete;
5105 // Detect array declaration, e.g. int A[],
5106 // then generate "int A[]" in C++ as "vector<int> A"
5107 // This method just returns the type
5108 private String checkAndGetCplusArrayType(String paramType) {
5110 String paramTypeRet = null;
5111 // Check for array declaration
5112 if (paramType.contains("[]")) {
5113 String type = paramType.split("\\[\\]")[0];
5114 paramTypeRet = checkAndGetCplusType(type) + "[]";
5115 } else if (paramType.contains("vector")) {
5116 // Just return it as is if it's not an array
5117 String type = paramType.split("<")[1].split(">")[0];
5118 paramTypeRet = checkAndGetCplusType(type) + "[]";
5120 paramTypeRet = paramType;
5122 return paramTypeRet;
5126 // Detect array declaration, e.g. int A[],
5127 // then generate "int A[]" in C++ as "vector<int> A"
5128 // This method just returns the type
5129 private String checkAndGetCplusArrayType(String paramType, String param) {
5131 String paramTypeRet = null;
5132 // Check for array declaration
5133 if (param.contains("[]")) {
5134 paramTypeRet = checkAndGetCplusType(paramType) + "[]";
5135 } else if (paramType.contains("vector")) {
5136 // Just return it as is if it's not an array
5137 String type = paramType.split("<")[1].split(">")[0];
5138 paramTypeRet = checkAndGetCplusType(type) + "[]";
5140 paramTypeRet = paramType;
5142 return paramTypeRet;
5146 // Return the class type for class resolution (for return value)
5147 // - Check and return C++ array class, e.g. int A[] into int*
5148 // - Check and return C++ vector class, e.g. List<Integer> A into vector<int>
5149 private String checkAndGetCplusRetClsType(String paramType) {
5151 String paramTypeRet = null;
5152 // Check for array declaration
5153 if (paramType.contains("[]")) {
5154 String type = paramType.split("\\[\\]")[0];
5155 paramTypeRet = getSimpleArrayType(type) + "*";
5156 } else if (paramType.contains("<") && paramType.contains(">")) {
5157 // Just return it as is if it's not an array
5158 String type = paramType.split("<")[1].split(">")[0];
5159 paramTypeRet = "vector<" + getGenericType(type) + ">";
5161 paramTypeRet = paramType;
5163 return paramTypeRet;
5167 // Return the class type for class resolution (for method arguments)
5168 // - Check and return C++ array class, e.g. int A[] into int*
5169 // - Check and return C++ vector class, e.g. List<Integer> A into vector<int>
5170 private String checkAndGetCplusArgClsType(String paramType, String param) {
5172 String paramTypeRet = getEnumCplusClsType(paramType);
5173 if (!paramTypeRet.equals(paramType))
5174 // Just return if it is an enum type
5175 // Type will still be the same if it's not an enum type
5176 return paramTypeRet;
5178 // Check for array declaration
5179 if (param.contains("[]")) {
5180 paramTypeRet = getSimpleArrayType(paramType) + "*";
5181 } else if (paramType.contains("<") && paramType.contains(">")) {
5182 // Just return it as is if it's not an array
5183 String type = paramType.split("<")[1].split(">")[0];
5184 paramTypeRet = "vector<" + getGenericType(type) + ">";
5186 paramTypeRet = paramType;
5188 return paramTypeRet;
5192 // Detect array declaration, e.g. int A[],
5193 // then generate type "int[]"
5194 private String checkAndGetArray(String paramType, String param) {
5196 String paramTypeRet = null;
5197 // Check for array declaration
5198 if (param.contains("[]")) {
5199 paramTypeRet = paramType + "[]";
5201 // Just return it as is if it's not an array
5202 paramTypeRet = paramType;
5204 return paramTypeRet;
5208 // Is array or list?
5209 private boolean isArrayOrList(String paramType, String param) {
5211 // Check for array declaration
5214 else if (isList(paramType))
5222 // For return type we use retType as input parameter
5223 private boolean isArray(String param) {
5225 // Check for array declaration
5226 if (param.contains("[]"))
5234 private boolean isList(String paramType) {
5236 // Check for array declaration
5237 if (paramType.contains("List"))
5244 // Get the right type for a callback object
5245 private String checkAndGetParamClass(String paramType) {
5247 // Check if this is generics
5248 if(getParamCategory(paramType) == ParamCategory.USERDEFINED) {
5249 return exchangeParamType(paramType);
5250 } else if (isList(paramType) &&
5251 (getParamCategory(getGenericType(paramType)) == ParamCategory.USERDEFINED)) {
5252 return "List<" + exchangeParamType(getGenericType(paramType)) + ">";
5258 // Returns the other interface for type-checking purposes for USERDEFINED
5259 // classes based on the information provided in multiple policy files
5260 // e.g. return CameraWithXXX instead of Camera
5261 private String exchangeParamType(String intface) {
5263 // Param type that's passed is the interface name we need to look for
5264 // in the map of interfaces, based on available policy files.
5265 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
5266 if (decHandler != null) {
5267 // We've found the required interface policy files
5268 RequiresDecl reqDecl = (RequiresDecl) decHandler.getRequiresDecl(intface);
5269 Set<String> setExchInt = reqDecl.getInterfaces();
5270 if (setExchInt.size() == 1) {
5271 Iterator iter = setExchInt.iterator();
5272 return (String) iter.next();
5274 throw new Error("IoTCompiler: Ambiguous stub interfaces: " + setExchInt.toString() +
5275 ". Only one new interface can be declared if the object " + intface +
5276 " needs to be passed in as an input parameter!\n");
5279 // NULL value - this means policy files missing
5280 throw new Error("IoTCompiler: Parameter type lookup failed for " + intface +
5281 "... Please provide the necessary policy files for user-defined types." +
5282 " If this is an array please type the brackets after the variable name," +
5283 " e.g. \"String str[]\", not \"String[] str\"." +
5284 " If this is a Collections (Java) / STL (C++) type, this compiler only" +
5285 " supports List/ArrayList (Java) or list (C++).\n");
5290 public static void main(String[] args) throws Exception {
5292 // If there is no argument or just "--help" or "-h", then invoke printUsage()
5293 if ((args[0].equals("-help") ||
5294 args[0].equals("--help")||
5295 args[0].equals("-h")) ||
5296 (args.length == 0)) {
5298 IoTCompiler.printUsage();
5300 } else if (args.length > 1) {
5302 IoTCompiler comp = new IoTCompiler();
5305 // Parse main policy file
5306 ParseNode pnPol = IoTCompiler.parseFile(args[i]);
5307 // Parse "requires" policy file
5308 ParseNode pnReq = IoTCompiler.parseFile(args[i+1]);
5309 // Get interface name
5310 String intface = ParseTreeHandler.getOrigIntface(pnPol);
5311 comp.setDataStructures(intface, pnPol, pnReq);
5312 comp.getMethodsForIntface(intface);
5314 // 1) Check if this is the last option before "-java" or "-cplus"
5315 // 2) Check if this is really the last option (no "-java" or "-cplus")
5316 } while(!args[i].equals("-java") &&
5317 !args[i].equals("-cplus") &&
5320 // Generate everything if we don't see "-java" or "-cplus"
5321 if (i == args.length) {
5322 comp.generateEnumJava();
5323 comp.generateStructJava();
5324 comp.generateJavaLocalInterfaces();
5325 comp.generateJavaInterfaces();
5326 comp.generateJavaStubClasses();
5327 comp.generateJavaSkeletonClass();
5328 comp.generateEnumCplus();
5329 comp.generateStructCplus();
5330 comp.generateCplusLocalInterfaces();
5331 comp.generateCPlusInterfaces();
5332 comp.generateCPlusStubClassesHpp();
5333 comp.generateCPlusStubClassesCpp();
5334 //comp.generateCPlusCallbackStubClasses();
5335 comp.generateCplusSkeletonClassHpp();
5336 comp.generateCplusSkeletonClassCpp();
5337 //comp.generateCplusCallbackSkeletonClass();
5339 // Check other options
5340 while(i < args.length) {
5342 if (!args[i].equals("-java") &&
5343 !args[i].equals("-cplus")) {
5344 throw new Error("IoTCompiler: ERROR - unrecognized command line option: " + args[i] + "\n");
5346 if (i + 1 < args.length) {
5347 comp.setDirectory(args[i+1]);
5349 throw new Error("IoTCompiler: ERROR - please provide <directory> after option: " + args[i] + "\n");
5351 if (args[i].equals("-java")) {
5352 comp.generateEnumJava();
5353 comp.generateStructJava();
5354 comp.generateJavaLocalInterfaces();
5355 comp.generateJavaInterfaces();
5356 comp.generateJavaStubClasses();
5357 comp.generateJavaSkeletonClass();
5359 comp.generateEnumCplus();
5360 comp.generateStructCplus();
5361 comp.generateCplusLocalInterfaces();
5362 comp.generateCPlusInterfaces();
5363 comp.generateCPlusStubClassesHpp();
5364 comp.generateCPlusStubClassesCpp();
5365 //comp.generateCPlusCallbackStubClasses();
5366 comp.generateCplusSkeletonClassHpp();
5367 comp.generateCplusSkeletonClassCpp();
5368 //comp.generateCplusCallbackSkeletonClass();
5375 // Need to at least have exactly 2 parameters, i.e. main policy file and requires file
5376 IoTCompiler.printUsage();
5377 throw new Error("IoTCompiler: At least two arguments (main and requires policy files) have to be provided!\n");