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 // Data structure to store our types (primitives and non-primitives) for compilation
52 private Map<String,String> mapPrimitives;
53 private Map<String,String> mapNonPrimitivesJava;
54 private Map<String,String> mapNonPrimitivesCplus;
55 // Other data structures
56 private Map<String,Integer> mapIntfaceObjId; // Maps interface name to object Id
57 private Map<String,Integer> mapNewIntfaceObjId; // Maps new interface name to its object Id (keep track of stubs)
58 private PrintWriter pw;
60 private String subdir;
65 private final static String OUTPUT_DIRECTORY = "output_files";
67 private enum ParamCategory {
69 PRIMITIVES, // All the primitive types, e.g. byte, short, int, long, etc.
70 NONPRIMITIVES, // Non-primitive types, e.g. Set, Map, List, etc.
71 USERDEFINED // Non-supported type by default; assumed as driver classes
77 public IoTCompiler() {
79 mapIntfacePTH = new HashMap<String,ParseTreeHandler>();
80 mapIntDeclHand = new HashMap<String,DeclarationHandler>();
81 mapInt2NewInts = new HashMap<String,Map<String,Set<String>>>();
82 mapIntfaceObjId = new HashMap<String,Integer>();
83 mapNewIntfaceObjId = new HashMap<String,Integer>();
84 mapPrimitives = new HashMap<String,String>();
85 arraysToMap(mapPrimitives, IoTRMITypes.primitivesJava, IoTRMITypes.primitivesCplus);
86 mapNonPrimitivesJava = new HashMap<String,String>();
87 arraysToMap(mapNonPrimitivesJava, IoTRMITypes.nonPrimitivesJava, IoTRMITypes.nonPrimitiveJavaLibs);
88 mapNonPrimitivesCplus = new HashMap<String,String>();
89 arraysToMap(mapNonPrimitivesCplus, IoTRMITypes.nonPrimitivesJava, IoTRMITypes.nonPrimitivesCplus);
91 dir = OUTPUT_DIRECTORY;
97 * setDataStructures() sets parse tree and other data structures based on policy files.
99 * It also generates parse tree (ParseTreeHandler) and
100 * copies useful information from parse tree into
101 * InterfaceDecl, CapabilityDecl, and RequiresDecl
103 * Additionally, the data structure handles are
104 * returned from tree-parsing for further process.
107 public void setDataStructures(String origInt, ParseNode pnPol, ParseNode pnReq) {
109 ParseTreeHandler ptHandler = new ParseTreeHandler(origInt, pnPol, pnReq);
110 DeclarationHandler decHandler = new DeclarationHandler();
111 // Process ParseNode and generate Declaration objects
113 ptHandler.processInterfaceDecl();
114 InterfaceDecl intDecl = ptHandler.getInterfaceDecl();
115 decHandler.addInterfaceDecl(origInt, intDecl);
117 ptHandler.processCapabilityDecl();
118 CapabilityDecl capDecl = ptHandler.getCapabilityDecl();
119 decHandler.addCapabilityDecl(origInt, capDecl);
121 ptHandler.processRequiresDecl();
122 RequiresDecl reqDecl = ptHandler.getRequiresDecl();
123 decHandler.addRequiresDecl(origInt, reqDecl);
125 ptHandler.processEnumDecl();
126 EnumDecl enumDecl = ptHandler.getEnumDecl();
127 decHandler.addEnumDecl(origInt, enumDecl);
129 ptHandler.processStructDecl();
130 StructDecl structDecl = ptHandler.getStructDecl();
131 decHandler.addStructDecl(origInt, structDecl);
133 mapIntfacePTH.put(origInt, ptHandler);
134 mapIntDeclHand.put(origInt, decHandler);
135 // Set object Id counter to 0 for each interface
136 mapIntfaceObjId.put(origInt, new Integer(0));
141 * getMethodsForIntface() reads for methods in the data structure
143 * It is going to give list of methods for a certain interface
144 * based on the declaration of capabilities.
146 public void getMethodsForIntface(String origInt) {
148 ParseTreeHandler ptHandler = mapIntfacePTH.get(origInt);
149 Map<String,Set<String>> mapNewIntMethods = new HashMap<String,Set<String>>();
150 // Get set of new interfaces, e.g. CameraWithCaptureAndData
151 // Generate this new interface with all the methods it needs
152 // from different capabilities it declares
153 DeclarationHandler decHandler = mapIntDeclHand.get(origInt);
154 RequiresDecl reqDecl = (RequiresDecl) decHandler.getRequiresDecl(origInt);
155 Set<String> setIntfaces = reqDecl.getInterfaces();
156 for (String strInt : setIntfaces) {
158 // Initialize a set of methods
159 Set<String> setMethods = new HashSet<String>();
160 // Get list of capabilities, e.g. ImageCapture, VideoRecording, etc.
161 List<String> listCapab = reqDecl.getCapabList(strInt);
162 for (String strCap : listCapab) {
164 // Get list of methods for each capability
165 CapabilityDecl capDecl = (CapabilityDecl) decHandler.getCapabilityDecl(origInt);
166 List<String> listCapabMeth = capDecl.getMethods(strCap);
167 for (String strMeth : listCapabMeth) {
169 // Add methods into setMethods
170 // This is to also handle redundancies (say two capabilities
171 // share the same methods)
172 setMethods.add(strMeth);
175 // Add interface and methods information into map
176 mapNewIntMethods.put(strInt, setMethods);
178 // Map the map of interface-methods to the original interface
179 mapInt2NewInts.put(origInt, mapNewIntMethods);
184 * HELPER: writeMethodJavaLocalInterface() writes the method of the interface
186 private void writeMethodJavaLocalInterface(Collection<String> methods, InterfaceDecl intDecl) {
188 for (String method : methods) {
190 List<String> methParams = intDecl.getMethodParams(method);
191 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
192 print("public " + intDecl.getMethodType(method) + " " +
193 intDecl.getMethodId(method) + "(");
194 for (int i = 0; i < methParams.size(); i++) {
195 // Check for params with driver class types and exchange it
196 // with its remote interface
197 String paramType = checkAndGetParamClass(methPrmTypes.get(i), false);
198 print(paramType + " " + methParams.get(i));
199 // Check if this is the last element (don't print a comma)
200 if (i != methParams.size() - 1) {
210 * HELPER: writeMethodJavaInterface() writes the method of the interface
212 private void writeMethodJavaInterface(Collection<String> methods, InterfaceDecl intDecl) {
214 for (String method : methods) {
216 List<String> methParams = intDecl.getMethodParams(method);
217 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
218 print("public " + intDecl.getMethodType(method) + " " +
219 intDecl.getMethodId(method) + "(");
220 for (int i = 0; i < methParams.size(); i++) {
221 // Check for params with driver class types and exchange it
222 // with its remote interface
223 String paramType = methPrmTypes.get(i);
224 print(paramType + " " + methParams.get(i));
225 // Check if this is the last element (don't print a comma)
226 if (i != methParams.size() - 1) {
236 * HELPER: writeEnumJava() writes the enumeration declaration
238 private void writeEnumJava(EnumDecl enumDecl) {
240 Set<String> enumTypes = enumDecl.getEnumDeclarations();
241 // Iterate over enum declarations
242 for (String enType : enumTypes) {
244 println("public enum " + enType + " {");
245 List<String> enumMembers = enumDecl.getMembers(enType);
246 for (int i = 0; i < enumMembers.size(); i++) {
248 String member = enumMembers.get(i);
250 // Check if this is the last element (don't print a comma)
251 if (i != enumMembers.size() - 1)
262 * HELPER: writeStructJava() writes the struct declaration
264 private void writeStructJava(StructDecl structDecl) {
266 List<String> structTypes = structDecl.getStructTypes();
267 // Iterate over enum declarations
268 for (String stType : structTypes) {
270 println("public class " + stType + " {");
271 List<String> structMemberTypes = structDecl.getMemberTypes(stType);
272 List<String> structMembers = structDecl.getMembers(stType);
273 for (int i = 0; i < structMembers.size(); i++) {
275 String memberType = structMemberTypes.get(i);
276 String member = structMembers.get(i);
277 println("public static " + memberType + " " + member + ";");
285 * generateJavaLocalInterface() writes the local interface and provides type-checking.
287 * It needs to rewrite and exchange USERDEFINED types in input parameters of stub
288 * and original interfaces, e.g. exchange Camera and CameraWithVideoAndRecording.
289 * The local interface has to be the input parameter for the stub and the stub
290 * interface has to be the input parameter for the local class.
292 public void generateJavaLocalInterfaces() throws IOException {
294 // Create a new directory
295 createDirectory(dir);
296 for (String intface : mapIntfacePTH.keySet()) {
297 // Open a new file to write into
298 FileWriter fw = new FileWriter(dir + "/" + intface + ".java");
299 pw = new PrintWriter(new BufferedWriter(fw));
300 // Pass in set of methods and get import classes
301 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
302 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
303 List<String> methods = intDecl.getMethods();
304 Set<String> importClasses = getImportClasses(methods, intDecl);
305 printImportStatements(importClasses);
306 // Write interface header
308 println("public interface " + intface + " {");
309 // Write enum if any...
310 EnumDecl enumDecl = (EnumDecl) decHandler.getEnumDecl(intface);
311 writeEnumJava(enumDecl);
312 // Write struct if any...
313 StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
314 writeStructJava(structDecl);
316 writeMethodJavaLocalInterface(methods, intDecl);
319 System.out.println("IoTCompiler: Generated local interface " + intface + ".java...");
325 * generateJavaInterfaces() generate stub interfaces based on the methods list in Java
327 public void generateJavaInterfaces() throws IOException {
329 // Create a new directory
330 String path = createDirectories(dir, subdir);
331 for (String intface : mapIntfacePTH.keySet()) {
333 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
334 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
336 // Open a new file to write into
337 String newIntface = intMeth.getKey();
338 FileWriter fw = new FileWriter(path + "/" + newIntface + ".java");
339 pw = new PrintWriter(new BufferedWriter(fw));
340 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
341 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
342 // Pass in set of methods and get import classes
343 Set<String> importClasses = getImportClasses(intMeth.getValue(), intDecl);
344 printImportStatements(importClasses);
345 // Write interface header
347 println("public interface " + newIntface + " {\n");
349 writeMethodJavaInterface(intMeth.getValue(), intDecl);
352 System.out.println("IoTCompiler: Generated interface " + newIntface + ".java...");
359 * HELPER: writePropertiesJavaStub() writes the properties of the stub class
361 private void writePropertiesJavaStub(String intface, String newIntface, boolean callbackExist, Set<String> callbackClasses) {
363 println("private IoTRMICall rmiCall;");
364 println("private String address;");
365 println("private int[] ports;\n");
367 Integer objId = mapIntfaceObjId.get(intface);
368 println("private final static int objectId = " + objId + ";");
369 mapNewIntfaceObjId.put(newIntface, objId);
370 mapIntfaceObjId.put(intface, objId++);
372 // We assume that each class only has one callback interface for now
373 Iterator it = callbackClasses.iterator();
374 String callbackType = (String) it.next();
375 println("// Callback properties");
376 println("private IoTRMIObject rmiObj;");
377 println("List<" + callbackType + "> listCallbackObj;");
378 println("private static int objIdCnt = 0;");
385 * HELPER: writeConstructorJavaStub() writes the constructor of the stub class
387 private void writeConstructorJavaStub(String intface, boolean callbackExist, Set<String> callbackClasses) {
389 println("public " + intface + "(int _port, String _address, int _rev, int[] _ports) throws Exception {");
390 println("address = _address;");
391 println("ports = _ports;");
392 println("rmiCall = new IoTRMICall(_port, _address, _rev);");
394 Iterator it = callbackClasses.iterator();
395 String callbackType = (String) it.next();
396 println("listCallbackObj = new ArrayList<" + callbackType + ">();");
397 println("___initCallBack();");
404 * HELPER: writeConstructorJavaStub() writes the constructor of the stub class
406 private void writeInitCallbackJavaStub(String intface, InterfaceDecl intDecl) {
408 println("public void ___initCallBack() {");
409 // Generate main thread for callbacks
410 println("Thread thread = new Thread() {");
411 println("public void run() {");
413 println("rmiObj = new IoTRMIObject(ports[0]);");
414 println("while (true) {");
415 println("byte[] method = rmiObj.getMethodBytes();");
416 println("int objId = IoTRMIObject.getObjectId(method);");
417 println(intface + "_CallbackSkeleton skel = (" + intface + "_CallbackSkeleton) listCallbackObj.get(objId);");
418 println("if (skel != null) {");
419 println("skel.invokeMethod(rmiObj);");
421 println("throw new Error(\"" + intface + ": Object with Id \" + objId + \" not found!\");");
424 println("} catch (Exception ex) {");
425 println("ex.printStackTrace();");
426 println("throw new Error(\"Error instantiating class " + intface + "_CallbackSkeleton!\");");
430 println("thread.start();\n");
431 // Generate info sending part
432 String method = "___initCallBack()";
433 println("int methodId = " + intDecl.getHelperMethodNumId(method) + ";");
434 println("Class<?> retType = void.class;");
435 println("Class<?>[] paramCls = new Class<?>[] { int.class, String.class, int.class };");
436 println("Object[] paramObj = new Object[] { ports[0], address, 0 };");
437 println("rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
443 * HELPER: writeStdMethodBodyJavaStub() writes the standard method body in the stub class
445 private void writeStdMethodBodyJavaStub(InterfaceDecl intDecl, List<String> methParams,
446 List<String> methPrmTypes, String method) {
448 println("int methodId = " + intDecl.getMethodNumId(method) + ";");
449 String retType = intDecl.getMethodType(method);
450 println("Class<?> retType = " + getSimpleType(retType) + ".class;");
451 // Generate array of parameter types
452 print("Class<?>[] paramCls = new Class<?>[] { ");
453 for (int i = 0; i < methParams.size(); i++) {
454 String paramType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
455 print(getSimpleType(paramType) + ".class");
456 // Check if this is the last element (don't print a comma)
457 if (i != methParams.size() - 1) {
462 // Generate array of parameter objects
463 print("Object[] paramObj = new Object[] { ");
464 for (int i = 0; i < methParams.size(); i++) {
465 print(getSimpleIdentifier(methParams.get(i)));
466 // Check if this is the last element (don't print a comma)
467 if (i != methParams.size() - 1) {
472 // Check if this is "void"
473 if (retType.equals("void")) {
474 println("rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
475 } else { // We do have a return value
476 // Check if the return value NONPRIMITIVES
477 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES) {
478 String[] retGenValType = getTypeOfGeneric(retType);
479 println("Class<?> retGenValType = " + retGenValType[0] + ".class;");
480 println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, retGenValType, paramCls, paramObj);");
481 println("return (" + retType + ")retObj;");
483 println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
484 println("return (" + retType + ")retObj;");
491 * HELPER: checkCallbackType() checks the callback type
493 private boolean checkCallbackType(String paramType, String callbackType) {
495 if (getParamCategory(paramType) == ParamCategory.NONPRIMITIVES)
496 paramType = getTypeOfGeneric(paramType)[0];
497 return callbackType.equals(paramType);
502 * HELPER: writeCallbackMethodBodyJavaStub() writes the callback method of the stub class
504 private void writeCallbackMethodBodyJavaStub(InterfaceDecl intDecl, List<String> methParams,
505 List<String> methPrmTypes, String method, String callbackType) {
508 // Check if this is single object, array, or list of objects
509 for (int i = 0; i < methParams.size(); i++) {
511 String paramType = methPrmTypes.get(i);
512 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
513 String param = methParams.get(i);
514 if (isArrayOrList(paramType, param)) { // Generate loop
515 println("for (" + paramType + " cb : " + getSimpleIdentifier(param) + ") {");
516 println(callbackType + "_CallbackSkeleton skel = new " + callbackType + "_CallbackSkeleton(cb, objIdCnt++);");
518 println(callbackType + "_CallbackSkeleton skel = new " + callbackType + "_CallbackSkeleton(" +
519 getSimpleIdentifier(param) + ", objIdCnt++);");
520 println("listCallbackObj.add(skel);");
521 if (isArrayOrList(paramType, param))
525 println("} catch (Exception ex) {");
526 println("ex.printStackTrace();");
527 println("throw new Error(\"Exception when generating skeleton objects!\");");
529 println("int methodId = " + intDecl.getMethodNumId(method) + ";");
530 String retType = intDecl.getMethodType(method);
531 println("Class<?> retType = " + getSimpleType(retType) + ".class;");
532 // Generate array of parameter types
533 print("Class<?>[] paramCls = new Class<?>[] { ");
534 for (int i = 0; i < methParams.size(); i++) {
535 String paramType = methPrmTypes.get(i);
536 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
538 } else { // Generate normal classes if it's not a callback object
539 String prmType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
540 print(getSimpleType(prmType) + ".class");
542 if (i != methParams.size() - 1) // Check if this is the last element
546 // Generate array of parameter objects
547 print("Object[] paramObj = new Object[] { ");
548 for (int i = 0; i < methParams.size(); i++) {
549 String paramType = methPrmTypes.get(i);
550 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
551 if (isArray(methPrmTypes.get(i), methParams.get(i)))
552 print(getSimpleIdentifier(methParams.get(i)) + ".length");
553 else if (isList(methPrmTypes.get(i), methParams.get(i)))
554 print(getSimpleIdentifier(methParams.get(i)) + ".size()");
556 print("new Integer(1)");
558 print(getSimpleIdentifier(methParams.get(i)));
559 if (i != methParams.size() - 1)
563 // Check if this is "void"
564 if (retType.equals("void")) {
565 println("rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
566 } else { // We do have a return value
567 // Check if the return value NONPRIMITIVES
568 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES) {
569 String[] retGenValType = getTypeOfGeneric(retType);
570 println("Class<?> retGenValType = " + retGenValType[0] + ".class;");
571 println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, retGenValType, paramCls, paramObj);");
572 println("return (" + retType + ")retObj;");
574 println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
575 println("return (" + retType + ")retObj;");
582 * HELPER: writeMethodJavaStub() writes the method of the stub class
584 private void writeMethodJavaStub(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
586 for (String method : methods) {
588 List<String> methParams = intDecl.getMethodParams(method);
589 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
590 print("public " + intDecl.getMethodType(method) + " " +
591 intDecl.getMethodId(method) + "(");
592 boolean isCallbackMethod = false;
593 String callbackType = null;
594 for (int i = 0; i < methParams.size(); i++) {
596 String paramType = methPrmTypes.get(i);
597 if (getParamCategory(paramType) == ParamCategory.NONPRIMITIVES)
598 paramType = getTypeOfGeneric(paramType)[0];
599 // Check if this has callback object
600 if (callbackClasses != null) {
601 if (callbackClasses.contains(paramType)) {
602 isCallbackMethod = true;
603 callbackType = paramType;
604 // Even if there're 2 callback arguments, we expect them to be of the same interface
607 print(methPrmTypes.get(i) + " " + methParams.get(i));
608 // Check if this is the last element (don't print a comma)
609 if (i != methParams.size() - 1) {
614 // Now, write the body of stub!
615 if (isCallbackMethod)
616 writeCallbackMethodBodyJavaStub(intDecl, methParams, methPrmTypes, method, callbackType);
618 writeStdMethodBodyJavaStub(intDecl, methParams, methPrmTypes, method);
620 // Write the init callback helper method
621 if (isCallbackMethod)
622 writeInitCallbackJavaStub(callbackType, intDecl);
628 * generateJavaStubClasses() generate stubs based on the methods list in Java
630 public void generateJavaStubClasses() throws IOException {
632 // Create a new directory
633 String path = createDirectories(dir, subdir);
634 for (String intface : mapIntfacePTH.keySet()) {
636 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
637 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
639 // Open a new file to write into
640 String newIntface = intMeth.getKey();
641 String newStubClass = newIntface + "_Stub";
642 FileWriter fw = new FileWriter(path + "/" + newStubClass + ".java");
643 pw = new PrintWriter(new BufferedWriter(fw));
644 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
645 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
646 // Pass in set of methods and get import classes
647 Set<String> methods = intMeth.getValue();
648 Set<String> importClasses = getImportClasses(methods, intDecl);
649 List<String> stdImportClasses = getStandardJavaImportClasses();
650 List<String> allImportClasses = getAllImportClasses(stdImportClasses, importClasses);
651 printImportStatements(allImportClasses); println("");
652 // Find out if there are callback objects
653 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
654 boolean callbackExist = !callbackClasses.isEmpty();
655 // Write class header
656 println("public class " + newStubClass + " implements " + newIntface + " {\n");
658 writePropertiesJavaStub(intface, newIntface, callbackExist, callbackClasses);
660 writeConstructorJavaStub(newStubClass, callbackExist, callbackClasses);
662 writeMethodJavaStub(intMeth.getValue(), intDecl, callbackClasses);
665 System.out.println("IoTCompiler: Generated stub class " + newStubClass + ".java...");
672 * HELPER: writePropertiesJavaCallbackStub() writes the properties of the callback stub class
674 private void writePropertiesJavaCallbackStub(String intface, String newIntface, boolean callbackExist, Set<String> callbackClasses) {
676 println("private IoTRMICall rmiCall;");
677 println("private String address;");
678 println("private int[] ports;\n");
680 println("private static int objectId = 0;");
682 // We assume that each class only has one callback interface for now
683 Iterator it = callbackClasses.iterator();
684 String callbackType = (String) it.next();
685 println("// Callback properties");
686 println("private IoTRMIObject rmiObj;");
687 println("List<" + callbackType + "> listCallbackObj;");
688 println("private static int objIdCnt = 0;");
695 * HELPER: writeConstructorJavaCallbackStub() writes the constructor of the callback stub class
697 private void writeConstructorJavaCallbackStub(String intface, boolean callbackExist, Set<String> callbackClasses) {
699 // TODO: If we want callback in callback, then we need to add address and port initializations
700 println("public " + intface + "(IoTRMICall _rmiCall, int _objectId) throws Exception {");
701 println("objectId = _objectId;");
702 println("rmiCall = _rmiCall;");
704 Iterator it = callbackClasses.iterator();
705 String callbackType = (String) it.next();
706 println("listCallbackObj = new ArrayList<" + callbackType + ">();");
707 println("___initCallBack();");
708 println("// TODO: Add address and port initialization here if we want callback in callback!");
715 * generateJavaCallbackStubClasses() generate callback stubs based on the methods list in Java
717 * Callback stubs gets the IoTRMICall objects from outside of the class as contructor input
718 * because all these stubs are populated by the class that takes in this object as a callback
719 * object. In such a class, we only use one socket, hence one IoTRMICall, for all callback objects.
721 public void generateJavaCallbackStubClasses() throws IOException {
723 // Create a new directory
724 String path = createDirectories(dir, subdir);
725 for (String intface : mapIntfacePTH.keySet()) {
727 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
728 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
730 // Open a new file to write into
731 String newIntface = intMeth.getKey();
732 String newStubClass = newIntface + "_CallbackStub";
733 FileWriter fw = new FileWriter(path + "/" + newStubClass + ".java");
734 pw = new PrintWriter(new BufferedWriter(fw));
735 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
736 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
737 // Pass in set of methods and get import classes
738 Set<String> methods = intMeth.getValue();
739 Set<String> importClasses = getImportClasses(methods, intDecl);
740 List<String> stdImportClasses = getStandardJavaImportClasses();
741 List<String> allImportClasses = getAllImportClasses(stdImportClasses, importClasses);
742 printImportStatements(allImportClasses); println("");
743 // Find out if there are callback objects
744 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
745 boolean callbackExist = !callbackClasses.isEmpty();
746 // Write class header
747 println("public class " + newStubClass + " implements " + newIntface + " {\n");
749 writePropertiesJavaCallbackStub(intface, newIntface, callbackExist, callbackClasses);
751 writeConstructorJavaCallbackStub(newStubClass, callbackExist, callbackClasses);
753 // TODO: perhaps need to generate callback for callback
754 writeMethodJavaStub(intMeth.getValue(), intDecl, callbackClasses);
757 System.out.println("IoTCompiler: Generated callback stub class " + newStubClass + ".java...");
764 * HELPER: writePropertiesJavaSkeleton() writes the properties of the skeleton class
766 private void writePropertiesJavaSkeleton(String intface, boolean callbackExist) {
768 println("private " + intface + " mainObj;");
769 //println("private int ports;");
770 println("private IoTRMIObject rmiObj;\n");
773 println("private static int objIdCnt = 0;");
774 println("private IoTRMICall rmiCall;");
776 // Keep track of object Ids of all stubs registered to this interface
777 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
778 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
779 String newIntface = intMeth.getKey();
780 int newObjectId = mapNewIntfaceObjId.get(newIntface);
781 println("private final static int object" + newObjectId + "Id = " +
782 newObjectId + ";\t//" + newIntface);
789 * HELPER: writeConstructorJavaSkeleton() writes the constructor of the skeleton class
791 private void writeConstructorJavaSkeleton(String newSkelClass, String intface) {
793 println("public " + newSkelClass + "(" + intface + " _mainObj, int _port) throws Exception {");
794 println("mainObj = _mainObj;");
795 println("rmiObj = new IoTRMIObject(_port);");
796 //println("set0Allowed = Arrays.asList(object0Permission);");
797 println("___waitRequestInvokeMethod();");
803 * HELPER: writeStdMethodBodyJavaSkeleton() writes the standard method body in the skeleton class
805 private void writeStdMethodBodyJavaSkeleton(List<String> methParams, String methodId, String methodType) {
807 if (methodType.equals("void"))
808 print("mainObj." + methodId + "(");
810 print("return mainObj." + methodId + "(");
811 for (int i = 0; i < methParams.size(); i++) {
813 print(getSimpleIdentifier(methParams.get(i)));
814 // Check if this is the last element (don't print a comma)
815 if (i != methParams.size() - 1) {
824 * HELPER: writeInitCallbackJavaSkeleton() writes the init callback method for skeleton class
826 private void writeInitCallbackJavaSkeleton(boolean callbackSkeleton) {
828 // This is a callback skeleton generation
829 if (callbackSkeleton)
830 println("public void ___regCB(IoTRMIObject rmiObj) throws IOException {");
832 println("public void ___regCB() throws IOException {");
833 println("Object[] paramObj = rmiObj.getMethodParams(new Class<?>[] { int.class, String.class, int.class },");
834 println("\tnew Class<?>[] { null, null, null });");
835 println("rmiCall = new IoTRMICall((int) paramObj[0], (String) paramObj[1], (int) paramObj[2]);");
841 * HELPER: writeMethodJavaSkeleton() writes the method of the skeleton class
843 private void writeMethodJavaSkeleton(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses,
844 boolean callbackSkeleton) {
846 for (String method : methods) {
848 List<String> methParams = intDecl.getMethodParams(method);
849 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
850 String methodId = intDecl.getMethodId(method);
851 print("public " + intDecl.getMethodType(method) + " " + methodId + "(");
852 boolean isCallbackMethod = false;
853 String callbackType = null;
854 for (int i = 0; i < methParams.size(); i++) {
856 String origParamType = methPrmTypes.get(i);
857 String paramType = checkAndGetParamClass(origParamType, false);
858 if (callbackClasses != null) { // Check if this has callback object
859 if (callbackClasses.contains(origParamType)) {
860 isCallbackMethod = true;
861 callbackType = origParamType;
864 print(paramType + " " + methParams.get(i));
865 // Check if this is the last element (don't print a comma)
866 if (i != methParams.size() - 1) {
871 // Now, write the body of skeleton!
872 writeStdMethodBodyJavaSkeleton(methParams, methodId, intDecl.getMethodType(method));
874 if (isCallbackMethod)
875 writeInitCallbackJavaSkeleton(callbackSkeleton);
881 * HELPER: writeCallbackStubGeneration() writes the callback stub generation part
883 private Map<Integer,String> writeCallbackStubGeneration(List<String> methParams, List<String> methPrmTypes, String callbackType) {
885 Map<Integer,String> mapStubParam = new HashMap<Integer,String>();
886 // Iterate over callback objects
887 for (int i = 0; i < methParams.size(); i++) {
888 String paramType = methPrmTypes.get(i);
889 String param = methParams.get(i);
890 //if (callbackType.equals(paramType)) {
891 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
893 String exchParamType = checkAndGetParamClass(paramType, false);
894 // Print array if this is array or list if this is a list of callback objects
895 if (isArray(paramType, param)) {
896 println("int numStubs" + i + " = (int) paramObj[" + i + "];");
897 println(exchParamType + "[] stub" + i + " = new " + exchParamType + "[numStubs" + i + "];");
898 } else if (isList(paramType, param)) {
899 println("int numStubs" + i + " = (int) paramObj[" + i + "];");
900 println("List<" + exchParamType + "> stub" + i + " = new ArrayList<" + exchParamType + ">();");
902 println(exchParamType + " stub" + i + " = new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt);");
903 println("objIdCnt++;");
906 // Generate a loop if needed
907 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
908 String exchParamType = checkAndGetParamClass(paramType, false);
909 if (isArray(paramType, param)) {
910 println("for (int objId = 0; objId < numStubs" + i + "; objId++) {");
911 println("stub" + i + "[objId] = new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt);");
912 println("objIdCnt++;");
914 } else if (isList(paramType, param)) {
915 println("for (int objId = 0; objId < numStubs" + i + "; objId++) {");
916 println("stub" + i + ".add(new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt));");
917 println("objIdCnt++;");
921 mapStubParam.put(i, "stub" + i); // List of all stub parameters
928 * HELPER: writeStdMethodHelperBodyJavaSkeleton() writes the standard method body helper in the skeleton class
930 private void writeStdMethodHelperBodyJavaSkeleton(InterfaceDecl intDecl, List<String> methParams,
931 List<String> methPrmTypes, String method, Set<String> callbackClasses) {
932 // Generate array of parameter objects
933 boolean isCallbackMethod = false;
934 String callbackType = null;
935 print("Object[] paramObj = rmiObj.getMethodParams(new Class<?>[] { ");
936 for (int i = 0; i < methParams.size(); i++) {
937 String paramType = methPrmTypes.get(i);
938 if (getParamCategory(paramType) == ParamCategory.NONPRIMITIVES)
939 paramType = getTypeOfGeneric(paramType)[0];
940 if (callbackClasses != null) {
941 if (callbackClasses.contains(paramType)) {
942 isCallbackMethod = true;
943 callbackType = paramType;
946 String prmType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
947 print(getSimpleType(prmType) + ".class");
949 } else { // Generate normal classes if it's not a callback object
950 String prmType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
951 print(getSimpleType(prmType) + ".class");
953 if (i != methParams.size() - 1)
957 // Generate generic class if it's a generic type.. null otherwise
958 print("new Class<?>[] { ");
959 for (int i = 0; i < methParams.size(); i++) {
960 String prmType = methPrmTypes.get(i);
961 if (getParamCategory(prmType) == ParamCategory.NONPRIMITIVES)
962 print(getTypeOfGeneric(prmType)[0] + ".class");
965 if (i != methParams.size() - 1)
969 Map<Integer,String> mapStubParam = null;
970 if (isCallbackMethod)
971 mapStubParam = writeCallbackStubGeneration(methParams, methPrmTypes, callbackType);
972 // Check if this is "void"
973 String retType = intDecl.getMethodType(method);
974 if (retType.equals("void")) {
975 print(intDecl.getMethodId(method) + "(");
976 } else { // We do have a return value
977 print("Object retObj = " + intDecl.getMethodId(method) + "(");
979 for (int i = 0; i < methParams.size(); i++) {
981 if (isCallbackMethod) {
982 print(mapStubParam.get(i)); // Get the callback parameter
984 String prmType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
985 print("(" + prmType + ") paramObj[" + i + "]");
987 if (i != methParams.size() - 1)
991 if (!retType.equals("void"))
992 println("rmiObj.sendReturnObj(retObj);");
993 if (isCallbackMethod) { // Catch exception if this is callback
994 println("} catch(Exception ex) {");
995 println("ex.printStackTrace();");
996 println("throw new Error(\"Exception from callback object instantiation!\");");
1003 * HELPER: writeMethodHelperJavaSkeleton() writes the method helper of the skeleton class
1005 private void writeMethodHelperJavaSkeleton(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
1007 // Use this set to handle two same methodIds
1008 Set<String> uniqueMethodIds = new HashSet<String>();
1009 for (String method : methods) {
1011 List<String> methParams = intDecl.getMethodParams(method);
1012 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1013 String methodId = intDecl.getMethodId(method);
1014 print("public void ___");
1015 String helperMethod = methodId;
1016 if (uniqueMethodIds.contains(methodId))
1017 helperMethod = helperMethod + intDecl.getMethodNumId(method);
1019 uniqueMethodIds.add(methodId);
1020 // Check if this is "void"
1021 String retType = intDecl.getMethodType(method);
1022 if (retType.equals("void"))
1023 println(helperMethod + "() {");
1025 println(helperMethod + "() throws IOException {");
1026 // Now, write the helper body of skeleton!
1027 writeStdMethodHelperBodyJavaSkeleton(intDecl, methParams, methPrmTypes, method, callbackClasses);
1034 * HELPER: writeJavaWaitRequestInvokeMethod() writes the main loop of the skeleton class
1036 private void writeJavaWaitRequestInvokeMethod(Collection<String> methods, InterfaceDecl intDecl, boolean callbackExist) {
1038 // Use this set to handle two same methodIds
1039 Set<String> uniqueMethodIds = new HashSet<String>();
1040 println("private void ___waitRequestInvokeMethod() throws IOException {");
1041 // Write variables here if we have callbacks or enums or structs
1042 println("while (true) {");
1043 println("rmiObj.getMethodBytes();");
1044 println("int _objectId = rmiObj.getObjectId();");
1045 println("int methodId = rmiObj.getMethodId();");
1046 // TODO: code the permission check here!
1047 println("switch (methodId) {");
1048 // Print methods and method Ids
1049 for (String method : methods) {
1050 String methodId = intDecl.getMethodId(method);
1051 int methodNumId = intDecl.getMethodNumId(method);
1052 print("case " + methodNumId + ": ___");
1053 String helperMethod = methodId;
1054 if (uniqueMethodIds.contains(methodId))
1055 helperMethod = helperMethod + methodNumId;
1057 uniqueMethodIds.add(methodId);
1058 println(helperMethod + "(); break;");
1060 String method = "___initCallBack()";
1061 // Print case -9999 (callback handler) if callback exists
1062 if (callbackExist) {
1063 int methodId = intDecl.getHelperMethodNumId(method);
1064 println("case " + methodId + ": ___regCB(); break;");
1066 println("default: ");
1067 println("throw new Error(\"Method Id \" + methodId + \" not recognized!\");");
1075 * generateJavaSkeletonClass() generate skeletons based on the methods list in Java
1077 public void generateJavaSkeletonClass() throws IOException {
1079 // Create a new directory
1080 String path = createDirectories(dir, subdir);
1081 for (String intface : mapIntfacePTH.keySet()) {
1082 // Open a new file to write into
1083 String newSkelClass = intface + "_Skeleton";
1084 FileWriter fw = new FileWriter(path + "/" + newSkelClass + ".java");
1085 pw = new PrintWriter(new BufferedWriter(fw));
1086 // Pass in set of methods and get import classes
1087 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
1088 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
1089 List<String> methods = intDecl.getMethods();
1090 Set<String> importClasses = getImportClasses(methods, intDecl);
1091 List<String> stdImportClasses = getStandardJavaImportClasses();
1092 List<String> allImportClasses = getAllImportClasses(stdImportClasses, importClasses);
1093 printImportStatements(allImportClasses);
1094 // Find out if there are callback objects
1095 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
1096 boolean callbackExist = !callbackClasses.isEmpty();
1097 // Write class header
1099 println("public class " + newSkelClass + " implements " + intface + " {\n");
1101 writePropertiesJavaSkeleton(intface, callbackExist);
1102 // Write constructor
1103 writeConstructorJavaSkeleton(newSkelClass, intface);
1105 writeMethodJavaSkeleton(methods, intDecl, callbackClasses, false);
1106 // Write method helper
1107 writeMethodHelperJavaSkeleton(methods, intDecl, callbackClasses);
1108 // Write waitRequestInvokeMethod() - main loop
1109 writeJavaWaitRequestInvokeMethod(methods, intDecl, callbackExist);
1112 System.out.println("IoTCompiler: Generated skeleton class " + newSkelClass + ".java...");
1118 * HELPER: writePropertiesJavaCallbackSkeleton() writes the properties of the callback skeleton class
1120 private void writePropertiesJavaCallbackSkeleton(String intface, boolean callbackExist) {
1122 println("private " + intface + " mainObj;");
1123 // For callback skeletons, this is its own object Id
1124 println("private static int objectId = 0;");
1126 if (callbackExist) {
1127 println("private static int objIdCnt = 0;");
1128 println("private IoTRMICall rmiCall;");
1135 * HELPER: writeConstructorJavaCallbackSkeleton() writes the constructor of the skeleton class
1137 private void writeConstructorJavaCallbackSkeleton(String newSkelClass, String intface) {
1139 println("public " + newSkelClass + "(" + intface + " _mainObj, int _objectId) throws Exception {");
1140 println("mainObj = _mainObj;");
1141 println("objectId = _objectId;");
1147 * HELPER: writeMethodHelperJavaCallbackSkeleton() writes the method helper of the callback skeleton class
1149 private void writeMethodHelperJavaCallbackSkeleton(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
1151 // Use this set to handle two same methodIds
1152 Set<String> uniqueMethodIds = new HashSet<String>();
1153 for (String method : methods) {
1155 List<String> methParams = intDecl.getMethodParams(method);
1156 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1157 String methodId = intDecl.getMethodId(method);
1158 print("public void ___");
1159 String helperMethod = methodId;
1160 if (uniqueMethodIds.contains(methodId))
1161 helperMethod = helperMethod + intDecl.getMethodNumId(method);
1163 uniqueMethodIds.add(methodId);
1164 // Check if this is "void"
1165 String retType = intDecl.getMethodType(method);
1166 if (retType.equals("void"))
1167 println(helperMethod + "(IoTRMIObject rmiObj) {");
1169 println(helperMethod + "(IoTRMIObject rmiObj) throws IOException {");
1170 // Now, write the helper body of skeleton!
1171 writeStdMethodHelperBodyJavaSkeleton(intDecl, methParams, methPrmTypes, method, callbackClasses);
1178 * HELPER: writeJavaCallbackWaitRequestInvokeMethod() writes the main loop of the skeleton class
1180 private void writeJavaCallbackWaitRequestInvokeMethod(Collection<String> methods, InterfaceDecl intDecl, boolean callbackExist) {
1182 // Use this set to handle two same methodIds
1183 Set<String> uniqueMethodIds = new HashSet<String>();
1184 println("public void invokeMethod(IoTRMIObject rmiObj) throws IOException {");
1185 // Write variables here if we have callbacks or enums or structs
1186 println("int methodId = rmiObj.getMethodId();");
1187 // TODO: code the permission check here!
1188 println("switch (methodId) {");
1189 // Print methods and method Ids
1190 for (String method : methods) {
1191 String methodId = intDecl.getMethodId(method);
1192 int methodNumId = intDecl.getMethodNumId(method);
1193 print("case " + methodNumId + ": ___");
1194 String helperMethod = methodId;
1195 if (uniqueMethodIds.contains(methodId))
1196 helperMethod = helperMethod + methodNumId;
1198 uniqueMethodIds.add(methodId);
1199 println(helperMethod + "(rmiObj); break;");
1201 String method = "___initCallBack()";
1202 // Print case -9999 (callback handler) if callback exists
1203 if (callbackExist) {
1204 int methodId = intDecl.getHelperMethodNumId(method);
1205 println("case " + methodId + ": ___regCB(rmiObj); break;");
1207 println("default: ");
1208 println("throw new Error(\"Method Id \" + methodId + \" not recognized!\");");
1215 * generateJavaCallbackSkeletonClass() generate callback skeletons based on the methods list in Java
1217 public void generateJavaCallbackSkeletonClass() throws IOException {
1219 // Create a new directory
1220 String path = createDirectories(dir, subdir);
1221 for (String intface : mapIntfacePTH.keySet()) {
1222 // Open a new file to write into
1223 String newSkelClass = intface + "_CallbackSkeleton";
1224 FileWriter fw = new FileWriter(path + "/" + newSkelClass + ".java");
1225 pw = new PrintWriter(new BufferedWriter(fw));
1226 // Pass in set of methods and get import classes
1227 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
1228 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
1229 List<String> methods = intDecl.getMethods();
1230 Set<String> importClasses = getImportClasses(methods, intDecl);
1231 List<String> stdImportClasses = getStandardJavaImportClasses();
1232 List<String> allImportClasses = getAllImportClasses(stdImportClasses, importClasses);
1233 printImportStatements(allImportClasses);
1234 // Find out if there are callback objects
1235 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
1236 boolean callbackExist = !callbackClasses.isEmpty();
1237 // Write class header
1239 println("public class " + newSkelClass + " implements " + intface + " {\n");
1241 writePropertiesJavaCallbackSkeleton(intface, callbackExist);
1242 // Write constructor
1243 writeConstructorJavaCallbackSkeleton(newSkelClass, intface);
1245 writeMethodJavaSkeleton(methods, intDecl, callbackClasses, true);
1246 // Write method helper
1247 writeMethodHelperJavaCallbackSkeleton(methods, intDecl, callbackClasses);
1248 // Write waitRequestInvokeMethod() - main loop
1249 writeJavaCallbackWaitRequestInvokeMethod(methods, intDecl, callbackExist);
1252 System.out.println("IoTCompiler: Generated callback skeleton class " + newSkelClass + ".java...");
1258 * HELPER: writeMethodCplusInterface() writes the method of the interface
1260 private void writeMethodCplusInterface(Collection<String> methods, InterfaceDecl intDecl) {
1262 for (String method : methods) {
1264 List<String> methParams = intDecl.getMethodParams(method);
1265 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1266 print("virtual " + checkAndGetCplusType(intDecl.getMethodType(method)) + " " +
1267 intDecl.getMethodId(method) + "(");
1268 for (int i = 0; i < methParams.size(); i++) {
1269 // Check for params with driver class types and exchange it
1270 // with its remote interface
1271 //String paramType = checkAndGetParamClass(methPrmTypes.get(i), true);
1272 String paramType = methPrmTypes.get(i);
1273 paramType = checkAndGetCplusType(paramType);
1274 // Check for arrays - translate into vector in C++
1275 String paramComplete = checkAndGetCplusArray(paramType, methParams.get(i));
1276 print(paramComplete);
1277 // Check if this is the last element (don't print a comma)
1278 if (i != methParams.size() - 1) {
1288 * HELPER: writeEnumCplus() writes the enumeration declaration
1290 private void writeEnumCplus(EnumDecl enumDecl) {
1292 Set<String> enumTypes = enumDecl.getEnumDeclarations();
1293 // Iterate over enum declarations
1294 for (String enType : enumTypes) {
1296 println("enum " + enType + " {");
1297 List<String> enumMembers = enumDecl.getMembers(enType);
1298 for (int i = 0; i < enumMembers.size(); i++) {
1300 String member = enumMembers.get(i);
1302 // Check if this is the last element (don't print a comma)
1303 if (i != enumMembers.size() - 1)
1314 * HELPER: writeStructCplus() writes the struct declaration
1316 private void writeStructCplus(StructDecl structDecl) {
1318 List<String> structTypes = structDecl.getStructTypes();
1319 // Iterate over enum declarations
1320 for (String stType : structTypes) {
1322 println("struct " + stType + " {");
1323 List<String> structMemberTypes = structDecl.getMemberTypes(stType);
1324 List<String> structMembers = structDecl.getMembers(stType);
1325 for (int i = 0; i < structMembers.size(); i++) {
1327 String memberType = structMemberTypes.get(i);
1328 String member = structMembers.get(i);
1329 String structTypeC = checkAndGetCplusType(memberType);
1330 String structComplete = checkAndGetCplusArray(structTypeC, member);
1331 println(structComplete + ";");
1339 * generateCplusLocalInterfaces() writes the local interfaces and provides type-checking.
1341 * It needs to rewrite and exchange USERDEFINED types in input parameters of stub
1342 * and original interfaces, e.g. exchange Camera and CameraWithVideoAndRecording.
1343 * The local interface has to be the input parameter for the stub and the stub
1344 * interface has to be the input parameter for the local class.
1346 public void generateCplusLocalInterfaces() throws IOException {
1348 // Create a new directory
1349 createDirectory(dir);
1350 for (String intface : mapIntfacePTH.keySet()) {
1351 // Open a new file to write into
1352 FileWriter fw = new FileWriter(dir + "/" + intface + ".hpp");
1353 pw = new PrintWriter(new BufferedWriter(fw));
1354 // Write file headers
1355 println("#ifndef _" + intface.toUpperCase() + "_HPP__");
1356 println("#define _" + intface.toUpperCase() + "_HPP__");
1357 println("#include <iostream>");
1358 // Pass in set of methods and get include classes
1359 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
1360 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
1361 List<String> methods = intDecl.getMethods();
1362 Set<String> includeClasses = getIncludeClasses(methods, intDecl);
1363 printIncludeStatements(includeClasses); println("");
1364 println("using namespace std;\n");
1365 // Write enum if any...
1366 EnumDecl enumDecl = (EnumDecl) decHandler.getEnumDecl(intface);
1367 writeEnumCplus(enumDecl);
1368 // Write struct if any...
1369 StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
1370 writeStructCplus(structDecl);
1371 println("class " + intface); println("{");
1374 writeMethodCplusInterface(methods, intDecl);
1378 System.out.println("IoTCompiler: Generated local interface " + intface + ".hpp...");
1384 * generateCPlusInterfaces() generate stub interfaces based on the methods list in C++
1386 * For C++ we use virtual classe as interface
1388 public void generateCPlusInterfaces() throws IOException {
1390 // Create a new directory
1391 String path = createDirectories(dir, subdir);
1392 for (String intface : mapIntfacePTH.keySet()) {
1394 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
1395 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
1397 // Open a new file to write into
1398 String newIntface = intMeth.getKey();
1399 FileWriter fw = new FileWriter(path + "/" + newIntface + ".hpp");
1400 pw = new PrintWriter(new BufferedWriter(fw));
1401 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
1402 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
1403 // Write file headers
1404 println("#ifndef _" + newIntface.toUpperCase() + "_HPP__");
1405 println("#define _" + newIntface.toUpperCase() + "_HPP__");
1406 println("#include <iostream>");
1407 // Pass in set of methods and get import classes
1408 Set<String> includeClasses = getIncludeClasses(intMeth.getValue(), intDecl);
1409 List<String> stdIncludeClasses = getStandardCplusIncludeClasses();
1410 List<String> allIncludeClasses = getAllImportClasses(stdIncludeClasses, includeClasses);
1411 printIncludeStatements(allIncludeClasses); println("");
1412 println("using namespace std;\n");
1413 println("class " + newIntface);
1417 writeMethodCplusInterface(intMeth.getValue(), intDecl);
1421 System.out.println("IoTCompiler: Generated interface " + newIntface + ".hpp...");
1428 * HELPER: writeMethodCplusStub() writes the method of the stub
1430 private void writeMethodCplusStub(Collection<String> methods, InterfaceDecl intDecl) {
1432 for (String method : methods) {
1434 List<String> methParams = intDecl.getMethodParams(method);
1435 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1436 print(checkAndGetCplusType(intDecl.getMethodType(method)) + " " +
1437 intDecl.getMethodId(method) + "(");
1438 for (int i = 0; i < methParams.size(); i++) {
1440 //String paramType = checkAndGetParamClass(methPrmTypes.get(i), true);
1441 String paramType = methPrmTypes.get(i);
1442 String methPrmType = checkAndGetCplusType(paramType);
1443 String methParamComplete = checkAndGetCplusArray(methPrmType, methParams.get(i));
1444 print(methParamComplete);
1445 // Check if this is the last element (don't print a comma)
1446 if (i != methParams.size() - 1) {
1451 writeStdMethodBodyCplusStub(intDecl, methParams, methPrmTypes, method);
1458 * HELPER: writeStdMethodBodyCplusStub() writes the standard method body in the stub class
1460 private void writeStdMethodBodyCplusStub(InterfaceDecl intDecl, List<String> methParams,
1461 List<String> methPrmTypes, String method) {
1463 println("int numParam = " + methParams.size() + ";");
1464 println("int methodId = " + intDecl.getMethodNumId(method) + ";");
1465 String retType = intDecl.getMethodType(method);
1466 String retTypeC = checkAndGetCplusType(retType);
1467 println("string retType = \"" + checkAndGetCplusArrayType(retTypeC) + "\";");
1468 // Generate array of parameter types
1469 print("string paramCls[] = { ");
1470 for (int i = 0; i < methParams.size(); i++) {
1471 String paramTypeC = checkAndGetCplusType(methPrmTypes.get(i));
1472 String paramType = checkAndGetCplusArrayType(paramTypeC, methParams.get(i));
1473 print("\"" + paramType + "\"");
1474 // Check if this is the last element (don't print a comma)
1475 if (i != methParams.size() - 1) {
1480 // Generate array of parameter objects
1481 print("void* paramObj[] = { ");
1482 for (int i = 0; i < methParams.size(); i++) {
1483 print("&" + checkAndGetCplusType(getSimpleIdentifier(methParams.get(i))));
1484 // Check if this is the last element (don't print a comma)
1485 if (i != methParams.size() - 1) {
1490 // Check if this is "void"
1491 if (retType.equals("void")) {
1492 println("void* retObj = NULL;");
1493 println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
1494 } else { // We do have a return value
1495 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
1496 println(checkAndGetCplusType(retType) + " retVal;");
1498 println(checkAndGetCplusType(retType) + " retVal = " + generateCplusInitializer(retType) + ";");
1499 println("void* retObj = &retVal;");
1500 println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
1501 println("return retVal;");
1507 * HELPER: writePropertiesCplusStub() writes the properties of the stub class
1509 private void writePropertiesCplusStub(String intface, String newIntface) {
1511 println("IoTRMICall *rmiCall;");
1512 //println("IoTRMIObject\t\t\t*rmiObj;");
1513 println("string address;");
1514 println("vector<int> ports;\n");
1515 // Get the object Id
1516 Integer objId = mapIntfaceObjId.get(intface);
1517 println("const static int objectId = " + objId + ";");
1518 mapNewIntfaceObjId.put(newIntface, objId);
1519 mapIntfaceObjId.put(intface, objId++);
1525 * HELPER: writeConstructorCplusStub() writes the constructor of the stub class
1527 private void writeConstructorCplusStub(String newStubClass) {
1529 println(newStubClass +
1530 "(int _port, const char* _address, int _rev, bool* _bResult, vector<int> _ports) {");
1531 println("address = _address;");
1532 println("ports = _ports;");
1533 println("rmiCall = new IoTRMICall(_port, _address, _rev, _bResult);");
1539 * HELPER: writeDeconstructorCplusStub() writes the deconstructor of the stub class
1541 private void writeDeconstructorCplusStub(String newStubClass) {
1543 println("~" + newStubClass + "() {");
1544 println("if (rmiCall != NULL) {");
1545 println("delete rmiCall;");
1546 println("rmiCall = NULL;");
1550 // Check if this is callback!!! and print "delete rmiObj and vecCBObj"
1555 * generateCPlusStubClasses() generate stubs based on the methods list in C++
1557 public void generateCPlusStubClasses() throws IOException {
1559 // Create a new directory
1560 String path = createDirectories(dir, subdir);
1561 for (String intface : mapIntfacePTH.keySet()) {
1563 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
1564 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
1565 // Open a new file to write into
1566 String newIntface = intMeth.getKey();
1567 String newStubClass = newIntface + "_Stub";
1568 FileWriter fw = new FileWriter(path + "/" + newStubClass + ".hpp");
1569 pw = new PrintWriter(new BufferedWriter(fw));
1570 // Write file headers
1571 println("#ifndef _" + newStubClass.toUpperCase() + "_HPP__");
1572 println("#define _" + newStubClass.toUpperCase() + "_HPP__");
1573 println("#include <iostream>");
1574 println("#include \"" + newIntface + ".hpp\""); println("");
1575 println("using namespace std;"); println("");
1576 println("class " + newStubClass + " : public " + newIntface); println("{");
1577 println("private:\n");
1578 writePropertiesCplusStub(intface, newIntface);
1579 println("public:\n");
1580 // Add default constructor and destructor
1581 println(newStubClass + "() { }"); println("");
1582 writeConstructorCplusStub(newStubClass);
1583 writeDeconstructorCplusStub(newStubClass);
1584 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
1585 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
1587 writeMethodCplusStub(intMeth.getValue(), intDecl);
1588 print("}"); println(";");
1591 System.out.println("IoTCompiler: Generated stub class " + newIntface + ".hpp...");
1598 * HELPER: writePropertiesCplusCallbackStub() writes the properties of the stub class
1600 private void writePropertiesCplusCallbackStub(String intface, String newIntface) {
1602 println("IoTRMICall *rmiCall;");
1603 // Get the object Id
1604 println("static int objectId;");
1610 * HELPER: writeConstructorCplusCallbackStub() writes the constructor of the stub class
1612 private void writeConstructorCplusCallbackStub(String newStubClass) {
1614 println(newStubClass + "(IoTRMICall* _rmiCall, int _objectId) {");
1615 println("objectId = _objectId;");
1616 println("rmiCall = _rmiCall;");
1622 * generateCPlusCallbackStubClasses() generate callback stubs based on the methods list in C++
1624 public void generateCPlusCallbackStubClasses() throws IOException {
1626 // Create a new directory
1627 String path = createDirectories(dir, subdir);
1628 for (String intface : mapIntfacePTH.keySet()) {
1630 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
1631 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
1632 // Open a new file to write into
1633 String newIntface = intMeth.getKey();
1634 String newStubClass = newIntface + "_CallbackStub";
1635 FileWriter fw = new FileWriter(path + "/" + newStubClass + ".hpp");
1636 pw = new PrintWriter(new BufferedWriter(fw));
1637 // Write file headers
1638 println("#ifndef _" + newStubClass.toUpperCase() + "_HPP__");
1639 println("#define _" + newStubClass.toUpperCase() + "_HPP__");
1640 println("#include <iostream>");
1641 println("#include \"" + newIntface + ".hpp\""); println("");
1642 println("using namespace std;"); println("");
1643 println("class " + newStubClass + " : public " + newIntface); println("{");
1644 println("private:\n");
1645 writePropertiesCplusCallbackStub(intface, newIntface);
1646 println("public:\n");
1647 // Add default constructor and destructor
1648 println(newStubClass + "() { }"); println("");
1649 writeConstructorCplusCallbackStub(newStubClass);
1650 writeDeconstructorCplusStub(newStubClass);
1651 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
1652 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
1654 writeMethodCplusStub(intMeth.getValue(), intDecl);
1655 print("}"); println(";");
1658 System.out.println("IoTCompiler: Generated callback stub class " + newIntface + ".hpp...");
1665 * HELPER: writePropertiesCplusSkeleton() writes the properties of the skeleton class
1667 private void writePropertiesCplusSkeleton(String intface) {
1669 println(intface + " *mainObj;");
1670 //println("private int ports;");
1671 //println("private IoTRMICall rmiCall;");
1672 println("IoTRMIObject *rmiObj;\n");
1673 // Keep track of object Ids of all stubs registered to this interface
1674 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
1675 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
1676 String newIntface = intMeth.getKey();
1677 int newObjectId = mapNewIntfaceObjId.get(newIntface);
1678 // println("const static int object" + newObjectId + "Id = " +
1679 // newObjectId + ";\t//" + newIntface);
1682 // TODO: code the set of allowed functions here
1688 * HELPER: writeConstructorCplusSkeleton() writes the constructor of the skeleton class
1690 private void writeConstructorCplusSkeleton(String newSkelClass, String intface) {
1692 println(newSkelClass + "(" + intface + " *_mainObj, int _port) {");
1693 println("bool _bResult = false;");
1694 println("mainObj = _mainObj;");
1695 println("rmiObj = new IoTRMIObject(_port, &_bResult);");
1696 //println("set0Allowed = Arrays.asList(object0Permission);");
1697 //println("___waitRequestInvokeMethod();");
1703 * HELPER: writeDeconstructorCplusSkeleton() writes the deconstructor of the skeleton class
1705 private void writeDeconstructorCplusSkeleton(String newSkelClass) {
1707 println("~" + newSkelClass + "() {");
1708 println("if (rmiObj != NULL) {");
1709 println("delete rmiObj;");
1710 println("rmiObj = NULL;");
1714 // Check if this is callback!!! and print "delete rmiObj and vecCBObj"
1719 * HELPER: writeStdMethodBodyCplusSkeleton() writes the standard method body in the skeleton class
1721 private void writeStdMethodBodyCplusSkeleton(List<String> methParams, String methodId, String methodType) {
1723 if (methodType.equals("void"))
1724 print("mainObj->" + methodId + "(");
1726 print("return mainObj->" + methodId + "(");
1727 for (int i = 0; i < methParams.size(); i++) {
1729 print(getSimpleIdentifier(methParams.get(i)));
1730 // Check if this is the last element (don't print a comma)
1731 if (i != methParams.size() - 1) {
1740 * HELPER: writeMethodCplusSkeleton() writes the method of the skeleton class
1742 private void writeMethodCplusSkeleton(Collection<String> methods, InterfaceDecl intDecl) {
1744 for (String method : methods) {
1746 List<String> methParams = intDecl.getMethodParams(method);
1747 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1748 String methodId = intDecl.getMethodId(method);
1749 String methodType = checkAndGetCplusType(intDecl.getMethodType(method));
1750 print(methodType + " " + methodId + "(");
1751 for (int i = 0; i < methParams.size(); i++) {
1753 String paramType = checkAndGetParamClass(methPrmTypes.get(i), true);
1754 String methPrmType = checkAndGetCplusType(paramType);
1755 String methParamComplete = checkAndGetCplusArray(methPrmType, methParams.get(i));
1756 print(methParamComplete);
1757 // Check if this is the last element (don't print a comma)
1758 if (i != methParams.size() - 1) {
1763 // Now, write the body of skeleton!
1764 writeStdMethodBodyCplusSkeleton(methParams, methodId, intDecl.getMethodType(method));
1771 * HELPER: writeStdMethodHelperBodyCplusSkeleton() writes the standard method body helper in the skeleton class
1773 private void writeStdMethodHelperBodyCplusSkeleton(InterfaceDecl intDecl, List<String> methParams,
1774 List<String> methPrmTypes, String method, String methodId) {
1776 // Generate array of parameter types
1777 print("string paramCls[] = { ");
1778 for (int i = 0; i < methParams.size(); i++) {
1779 String paramTypeC = checkAndGetCplusType(methPrmTypes.get(i));
1780 String paramType = checkAndGetCplusArrayType(paramTypeC, methParams.get(i));
1781 print("\"" + paramType + "\"");
1782 if (i != methParams.size() - 1) {
1787 println("int numParam = " + methParams.size() + ";");
1788 // Generate parameters
1789 for (int i = 0; i < methParams.size(); i++) {
1790 String methPrmType = checkAndGetCplusType(methPrmTypes.get(i));
1791 String methParamComplete = checkAndGetCplusArray(methPrmType, methParams.get(i));
1792 println(methParamComplete + ";");
1794 // Generate array of parameter objects
1795 print("void* paramObj[] = { ");
1796 for (int i = 0; i < methParams.size(); i++) {
1797 print("&" + getSimpleIdentifier(methParams.get(i)));
1798 if (i != methParams.size() - 1) {
1803 println("rmiObj->getMethodParams(paramCls, numParam, paramObj);");
1804 String retType = intDecl.getMethodType(method);
1805 // Check if this is "void"
1806 if (retType.equals("void")) {
1807 print(methodId + "(");
1808 for (int i = 0; i < methParams.size(); i++) {
1809 print(getSimpleIdentifier(methParams.get(i)));
1810 if (i != methParams.size() - 1) {
1815 } else { // We do have a return value
1816 print(checkAndGetCplusType(retType) + " retVal = " + methodId + "(");
1817 for (int i = 0; i < methParams.size(); i++) {
1818 print(getSimpleIdentifier(methParams.get(i)));
1819 if (i != methParams.size() - 1) {
1824 println("void* retObj = &retVal;");
1825 String retTypeC = checkAndGetCplusType(retType);
1826 println("rmiObj->sendReturnObj(retObj, \"" + checkAndGetCplusArrayType(retTypeC) + "\");");
1832 * HELPER: writeMethodHelperCplusSkeleton() writes the method helper of the skeleton class
1834 private void writeMethodHelperCplusSkeleton(Collection<String> methods, InterfaceDecl intDecl) {
1836 // Use this set to handle two same methodIds
1837 Set<String> uniqueMethodIds = new HashSet<String>();
1838 for (String method : methods) {
1840 List<String> methParams = intDecl.getMethodParams(method);
1841 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1842 String methodId = intDecl.getMethodId(method);
1844 String helperMethod = methodId;
1845 if (uniqueMethodIds.contains(methodId))
1846 helperMethod = helperMethod + intDecl.getMethodNumId(method);
1848 uniqueMethodIds.add(methodId);
1849 // Check if this is "void"
1850 String retType = intDecl.getMethodType(method);
1851 println(helperMethod + "() {");
1852 // Now, write the helper body of skeleton!
1853 writeStdMethodHelperBodyCplusSkeleton(intDecl, methParams, methPrmTypes, method, methodId);
1860 * HELPER: writeCplusWaitRequestInvokeMethod() writes the main loop of the skeleton class
1862 private void writeCplusWaitRequestInvokeMethod(Collection<String> methods, InterfaceDecl intDecl) {
1864 // Use this set to handle two same methodIds
1865 Set<String> uniqueMethodIds = new HashSet<String>();
1866 println("void ___waitRequestInvokeMethod() {");
1867 // Write variables here if we have callbacks or enums or structs
1868 println("while (true) {");
1869 println("rmiObj->getMethodBytes();");
1870 println("int _objectId = rmiObj->getObjectId();");
1871 println("int methodId = rmiObj->getMethodId();");
1872 // TODO: code the permission check here!
1873 println("switch (methodId) {");
1874 // Print methods and method Ids
1875 for (String method : methods) {
1876 String methodId = intDecl.getMethodId(method);
1877 int methodNumId = intDecl.getMethodNumId(method);
1878 print("case " + methodNumId + ": ___");
1879 String helperMethod = methodId;
1880 if (uniqueMethodIds.contains(methodId))
1881 helperMethod = helperMethod + methodNumId;
1883 uniqueMethodIds.add(methodId);
1884 println(helperMethod + "(); break;");
1886 println("default: ");
1887 println("cerr << \"Method Id \" << methodId << \" not recognized!\" << endl;");
1888 println("throw exception();");
1896 * generateCplusSkeletonClass() generate skeletons based on the methods list in C++
1898 public void generateCplusSkeletonClass() throws IOException {
1900 // Create a new directory
1901 String path = createDirectories(dir, subdir);
1902 for (String intface : mapIntfacePTH.keySet()) {
1903 // Open a new file to write into
1904 String newSkelClass = intface + "_Skeleton";
1905 FileWriter fw = new FileWriter(path + "/" + newSkelClass + ".hpp");
1906 pw = new PrintWriter(new BufferedWriter(fw));
1907 // Write file headers
1908 println("#ifndef _" + newSkelClass.toUpperCase() + "_HPP__");
1909 println("#define _" + newSkelClass.toUpperCase() + "_HPP__");
1910 println("#include <iostream>");
1911 println("#include \"" + intface + ".hpp\"\n");
1912 // Pass in set of methods and get import classes
1913 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
1914 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
1915 List<String> methods = intDecl.getMethods();
1916 Set<String> includeClasses = getIncludeClasses(methods, intDecl);
1917 List<String> stdIncludeClasses = getStandardCplusIncludeClasses();
1918 List<String> allIncludeClasses = getAllImportClasses(stdIncludeClasses, includeClasses);
1919 printIncludeStatements(allIncludeClasses); println("");
1920 println("using namespace std;\n");
1921 // Write class header
1922 println("class " + newSkelClass + " : public " + intface); println("{");
1923 println("private:\n");
1925 writePropertiesCplusSkeleton(intface);
1926 println("public:\n");
1927 // Write constructor
1928 writeConstructorCplusSkeleton(newSkelClass, intface);
1929 // Write deconstructor
1930 writeDeconstructorCplusSkeleton(newSkelClass);
1932 writeMethodCplusSkeleton(methods, intDecl);
1933 // Write method helper
1934 writeMethodHelperCplusSkeleton(methods, intDecl);
1935 // Write waitRequestInvokeMethod() - main loop
1936 writeCplusWaitRequestInvokeMethod(methods, intDecl);
1940 System.out.println("IoTCompiler: Generated skeleton class " + newSkelClass + ".hpp...");
1946 * HELPER: writePropertiesCplusCallbackSkeleton() writes the properties of the callback skeleton class
1948 private void writePropertiesCplusCallbackSkeleton(String intface) {
1950 println(intface + " *mainObj;");
1951 //println("IoTRMIObject *rmiObj;\n");
1952 // Keep track of object Ids of all stubs registered to this interface
1953 println("static int objectId;");
1959 * HELPER: writeConstructorCplusCallbackSkeleton() writes the constructor of the skeleton class
1961 private void writeConstructorCplusCallbackSkeleton(String newSkelClass, String intface) {
1963 println(newSkelClass + "(" + intface + " *_mainObj, int _objectId) {");
1964 println("mainObj = _mainObj;");
1965 println("objectId = _objectId;");
1971 * HELPER: writeMethodHelperCplusCallbackSkeleton() writes the method helper of the callback skeleton class
1973 private void writeMethodHelperCplusCallbackSkeleton(Collection<String> methods, InterfaceDecl intDecl) {
1975 // Use this set to handle two same methodIds
1976 Set<String> uniqueMethodIds = new HashSet<String>();
1977 for (String method : methods) {
1979 List<String> methParams = intDecl.getMethodParams(method);
1980 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1981 String methodId = intDecl.getMethodId(method);
1983 String helperMethod = methodId;
1984 if (uniqueMethodIds.contains(methodId))
1985 helperMethod = helperMethod + intDecl.getMethodNumId(method);
1987 uniqueMethodIds.add(methodId);
1988 // Check if this is "void"
1989 String retType = intDecl.getMethodType(method);
1990 println(helperMethod + "(IoTRMIObject* rmiObj) {");
1991 // Now, write the helper body of skeleton!
1992 writeStdMethodHelperBodyCplusSkeleton(intDecl, methParams, methPrmTypes, method, methodId);
1999 * HELPER: writeCplusCallbackWaitRequestInvokeMethod() writes the main loop of the skeleton class
2001 private void writeCplusCallbackWaitRequestInvokeMethod(Collection<String> methods, InterfaceDecl intDecl) {
2003 // Use this set to handle two same methodIds
2004 Set<String> uniqueMethodIds = new HashSet<String>();
2005 println("void invokeMethod(IoTRMIObject* rmiObj) {");
2006 // Write variables here if we have callbacks or enums or structs
2007 println("int methodId = rmiObj->getMethodId();");
2008 // TODO: code the permission check here!
2009 println("switch (methodId) {");
2010 // Print methods and method Ids
2011 for (String method : methods) {
2012 String methodId = intDecl.getMethodId(method);
2013 int methodNumId = intDecl.getMethodNumId(method);
2014 print("case " + methodNumId + ": ___");
2015 String helperMethod = methodId;
2016 if (uniqueMethodIds.contains(methodId))
2017 helperMethod = helperMethod + methodNumId;
2019 uniqueMethodIds.add(methodId);
2020 println(helperMethod + "(rmiObj); break;");
2022 println("default: ");
2023 println("cerr << \"Method Id \" << methodId << \" not recognized!\" << endl;");
2024 println("throw exception();");
2032 * generateCplusCallbackSkeletonClass() generate callback skeletons based on the methods list in C++
2034 public void generateCplusCallbackSkeletonClass() throws IOException {
2036 // Create a new directory
2037 String path = createDirectories(dir, subdir);
2038 for (String intface : mapIntfacePTH.keySet()) {
2039 // Open a new file to write into
2040 String newSkelClass = intface + "_CallbackSkeleton";
2041 FileWriter fw = new FileWriter(path + "/" + newSkelClass + ".hpp");
2042 pw = new PrintWriter(new BufferedWriter(fw));
2043 // Write file headers
2044 println("#ifndef _" + newSkelClass.toUpperCase() + "_HPP__");
2045 println("#define _" + newSkelClass.toUpperCase() + "_HPP__");
2046 println("#include <iostream>");
2047 println("#include \"" + intface + ".hpp\"\n");
2048 // Pass in set of methods and get import classes
2049 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2050 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
2051 List<String> methods = intDecl.getMethods();
2052 Set<String> includeClasses = getIncludeClasses(methods, intDecl);
2053 List<String> stdIncludeClasses = getStandardCplusIncludeClasses();
2054 List<String> allIncludeClasses = getAllImportClasses(stdIncludeClasses, includeClasses);
2055 printIncludeStatements(allIncludeClasses); println("");
2056 println("using namespace std;\n");
2057 // Write class header
2058 println("class " + newSkelClass + " : public " + intface); println("{");
2059 println("private:\n");
2061 writePropertiesCplusCallbackSkeleton(intface);
2062 println("public:\n");
2063 // Write constructor
2064 writeConstructorCplusCallbackSkeleton(newSkelClass, intface);
2065 // Write deconstructor
2066 //writeDeconstructorCplusSkeleton(newSkelClass);
2068 writeMethodCplusSkeleton(methods, intDecl);
2069 // Write method helper
2070 writeMethodHelperCplusCallbackSkeleton(methods, intDecl);
2071 // Write waitRequestInvokeMethod() - main loop
2072 writeCplusCallbackWaitRequestInvokeMethod(methods, intDecl);
2076 System.out.println("IoTCompiler: Generated callback skeleton class " + newSkelClass + ".hpp...");
2082 * generateInitializer() generate initializer based on type
2084 public String generateCplusInitializer(String type) {
2086 // Generate dummy returns for now
2087 if (type.equals("short")||
2088 type.equals("int") ||
2089 type.equals("long") ||
2090 type.equals("float")||
2091 type.equals("double")) {
2094 } else if ( type.equals("String") ||
2095 type.equals("string")) {
2098 } else if ( type.equals("char") ||
2099 type.equals("byte")) {
2102 } else if ( type.equals("boolean")) {
2112 * generateReturnStmt() generate return statement based on methType
2114 public String generateReturnStmt(String methType) {
2116 // Generate dummy returns for now
2117 if (methType.equals("short")||
2118 methType.equals("int") ||
2119 methType.equals("long") ||
2120 methType.equals("float")||
2121 methType.equals("double")) {
2124 } else if ( methType.equals("String")) {
2127 } else if ( methType.equals("char") ||
2128 methType.equals("byte")) {
2131 } else if ( methType.equals("boolean")) {
2141 * setDirectory() sets a new directory for stub files
2143 public void setDirectory(String _subdir) {
2150 * printUsage() prints the usage of this compiler
2152 public static void printUsage() {
2154 System.out.println();
2155 System.out.println("Sentinel interface and stub compiler version 1.0");
2156 System.out.println("Copyright (c) 2015-2016 University of California, Irvine - Programming Language Group.");
2157 System.out.println("All rights reserved.");
2158 System.out.println("Usage:");
2159 System.out.println("\tjava IoTCompiler -help / --help / -h\n");
2160 System.out.println("\t\tDisplay this help texts\n\n");
2161 System.out.println("\tjava IoTCompiler [<main-policy-file> <req-policy-file>]");
2162 System.out.println("\tjava IoTCompiler [<main-policy-file> <req-policy-file>] [options]\n");
2163 System.out.println("\t\tTake one or more pairs of main-req policy files, and generate Java and/or C++ files\n");
2164 System.out.println("Options:");
2165 System.out.println("\t-java\t<directory>\tGenerate Java stub files");
2166 System.out.println("\t-cplus\t<directory>\tGenerate C++ stub files");
2167 System.out.println();
2172 * parseFile() prepares Lexer and Parser objects, then parses the file
2174 public static ParseNode parseFile(String file) {
2176 ParseNode pn = null;
2178 ComplexSymbolFactory csf = new ComplexSymbolFactory();
2179 ScannerBuffer lexer =
2180 new ScannerBuffer(new Lexer(new BufferedReader(new FileReader(file)),csf));
2181 Parser parse = new Parser(lexer,csf);
2182 pn = (ParseNode) parse.parse().value;
2183 } catch (Exception e) {
2184 e.printStackTrace();
2185 throw new Error("IoTCompiler: ERROR parsing policy file or wrong command line option: " + file);
2196 boolean newline=true;
2199 private void print(String str) {
2202 if (str.equals("}"))
2204 for(int i=0; i<tab; i++)
2214 * This function converts Java to C++ type for compilation
2216 private String convertType(String jType) {
2218 return mapPrimitives.get(jType);
2222 private void println(String str) {
2225 if (str.equals("}"))
2227 for(int i=0; i<tab; i++)
2236 private void updatetabbing(String str) {
2237 tablevel+=count(str,'{')-count(str,'}');
2241 private int count(String str, char key) {
2242 char[] array = str.toCharArray();
2244 for(int i=0; i<array.length; i++) {
2245 if (array[i] == key)
2252 private void createDirectory(String dirName) {
2254 File file = new File(dirName);
2255 if (!file.exists()) {
2257 System.out.println("IoTCompiler: Directory " + dirName + " has been created!");
2259 System.out.println("IoTCompiler: Failed to create directory " + dirName + "!");
2262 System.out.println("IoTCompiler: Directory " + dirName + " exists...");
2267 // Create a directory and possibly a sub directory
2268 private String createDirectories(String dir, String subdir) {
2271 createDirectory(path);
2272 if (subdir != null) {
2273 path = path + "/" + subdir;
2274 createDirectory(path);
2280 // Inserting array members into a Map object
2281 // that maps arrKey to arrVal objects
2282 private void arraysToMap(Map map, Object[] arrKey, Object[] arrVal) {
2284 for(int i = 0; i < arrKey.length; i++) {
2286 map.put(arrKey[i], arrVal[i]);
2291 // Return parameter category, i.e. PRIMITIVES, NONPRIMITIVES, or USERDEFINED
2292 private ParamCategory getParamCategory(String paramType) {
2294 if (mapPrimitives.containsKey(paramType)) {
2295 return ParamCategory.PRIMITIVES;
2296 // We can either use mapNonPrimitivesJava or mapNonPrimitivesCplus here
2297 } else if (mapNonPrimitivesJava.containsKey(getSimpleType(paramType))) {
2298 return ParamCategory.NONPRIMITIVES;
2300 return ParamCategory.USERDEFINED;
2304 // Return full class name for non-primitives to generate Java import statements
2305 // e.g. java.util.Set for Set, java.util.Map for Map
2306 private String getNonPrimitiveJavaClass(String paramNonPrimitives) {
2308 return mapNonPrimitivesJava.get(paramNonPrimitives);
2312 // Return full class name for non-primitives to generate Cplus include statements
2313 // e.g. #include <set> for Set, #include <map> for Map
2314 private String getNonPrimitiveCplusClass(String paramNonPrimitives) {
2316 return mapNonPrimitivesCplus.get(paramNonPrimitives);
2320 // Get simple types, e.g. HashSet for HashSet<...>
2321 // Basically strip off the "<...>"
2322 private String getSimpleType(String paramType) {
2324 // Check if this is generics
2325 if(paramType.contains("<")) {
2326 String[] type = paramType.split("<");
2333 // Generate a set of standard classes for import statements
2334 private List<String> getStandardJavaImportClasses() {
2336 List<String> importClasses = new ArrayList<String>();
2337 // Add the standard list first
2338 importClasses.add("java.io.IOException");
2339 importClasses.add("java.util.List");
2340 importClasses.add("java.util.ArrayList");
2341 importClasses.add("iotrmi.Java.IoTRMICall");
2342 importClasses.add("iotrmi.Java.IoTRMIObject");
2344 return importClasses;
2348 // Generate a set of standard classes for import statements
2349 private List<String> getStandardCplusIncludeClasses() {
2351 List<String> importClasses = new ArrayList<String>();
2352 // Add the standard list first
2353 importClasses.add("<vector>");
2354 importClasses.add("\"IoTRMICall.hpp\"");
2355 importClasses.add("\"IoTRMIObject.hpp\"");
2357 return importClasses;
2361 // Generate a set of standard classes for import statements
2362 private List<String> getAllImportClasses(Collection<String> stdImportClasses, Collection<String> importClasses) {
2364 List<String> allImportClasses = new ArrayList<String>(stdImportClasses);
2365 // Iterate over the list of import classes
2366 for (String str : importClasses) {
2367 if (!stdImportClasses.contains(str)) {
2368 stdImportClasses.add(str);
2372 return allImportClasses;
2377 // Generate a set of classes for import statements
2378 private Set<String> getImportClasses(Collection<String> methods, InterfaceDecl intDecl) {
2380 Set<String> importClasses = new HashSet<String>();
2381 for (String method : methods) {
2382 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2383 for (String paramType : methPrmTypes) {
2385 String simpleType = getSimpleType(paramType);
2386 if (getParamCategory(simpleType) == ParamCategory.NONPRIMITIVES) {
2387 importClasses.add(getNonPrimitiveJavaClass(simpleType));
2391 return importClasses;
2395 // Generate a set of classes for include statements
2396 private Set<String> getIncludeClasses(Collection<String> methods, InterfaceDecl intDecl) {
2398 Set<String> includeClasses = new HashSet<String>();
2399 for (String method : methods) {
2401 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2402 List<String> methParams = intDecl.getMethodParams(method);
2403 for (int i = 0; i < methPrmTypes.size(); i++) {
2405 String simpleType = getSimpleType(methPrmTypes.get(i));
2406 String param = methParams.get(i);
2407 if (getParamCategory(simpleType) == ParamCategory.NONPRIMITIVES) {
2408 includeClasses.add("<" + getNonPrimitiveCplusClass(simpleType) + ">");
2409 } else if (getParamCategory(simpleType) == ParamCategory.USERDEFINED) {
2410 includeClasses.add("\"" + exchangeParamType(simpleType) + ".hpp\"");
2411 } else if (param.contains("[]")) {
2412 // Check if this is array for C++; translate into vector
2413 includeClasses.add("<vector>");
2417 return includeClasses;
2421 // Generate a set of callback classes
2422 private Set<String> getCallbackClasses(Collection<String> methods, InterfaceDecl intDecl) {
2424 Set<String> callbackClasses = new HashSet<String>();
2425 for (String method : methods) {
2427 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2428 List<String> methParams = intDecl.getMethodParams(method);
2429 for (int i = 0; i < methPrmTypes.size(); i++) {
2431 String type = methPrmTypes.get(i);
2432 if (getParamCategory(type) == ParamCategory.USERDEFINED) {
2433 callbackClasses.add(type);
2434 } else if (getParamCategory(type) == ParamCategory.NONPRIMITIVES) {
2435 // Can be a List<...> of callback objects ...
2436 String genericType = getTypeOfGeneric(type)[0];
2437 if (getParamCategory(type) == ParamCategory.USERDEFINED) {
2438 callbackClasses.add(type);
2443 return callbackClasses;
2447 private void printImportStatements(Collection<String> importClasses) {
2449 for(String cls : importClasses) {
2450 println("import " + cls + ";");
2455 private void printIncludeStatements(Collection<String> includeClasses) {
2457 for(String cls : includeClasses) {
2458 println("#include " + cls);
2463 // Get the C++ version of a non-primitive type
2464 // e.g. set for Set and map for Map
2465 // Input nonPrimitiveType has to be generics in format
2466 private String[] getTypeOfGeneric(String nonPrimitiveType) {
2468 // Handle <, >, and , for 2-type generic/template
2469 String[] substr = nonPrimitiveType.split("<")[1].split(">")[0].split(",");
2474 // This helper function strips off array declaration, e.g. D[] becomes D
2475 private String getSimpleIdentifier(String ident) {
2477 // Handle [ for array declaration
2478 String substr = ident;
2479 if (ident.contains("[]")) {
2480 substr = ident.split("\\[\\]")[0];
2486 private String checkAndGetCplusType(String paramType) {
2488 if (getParamCategory(paramType) == ParamCategory.PRIMITIVES) {
2489 return convertType(paramType);
2490 } else if (getParamCategory(paramType) == ParamCategory.NONPRIMITIVES) {
2492 // Check for generic/template format
2493 if (paramType.contains("<") && paramType.contains(">")) {
2495 String genericClass = getSimpleType(paramType);
2496 String[] genericType = getTypeOfGeneric(paramType);
2497 String cplusTemplate = null;
2498 if (genericType.length == 1) // Generic/template with one type
2499 cplusTemplate = getNonPrimitiveCplusClass(genericClass) +
2500 "<" + convertType(genericType[0]) + ">";
2501 else // Generic/template with two types
2502 cplusTemplate = getNonPrimitiveCplusClass(genericClass) +
2503 "<" + convertType(genericType[0]) + "," + convertType(genericType[1]) + ">";
2504 return cplusTemplate;
2506 return getNonPrimitiveCplusClass(paramType);
2508 // Just return it as is if it's not non-primitives
2513 // Detect array declaration, e.g. int A[],
2514 // then generate "int A[]" in C++ as "vector<int> A"
2515 private String checkAndGetCplusArray(String paramType, String param) {
2517 String paramComplete = null;
2518 // Check for array declaration
2519 if (param.contains("[]")) {
2520 paramComplete = "vector<" + paramType + "> " + param.replace("[]","");
2522 // Just return it as is if it's not an array
2523 paramComplete = paramType + " " + param;
2525 return paramComplete;
2529 // Detect array declaration, e.g. int A[],
2530 // then generate "int A[]" in C++ as "vector<int> A"
2531 // This method just returns the type
2532 private String checkAndGetCplusArrayType(String paramType) {
2534 String paramTypeRet = null;
2535 // Check for array declaration
2536 if (paramType.contains("[]")) {
2537 String type = paramType.split("\\[\\]")[0];
2538 paramTypeRet = checkAndGetCplusType(type) + "[]";
2539 } else if (paramType.contains("vector")) {
2540 // Just return it as is if it's not an array
2541 String type = paramType.split("<")[1].split(">")[0];
2542 paramTypeRet = checkAndGetCplusType(type) + "[]";
2544 paramTypeRet = paramType;
2546 return paramTypeRet;
2550 // Detect array declaration, e.g. int A[],
2551 // then generate "int A[]" in C++ as "vector<int> A"
2552 // This method just returns the type
2553 private String checkAndGetCplusArrayType(String paramType, String param) {
2555 String paramTypeRet = null;
2556 // Check for array declaration
2557 if (param.contains("[]")) {
2558 paramTypeRet = checkAndGetCplusType(paramType) + "[]";
2559 } else if (paramType.contains("vector")) {
2560 // Just return it as is if it's not an array
2561 String type = paramType.split("<")[1].split(">")[0];
2562 paramTypeRet = checkAndGetCplusType(type) + "[]";
2564 paramTypeRet = paramType;
2566 return paramTypeRet;
2570 // Detect array declaration, e.g. int A[],
2571 // then generate type "int[]"
2572 private String checkAndGetArray(String paramType, String param) {
2574 String paramTypeRet = null;
2575 // Check for array declaration
2576 if (param.contains("[]")) {
2577 paramTypeRet = paramType + "[]";
2579 // Just return it as is if it's not an array
2580 paramTypeRet = paramType;
2582 return paramTypeRet;
2586 // Is array or list?
2587 private boolean isArrayOrList(String paramType, String param) {
2589 // Check for array declaration
2590 if (isArray(paramType, param))
2592 else if (isList(paramType, param))
2599 // Is array or list?
2600 private boolean isArray(String paramType, String param) {
2602 // Check for array declaration
2603 if (param.contains("[]"))
2610 // Is array or list?
2611 private boolean isList(String paramType, String param) {
2613 // Check for array declaration
2614 if (paramType.contains("List"))
2621 // Get the right type for a callback object
2622 private String checkAndGetParamClass(String paramType, boolean needPtr) {
2624 // Check if this is generics
2625 if(getParamCategory(paramType) == ParamCategory.USERDEFINED) {
2626 // If true then return with pointer (C++)
2628 return exchangeParamType(paramType) + "*";
2629 else // Java, so no pointer needed
2630 return exchangeParamType(paramType);
2636 // Returns the other interface for type-checking purposes for USERDEFINED
2637 // classes based on the information provided in multiple policy files
2638 // e.g. return CameraWithXXX instead of Camera
2639 private String exchangeParamType(String intface) {
2641 // Param type that's passed is the interface name we need to look for
2642 // in the map of interfaces, based on available policy files.
2643 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2644 if (decHandler != null) {
2645 // We've found the required interface policy files
2646 RequiresDecl reqDecl = (RequiresDecl) decHandler.getRequiresDecl(intface);
2647 Set<String> setExchInt = reqDecl.getInterfaces();
2648 if (setExchInt.size() == 1) {
2649 Iterator iter = setExchInt.iterator();
2650 return (String) iter.next();
2652 throw new Error("IoTCompiler: Ambiguous stub interfaces: " + setExchInt.toString() +
2653 ". Only one new interface can be declared if the object " + intface +
2654 " needs to be passed in as an input parameter!");
2657 // NULL value - this means policy files missing
2658 throw new Error("IoTCompiler: Parameter type lookup failed for " + intface +
2659 "... Please provide the necessary policy files for user-defined types." +
2660 " If this is an array please type the brackets after the variable name," +
2661 " e.g. \"String str[]\", not \"String[] str\"." +
2662 " If this is a Collections (Java) / STL (C++) type, this compiler only" +
2663 " supports List/ArrayList (Java) or list (C++).");
2668 public static void main(String[] args) throws Exception {
2670 // If there is no argument or just "--help" or "-h", then invoke printUsage()
2671 if ((args[0].equals("-help") ||
2672 args[0].equals("--help")||
2673 args[0].equals("-h")) ||
2674 (args.length == 0)) {
2676 IoTCompiler.printUsage();
2678 } else if (args.length > 1) {
2680 IoTCompiler comp = new IoTCompiler();
2683 // Parse main policy file
2684 ParseNode pnPol = IoTCompiler.parseFile(args[i]);
2685 // Parse "requires" policy file
2686 ParseNode pnReq = IoTCompiler.parseFile(args[i+1]);
2687 // Get interface name
2688 String intface = ParseTreeHandler.getOrigIntface(pnPol);
2689 comp.setDataStructures(intface, pnPol, pnReq);
2690 comp.getMethodsForIntface(intface);
2692 // 1) Check if this is the last option before "-java" or "-cplus"
2693 // 2) Check if this is really the last option (no "-java" or "-cplus")
2694 } while(!args[i].equals("-java") &&
2695 !args[i].equals("-cplus") &&
2698 // Generate everything if we don't see "-java" or "-cplus"
2699 if (i == args.length) {
2700 comp.generateJavaLocalInterfaces();
2701 comp.generateJavaInterfaces();
2702 comp.generateJavaStubClasses();
2703 comp.generateJavaCallbackStubClasses();
2704 comp.generateJavaSkeletonClass();
2705 comp.generateJavaCallbackSkeletonClass();
2706 comp.generateCplusLocalInterfaces();
2707 comp.generateCPlusInterfaces();
2708 comp.generateCPlusStubClasses();
2709 comp.generateCPlusCallbackStubClasses();
2710 comp.generateCplusSkeletonClass();
2711 comp.generateCplusCallbackSkeletonClass();
2713 // Check other options
2714 while(i < args.length) {
2716 if (!args[i].equals("-java") &&
2717 !args[i].equals("-cplus")) {
2718 throw new Error("IoTCompiler: ERROR - unrecognized command line option: " + args[i]);
2720 if (i + 1 < args.length) {
2721 comp.setDirectory(args[i+1]);
2723 throw new Error("IoTCompiler: ERROR - please provide <directory> after option: " + args[i]);
2725 if (args[i].equals("-java")) {
2726 comp.generateJavaLocalInterfaces();
2727 comp.generateJavaInterfaces();
2728 comp.generateJavaStubClasses();
2729 comp.generateJavaCallbackStubClasses();
2730 comp.generateJavaSkeletonClass();
2731 comp.generateJavaCallbackSkeletonClass();
2733 comp.generateCplusLocalInterfaces();
2734 comp.generateCPlusInterfaces();
2735 comp.generateCPlusStubClasses();
2736 comp.generateCPlusCallbackStubClasses();
2737 comp.generateCplusSkeletonClass();
2738 comp.generateCplusCallbackSkeletonClass();
2745 // Need to at least have exactly 2 parameters, i.e. main policy file and requires file
2746 IoTCompiler.printUsage();
2747 throw new Error("IoTCompiler: At least two arguments (main and requires policy files) have to be provided!");