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.
72 STRUCT, // Struct type
73 USERDEFINED // Assumed as driver classes
79 public IoTCompiler() {
81 mapIntfacePTH = new HashMap<String,ParseTreeHandler>();
82 mapIntDeclHand = new HashMap<String,DeclarationHandler>();
83 mapInt2NewInts = new HashMap<String,Map<String,Set<String>>>();
84 mapIntfaceObjId = new HashMap<String,Integer>();
85 mapNewIntfaceObjId = new HashMap<String,Integer>();
86 mapPrimitives = new HashMap<String,String>();
87 arraysToMap(mapPrimitives, IoTRMITypes.primitivesJava, IoTRMITypes.primitivesCplus);
88 mapNonPrimitivesJava = new HashMap<String,String>();
89 arraysToMap(mapNonPrimitivesJava, IoTRMITypes.nonPrimitivesJava, IoTRMITypes.nonPrimitiveJavaLibs);
90 mapNonPrimitivesCplus = new HashMap<String,String>();
91 arraysToMap(mapNonPrimitivesCplus, IoTRMITypes.nonPrimitivesJava, IoTRMITypes.nonPrimitivesCplus);
93 dir = OUTPUT_DIRECTORY;
99 * setDataStructures() sets parse tree and other data structures based on policy files.
101 * It also generates parse tree (ParseTreeHandler) and
102 * copies useful information from parse tree into
103 * InterfaceDecl, CapabilityDecl, and RequiresDecl
105 * Additionally, the data structure handles are
106 * returned from tree-parsing for further process.
109 public void setDataStructures(String origInt, ParseNode pnPol, ParseNode pnReq) {
111 ParseTreeHandler ptHandler = new ParseTreeHandler(origInt, pnPol, pnReq);
112 DeclarationHandler decHandler = new DeclarationHandler();
113 // Process ParseNode and generate Declaration objects
115 ptHandler.processInterfaceDecl();
116 InterfaceDecl intDecl = ptHandler.getInterfaceDecl();
117 decHandler.addInterfaceDecl(origInt, intDecl);
119 ptHandler.processCapabilityDecl();
120 CapabilityDecl capDecl = ptHandler.getCapabilityDecl();
121 decHandler.addCapabilityDecl(origInt, capDecl);
123 ptHandler.processRequiresDecl();
124 RequiresDecl reqDecl = ptHandler.getRequiresDecl();
125 decHandler.addRequiresDecl(origInt, reqDecl);
127 ptHandler.processEnumDecl();
128 EnumDecl enumDecl = ptHandler.getEnumDecl();
129 decHandler.addEnumDecl(origInt, enumDecl);
131 ptHandler.processStructDecl();
132 StructDecl structDecl = ptHandler.getStructDecl();
133 decHandler.addStructDecl(origInt, structDecl);
135 mapIntfacePTH.put(origInt, ptHandler);
136 mapIntDeclHand.put(origInt, decHandler);
137 // Set object Id counter to 0 for each interface
138 mapIntfaceObjId.put(origInt, new Integer(0));
143 * getMethodsForIntface() reads for methods in the data structure
145 * It is going to give list of methods for a certain interface
146 * based on the declaration of capabilities.
148 public void getMethodsForIntface(String origInt) {
150 ParseTreeHandler ptHandler = mapIntfacePTH.get(origInt);
151 Map<String,Set<String>> mapNewIntMethods = new HashMap<String,Set<String>>();
152 // Get set of new interfaces, e.g. CameraWithCaptureAndData
153 // Generate this new interface with all the methods it needs
154 // from different capabilities it declares
155 DeclarationHandler decHandler = mapIntDeclHand.get(origInt);
156 RequiresDecl reqDecl = (RequiresDecl) decHandler.getRequiresDecl(origInt);
157 Set<String> setIntfaces = reqDecl.getInterfaces();
158 for (String strInt : setIntfaces) {
160 // Initialize a set of methods
161 Set<String> setMethods = new HashSet<String>();
162 // Get list of capabilities, e.g. ImageCapture, VideoRecording, etc.
163 List<String> listCapab = reqDecl.getCapabList(strInt);
164 for (String strCap : listCapab) {
166 // Get list of methods for each capability
167 CapabilityDecl capDecl = (CapabilityDecl) decHandler.getCapabilityDecl(origInt);
168 List<String> listCapabMeth = capDecl.getMethods(strCap);
169 for (String strMeth : listCapabMeth) {
171 // Add methods into setMethods
172 // This is to also handle redundancies (say two capabilities
173 // share the same methods)
174 setMethods.add(strMeth);
177 // Add interface and methods information into map
178 mapNewIntMethods.put(strInt, setMethods);
180 // Map the map of interface-methods to the original interface
181 mapInt2NewInts.put(origInt, mapNewIntMethods);
186 * HELPER: writeMethodJavaLocalInterface() writes the method of the interface
188 private void writeMethodJavaLocalInterface(Collection<String> methods, InterfaceDecl intDecl) {
190 for (String method : methods) {
192 List<String> methParams = intDecl.getMethodParams(method);
193 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
194 print("public " + intDecl.getMethodType(method) + " " +
195 intDecl.getMethodId(method) + "(");
196 for (int i = 0; i < methParams.size(); i++) {
197 // Check for params with driver class types and exchange it
198 // with its remote interface
199 String paramType = checkAndGetParamClass(methPrmTypes.get(i));
200 print(paramType + " " + methParams.get(i));
201 // Check if this is the last element (don't print a comma)
202 if (i != methParams.size() - 1) {
212 * HELPER: writeMethodJavaInterface() writes the method of the interface
214 private void writeMethodJavaInterface(Collection<String> methods, InterfaceDecl intDecl) {
216 for (String method : methods) {
218 List<String> methParams = intDecl.getMethodParams(method);
219 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
220 print("public " + intDecl.getMethodType(method) + " " +
221 intDecl.getMethodId(method) + "(");
222 for (int i = 0; i < methParams.size(); i++) {
223 // Check for params with driver class types and exchange it
224 // with its remote interface
225 String paramType = methPrmTypes.get(i);
226 print(paramType + " " + methParams.get(i));
227 // Check if this is the last element (don't print a comma)
228 if (i != methParams.size() - 1) {
238 * HELPER: generateEnumJava() writes the enumeration declaration
240 private void generateEnumJava() throws IOException {
242 // Create a new directory
243 createDirectory(dir);
244 for (String intface : mapIntfacePTH.keySet()) {
245 // Get the right EnumDecl
246 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
247 EnumDecl enumDecl = (EnumDecl) decHandler.getEnumDecl(intface);
248 Set<String> enumTypes = enumDecl.getEnumDeclarations();
249 // Iterate over enum declarations
250 for (String enType : enumTypes) {
251 // Open a new file to write into
252 FileWriter fw = new FileWriter(dir + "/" + enType + ".java");
253 pw = new PrintWriter(new BufferedWriter(fw));
254 println("public enum " + enType + " {");
255 List<String> enumMembers = enumDecl.getMembers(enType);
256 for (int i = 0; i < enumMembers.size(); i++) {
258 String member = enumMembers.get(i);
260 // Check if this is the last element (don't print a comma)
261 if (i != enumMembers.size() - 1)
268 System.out.println("IoTCompiler: Generated enum class " + enType + ".java...");
275 * HELPER: generateStructJava() writes the struct declaration
277 private void generateStructJava() throws IOException {
279 // Create a new directory
280 createDirectory(dir);
281 for (String intface : mapIntfacePTH.keySet()) {
282 // Get the right StructDecl
283 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
284 StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
285 List<String> structTypes = structDecl.getStructTypes();
286 // Iterate over enum declarations
287 for (String stType : structTypes) {
288 // Open a new file to write into
289 FileWriter fw = new FileWriter(dir + "/" + stType + ".java");
290 pw = new PrintWriter(new BufferedWriter(fw));
291 println("public class " + stType + " {");
292 List<String> structMemberTypes = structDecl.getMemberTypes(stType);
293 List<String> structMembers = structDecl.getMembers(stType);
294 for (int i = 0; i < structMembers.size(); i++) {
296 String memberType = structMemberTypes.get(i);
297 String member = structMembers.get(i);
298 println("public static " + memberType + " " + member + ";");
302 System.out.println("IoTCompiler: Generated struct class " + stType + ".java...");
309 * generateJavaLocalInterface() writes the local interface and provides type-checking.
311 * It needs to rewrite and exchange USERDEFINED types in input parameters of stub
312 * and original interfaces, e.g. exchange Camera and CameraWithVideoAndRecording.
313 * The local interface has to be the input parameter for the stub and the stub
314 * interface has to be the input parameter for the local class.
316 public void generateJavaLocalInterfaces() throws IOException {
318 // Create a new directory
319 createDirectory(dir);
320 for (String intface : mapIntfacePTH.keySet()) {
321 // Open a new file to write into
322 FileWriter fw = new FileWriter(dir + "/" + intface + ".java");
323 pw = new PrintWriter(new BufferedWriter(fw));
324 // Pass in set of methods and get import classes
325 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
326 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
327 List<String> methods = intDecl.getMethods();
328 Set<String> importClasses = getImportClasses(methods, intDecl);
329 printImportStatements(importClasses);
330 // Write interface header
332 println("public interface " + intface + " {");
333 // Write enum if any...
334 //EnumDecl enumDecl = (EnumDecl) decHandler.getEnumDecl(intface);
335 //writeEnumJava(enumDecl);
336 // Write struct if any...
337 //StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
338 //writeStructJava(structDecl);
340 writeMethodJavaLocalInterface(methods, intDecl);
343 System.out.println("IoTCompiler: Generated local interface " + intface + ".java...");
349 * generateJavaInterfaces() generate stub interfaces based on the methods list in Java
351 public void generateJavaInterfaces() throws IOException {
353 // Create a new directory
354 String path = createDirectories(dir, subdir);
355 for (String intface : mapIntfacePTH.keySet()) {
357 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
358 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
360 // Open a new file to write into
361 String newIntface = intMeth.getKey();
362 FileWriter fw = new FileWriter(path + "/" + newIntface + ".java");
363 pw = new PrintWriter(new BufferedWriter(fw));
364 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
365 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
366 // Pass in set of methods and get import classes
367 Set<String> importClasses = getImportClasses(intMeth.getValue(), intDecl);
368 printImportStatements(importClasses);
369 // Write interface header
371 println("public interface " + newIntface + " {\n");
373 writeMethodJavaInterface(intMeth.getValue(), intDecl);
376 System.out.println("IoTCompiler: Generated interface " + newIntface + ".java...");
383 * HELPER: writePropertiesJavaPermission() writes the permission in properties
385 private void writePropertiesJavaPermission(String intface, InterfaceDecl intDecl) {
387 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
388 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
389 String newIntface = intMeth.getKey();
390 int newObjectId = mapNewIntfaceObjId.get(newIntface);
391 println("private final static int object" + newObjectId + "Id = " +
392 newObjectId + ";\t//" + newIntface);
393 Set<String> methodIds = intMeth.getValue();
394 print("private static Integer[] object" + newObjectId + "Permission = { ");
396 for (String methodId : methodIds) {
397 int methodNumId = intDecl.getMethodNumId(methodId);
398 print(Integer.toString(methodNumId));
399 // Check if this is the last element (don't print a comma)
400 if (i != methodIds.size() - 1) {
406 println("private List<Integer> set" + newObjectId + "Allowed;");
412 * HELPER: writePropertiesJavaStub() writes the properties of the stub class
414 private void writePropertiesJavaStub(String intface, String newIntface, boolean callbackExist, Set<String> callbackClasses) {
416 println("private IoTRMICall rmiCall;");
417 println("private String address;");
418 println("private int[] ports;\n");
420 Integer objId = mapIntfaceObjId.get(intface);
421 println("private final static int objectId = " + objId + ";");
422 mapNewIntfaceObjId.put(newIntface, objId);
423 mapIntfaceObjId.put(intface, objId++);
425 // We assume that each class only has one callback interface for now
426 Iterator it = callbackClasses.iterator();
427 String callbackType = (String) it.next();
428 println("// Callback properties");
429 println("private IoTRMIObject rmiObj;");
430 println("List<" + callbackType + "> listCallbackObj;");
431 println("private static int objIdCnt = 0;");
432 // Generate permission stuff for callback stubs
433 DeclarationHandler decHandler = mapIntDeclHand.get(callbackType);
434 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(callbackType);
435 writePropertiesJavaPermission(callbackType, intDecl);
442 * HELPER: writeConstructorJavaPermission() writes the permission in constructor
444 private void writeConstructorJavaPermission(String intface) {
446 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
447 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
448 String newIntface = intMeth.getKey();
449 int newObjectId = mapNewIntfaceObjId.get(newIntface);
450 println("set" + newObjectId + "Allowed = Arrays.asList(object" + newObjectId +"Permission);");
456 * HELPER: writeConstructorJavaStub() writes the constructor of the stub class
458 private void writeConstructorJavaStub(String intface, String newStubClass, boolean callbackExist, Set<String> callbackClasses) {
460 println("public " + newStubClass + "(int _port, String _address, int _rev, int[] _ports) throws Exception {");
461 println("address = _address;");
462 println("ports = _ports;");
463 println("rmiCall = new IoTRMICall(_port, _address, _rev);");
465 Iterator it = callbackClasses.iterator();
466 String callbackType = (String) it.next();
467 writeConstructorJavaPermission(intface);
468 println("listCallbackObj = new ArrayList<" + callbackType + ">();");
469 println("___initCallBack();");
476 * HELPER: writeJavaMethodCallbackPermission() writes permission checks in stub for callbacks
478 private void writeJavaMethodCallbackPermission(String intface) {
480 println("int methodId = IoTRMIObject.getMethodId(method);");
481 // Get all the different stubs
482 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
483 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
484 String newIntface = intMeth.getKey();
485 int newObjectId = mapNewIntfaceObjId.get(newIntface);
486 println("if (!set" + newObjectId + "Allowed.contains(methodId)) {");
487 println("throw new Error(\"Callback object for " + intface + " is not allowed to access method: \" + methodId);");
494 * HELPER: writeConstructorJavaStub() writes the constructor of the stub class
496 private void writeInitCallbackJavaStub(String intface, InterfaceDecl intDecl) {
498 println("public void ___initCallBack() {");
499 // Generate main thread for callbacks
500 println("Thread thread = new Thread() {");
501 println("public void run() {");
503 println("rmiObj = new IoTRMIObject(ports[0]);");
504 println("while (true) {");
505 println("byte[] method = rmiObj.getMethodBytes();");
506 writeJavaMethodCallbackPermission(intface);
507 println("int objId = IoTRMIObject.getObjectId(method);");
508 println(intface + "_CallbackSkeleton skel = (" + intface + "_CallbackSkeleton) listCallbackObj.get(objId);");
509 println("if (skel != null) {");
510 println("skel.invokeMethod(rmiObj);");
512 println("throw new Error(\"" + intface + ": Object with Id \" + objId + \" not found!\");");
515 println("} catch (Exception ex) {");
516 println("ex.printStackTrace();");
517 println("throw new Error(\"Error instantiating class " + intface + "_CallbackSkeleton!\");");
521 println("thread.start();\n");
522 // Generate info sending part
523 String method = "___initCallBack()";
524 println("int methodId = " + intDecl.getHelperMethodNumId(method) + ";");
525 println("Class<?> retType = void.class;");
526 println("Class<?>[] paramCls = new Class<?>[] { int.class, String.class, int.class };");
527 println("Object[] paramObj = new Object[] { ports[0], address, 0 };");
528 println("rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
534 * HELPER: checkAndWriteEnumTypeJavaStub() writes the enum type (convert from enum to int)
536 private void checkAndWriteEnumTypeJavaStub(List<String> methParams, List<String> methPrmTypes) {
538 // Iterate and find enum declarations
539 for (int i = 0; i < methParams.size(); i++) {
540 String paramType = methPrmTypes.get(i);
541 String param = methParams.get(i);
542 String simpleType = getSimpleType(paramType);
543 if (isEnumClass(simpleType)) {
544 // Check if this is enum type
545 if (isArray(param)) { // An array
546 println("int len" + i + " = " + param + ".length;");
547 println("int paramEnum" + i + "[] = new int[len];");
548 println("for (int i = 0; i < len" + i + "; i++) {");
549 println("paramEnum" + i + "[i] = " + param + "[i].ordinal();");
551 } else if (isList(paramType)) { // A list
552 println("int len" + i + " = " + param + ".size();");
553 println("int paramEnum" + i + "[] = new int[len];");
554 println("for (int i = 0; i < len" + i + "; i++) {");
555 println("paramEnum" + i + "[i] = " + param + ".get(i).ordinal();");
557 } else { // Just one element
558 println("int paramEnum" + i + "[] = new int[1];");
559 println("paramEnum" + i + "[0] = " + param + ".ordinal();");
567 * HELPER: checkAndWriteEnumRetTypeJavaStub() writes the enum return type (convert from enum to int)
569 private void checkAndWriteEnumRetTypeJavaStub(String retType) {
571 // Strips off array "[]" for return type
572 String pureType = getSimpleArrayType(getSimpleType(retType));
573 // Take the inner type of generic
574 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
575 pureType = getTypeOfGeneric(retType)[0];
576 if (isEnumClass(pureType)) {
577 // Check if this is enum type
579 println("int[] retEnum = (int[]) retObj;");
580 println(pureType + "[] enumVals = " + pureType + ".values();");
581 if (isArray(retType)) { // An array
582 println("int retLen = retEnum.length;");
583 println(pureType + "[] enumRetVal = new " + pureType + "[retLen];");
584 println("for (int i = 0; i < retLen; i++) {");
585 println("enumRetVal[i] = enumVals[retEnum[i]];");
587 } else if (isList(retType)) { // A list
588 println("int retLen = retEnum.length;");
589 println("List<" + pureType + "> enumRetVal = new ArrayList<" + pureType + ">();");
590 println("for (int i = 0; i < retLen; i++) {");
591 println("enumRetVal.add(enumVals[retEnum[i]]);");
593 } else { // Just one element
594 println(pureType + " enumRetVal = enumVals[retEnum[0]];");
596 println("return enumRetVal;");
602 * HELPER: writeStdMethodBodyJavaStub() writes the standard method body in the stub class
604 private void writeStdMethodBodyJavaStub(InterfaceDecl intDecl, List<String> methParams,
605 List<String> methPrmTypes, String method) {
607 println("int methodId = " + intDecl.getMethodNumId(method) + ";");
608 String retType = intDecl.getMethodType(method);
609 println("Class<?> retType = " + getSimpleType(getEnumType(retType)) + ".class;");
610 checkAndWriteEnumTypeJavaStub(methParams, methPrmTypes);
611 // Generate array of parameter types
612 print("Class<?>[] paramCls = new Class<?>[] { ");
613 for (int i = 0; i < methParams.size(); i++) {
614 String paramType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
615 print(getSimpleType(getEnumType(paramType)) + ".class");
616 // Check if this is the last element (don't print a comma)
617 if (i != methParams.size() - 1) {
622 // Generate array of parameter objects
623 print("Object[] paramObj = new Object[] { ");
624 for (int i = 0; i < methParams.size(); i++) {
625 print(getEnumParam(methPrmTypes.get(i), getSimpleIdentifier(methParams.get(i)), i));
626 // Check if this is the last element (don't print a comma)
627 if (i != methParams.size() - 1) {
632 // Check if this is "void"
633 if (retType.equals("void")) {
634 println("rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
635 } else { // We do have a return value
636 // Check if the return value NONPRIMITIVES
637 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES) {
638 String[] retGenValType = getTypeOfGeneric(retType);
639 println("Class<?> retGenValType = " + retGenValType[0] + ".class;");
640 println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, retGenValType, paramCls, paramObj);");
641 println("return (" + retType + ")retObj;");
642 } else if (getParamCategory(retType) == ParamCategory.ENUM) {
643 // This is an enum type
644 println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
645 checkAndWriteEnumRetTypeJavaStub(retType);
647 println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
648 println("return (" + retType + ")retObj;");
655 * HELPER: returnGenericCallbackType() returns the callback type
657 private String returnGenericCallbackType(String paramType) {
659 if (getParamCategory(paramType) == ParamCategory.NONPRIMITIVES)
660 return getTypeOfGeneric(paramType)[0];
667 * HELPER: checkCallbackType() checks the callback type
669 private boolean checkCallbackType(String paramType, String callbackType) {
671 String prmType = returnGenericCallbackType(paramType);
672 return callbackType.equals(prmType);
677 * HELPER: writeCallbackMethodBodyJavaStub() writes the callback method of the stub class
679 private void writeCallbackMethodBodyJavaStub(InterfaceDecl intDecl, List<String> methParams,
680 List<String> methPrmTypes, String method, String callbackType) {
683 // Check if this is single object, array, or list of objects
684 for (int i = 0; i < methParams.size(); i++) {
686 String paramType = methPrmTypes.get(i);
687 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
688 String param = methParams.get(i);
689 if (isArrayOrList(paramType, param)) { // Generate loop
690 println("for (" + paramType + " cb : " + getSimpleIdentifier(param) + ") {");
691 println(callbackType + "_CallbackSkeleton skel = new " + callbackType + "_CallbackSkeleton(cb, objIdCnt++);");
693 println(callbackType + "_CallbackSkeleton skel = new " + callbackType + "_CallbackSkeleton(" +
694 getSimpleIdentifier(param) + ", objIdCnt++);");
695 println("listCallbackObj.add(skel);");
696 if (isArrayOrList(paramType, param))
700 println("} catch (Exception ex) {");
701 println("ex.printStackTrace();");
702 println("throw new Error(\"Exception when generating skeleton objects!\");");
704 println("int methodId = " + intDecl.getMethodNumId(method) + ";");
705 String retType = intDecl.getMethodType(method);
706 println("Class<?> retType = " + getSimpleType(getEnumType(retType)) + ".class;");
707 // Generate array of parameter types
708 print("Class<?>[] paramCls = new Class<?>[] { ");
709 for (int i = 0; i < methParams.size(); i++) {
710 String paramType = methPrmTypes.get(i);
711 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
713 } else { // Generate normal classes if it's not a callback object
714 String prmType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
715 print(getSimpleType(prmType) + ".class");
717 if (i != methParams.size() - 1) // Check if this is the last element
721 // Generate array of parameter objects
722 print("Object[] paramObj = new Object[] { ");
723 for (int i = 0; i < methParams.size(); i++) {
724 String paramType = methPrmTypes.get(i);
725 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
726 //if (isArray(methPrmTypes.get(i), methParams.get(i)))
727 if (isArray(methParams.get(i)))
728 print(getSimpleIdentifier(methParams.get(i)) + ".length");
729 else if (isList(methPrmTypes.get(i)))
730 print(getSimpleIdentifier(methParams.get(i)) + ".size()");
732 print("new Integer(1)");
734 print(getSimpleIdentifier(methParams.get(i)));
735 if (i != methParams.size() - 1)
739 // Check if this is "void"
740 if (retType.equals("void")) {
741 println("rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
742 } else { // We do have a return value
743 // Check if the return value NONPRIMITIVES
744 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES) {
745 String[] retGenValType = getTypeOfGeneric(retType);
746 println("Class<?> retGenValType = " + retGenValType[0] + ".class;");
747 println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, retGenValType, paramCls, paramObj);");
748 println("return (" + retType + ")retObj;");
750 println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
751 println("return (" + retType + ")retObj;");
758 * HELPER: writeMethodJavaStub() writes the method of the stub class
760 private void writeMethodJavaStub(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
762 for (String method : methods) {
764 List<String> methParams = intDecl.getMethodParams(method);
765 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
766 print("public " + intDecl.getMethodType(method) + " " +
767 intDecl.getMethodId(method) + "(");
768 boolean isCallbackMethod = false;
769 String callbackType = null;
770 for (int i = 0; i < methParams.size(); i++) {
772 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
773 // Check if this has callback object
774 if (callbackClasses.contains(paramType)) {
775 isCallbackMethod = true;
776 callbackType = paramType;
777 // Even if there're 2 callback arguments, we expect them to be of the same interface
779 print(methPrmTypes.get(i) + " " + methParams.get(i));
780 // Check if this is the last element (don't print a comma)
781 if (i != methParams.size() - 1) {
786 // Now, write the body of stub!
787 if (isCallbackMethod)
788 writeCallbackMethodBodyJavaStub(intDecl, methParams, methPrmTypes, method, callbackType);
790 writeStdMethodBodyJavaStub(intDecl, methParams, methPrmTypes, method);
792 // Write the init callback helper method
793 if (isCallbackMethod)
794 writeInitCallbackJavaStub(callbackType, intDecl);
800 * generateJavaStubClasses() generate stubs based on the methods list in Java
802 public void generateJavaStubClasses() throws IOException {
804 // Create a new directory
805 String path = createDirectories(dir, subdir);
806 for (String intface : mapIntfacePTH.keySet()) {
808 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
809 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
811 // Open a new file to write into
812 String newIntface = intMeth.getKey();
813 String newStubClass = newIntface + "_Stub";
814 FileWriter fw = new FileWriter(path + "/" + newStubClass + ".java");
815 pw = new PrintWriter(new BufferedWriter(fw));
816 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
817 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
818 // Pass in set of methods and get import classes
819 Set<String> methods = intMeth.getValue();
820 Set<String> importClasses = getImportClasses(methods, intDecl);
821 List<String> stdImportClasses = getStandardJavaImportClasses();
822 List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
823 printImportStatements(allImportClasses); println("");
824 // Find out if there are callback objects
825 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
826 boolean callbackExist = !callbackClasses.isEmpty();
827 // Write class header
828 println("public class " + newStubClass + " implements " + newIntface + " {\n");
830 writePropertiesJavaStub(intface, newIntface, callbackExist, callbackClasses);
832 writeConstructorJavaStub(intface, newStubClass, callbackExist, callbackClasses);
834 writeMethodJavaStub(intMeth.getValue(), intDecl, callbackClasses);
837 System.out.println("IoTCompiler: Generated stub class " + newStubClass + ".java...");
844 * HELPER: writePropertiesJavaCallbackStub() writes the properties of the callback stub class
846 private void writePropertiesJavaCallbackStub(String intface, String newIntface, boolean callbackExist, Set<String> callbackClasses) {
848 println("private IoTRMICall rmiCall;");
849 println("private String address;");
850 println("private int[] ports;\n");
852 println("private static int objectId = 0;");
854 // We assume that each class only has one callback interface for now
855 Iterator it = callbackClasses.iterator();
856 String callbackType = (String) it.next();
857 println("// Callback properties");
858 println("private IoTRMIObject rmiObj;");
859 println("List<" + callbackType + "> listCallbackObj;");
860 println("private static int objIdCnt = 0;");
861 // Generate permission stuff for callback stubs
862 DeclarationHandler decHandler = mapIntDeclHand.get(callbackType);
863 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(callbackType);
864 writePropertiesJavaPermission(callbackType, intDecl);
871 * HELPER: writeConstructorJavaCallbackStub() writes the constructor of the callback stub class
873 private void writeConstructorJavaCallbackStub(String intface, String newStubClass, boolean callbackExist, Set<String> callbackClasses) {
875 // TODO: If we want callback in callback, then we need to add address and port initializations
876 println("public " + newStubClass + "(IoTRMICall _rmiCall, int _objectId) throws Exception {");
877 println("objectId = _objectId;");
878 println("rmiCall = _rmiCall;");
880 Iterator it = callbackClasses.iterator();
881 String callbackType = (String) it.next();
882 writeConstructorJavaPermission(intface);
883 println("listCallbackObj = new ArrayList<" + callbackType + ">();");
884 println("___initCallBack();");
885 println("// TODO: Add address and port initialization here if we want callback in callback!");
892 * generateJavaCallbackStubClasses() generate callback stubs based on the methods list in Java
894 * Callback stubs gets the IoTRMICall objects from outside of the class as contructor input
895 * because all these stubs are populated by the class that takes in this object as a callback
896 * object. In such a class, we only use one socket, hence one IoTRMICall, for all callback objects.
898 public void generateJavaCallbackStubClasses() throws IOException {
900 // Create a new directory
901 String path = createDirectories(dir, subdir);
902 for (String intface : mapIntfacePTH.keySet()) {
904 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
905 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
907 // Open a new file to write into
908 String newIntface = intMeth.getKey();
909 String newStubClass = newIntface + "_CallbackStub";
910 FileWriter fw = new FileWriter(path + "/" + newStubClass + ".java");
911 pw = new PrintWriter(new BufferedWriter(fw));
912 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
913 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
914 // Pass in set of methods and get import classes
915 Set<String> methods = intMeth.getValue();
916 Set<String> importClasses = getImportClasses(methods, intDecl);
917 List<String> stdImportClasses = getStandardJavaImportClasses();
918 List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
919 printImportStatements(allImportClasses); println("");
920 // Find out if there are callback objects
921 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
922 boolean callbackExist = !callbackClasses.isEmpty();
923 // Write class header
924 println("public class " + newStubClass + " implements " + newIntface + " {\n");
926 writePropertiesJavaCallbackStub(intface, newIntface, callbackExist, callbackClasses);
928 writeConstructorJavaCallbackStub(intface, newStubClass, callbackExist, callbackClasses);
930 // TODO: perhaps need to generate callback for callback
931 writeMethodJavaStub(intMeth.getValue(), intDecl, callbackClasses);
934 System.out.println("IoTCompiler: Generated callback stub class " + newStubClass + ".java...");
941 * HELPER: writePropertiesJavaSkeleton() writes the properties of the skeleton class
943 private void writePropertiesJavaSkeleton(String intface, boolean callbackExist, InterfaceDecl intDecl) {
945 println("private " + intface + " mainObj;");
946 //println("private int ports;");
947 println("private IoTRMIObject rmiObj;\n");
950 println("private static int objIdCnt = 0;");
951 println("private IoTRMICall rmiCall;");
953 writePropertiesJavaPermission(intface, intDecl);
959 * HELPER: writeConstructorJavaSkeleton() writes the constructor of the skeleton class
961 private void writeConstructorJavaSkeleton(String newSkelClass, String intface) {
963 println("public " + newSkelClass + "(" + intface + " _mainObj, int _port) throws Exception {");
964 println("mainObj = _mainObj;");
965 println("rmiObj = new IoTRMIObject(_port);");
966 // Generate permission control initialization
967 writeConstructorJavaPermission(intface);
968 println("___waitRequestInvokeMethod();");
974 * HELPER: writeStdMethodBodyJavaSkeleton() writes the standard method body in the skeleton class
976 private void writeStdMethodBodyJavaSkeleton(List<String> methParams, String methodId, String methodType) {
978 if (methodType.equals("void"))
979 print("mainObj." + methodId + "(");
981 print("return mainObj." + methodId + "(");
982 for (int i = 0; i < methParams.size(); i++) {
984 print(getSimpleIdentifier(methParams.get(i)));
985 // Check if this is the last element (don't print a comma)
986 if (i != methParams.size() - 1) {
995 * HELPER: writeInitCallbackJavaSkeleton() writes the init callback method for skeleton class
997 private void writeInitCallbackJavaSkeleton(boolean callbackSkeleton) {
999 // This is a callback skeleton generation
1000 if (callbackSkeleton)
1001 println("public void ___regCB(IoTRMIObject rmiObj) throws IOException {");
1003 println("public void ___regCB() throws IOException {");
1004 println("Object[] paramObj = rmiObj.getMethodParams(new Class<?>[] { int.class, String.class, int.class },");
1005 println("\tnew Class<?>[] { null, null, null });");
1006 println("rmiCall = new IoTRMICall((int) paramObj[0], (String) paramObj[1], (int) paramObj[2]);");
1012 * HELPER: writeMethodJavaSkeleton() writes the method of the skeleton class
1014 private void writeMethodJavaSkeleton(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses,
1015 boolean callbackSkeleton) {
1017 for (String method : methods) {
1019 List<String> methParams = intDecl.getMethodParams(method);
1020 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1021 String methodId = intDecl.getMethodId(method);
1022 print("public " + intDecl.getMethodType(method) + " " + methodId + "(");
1023 boolean isCallbackMethod = false;
1024 String callbackType = null;
1025 for (int i = 0; i < methParams.size(); i++) {
1027 String origParamType = methPrmTypes.get(i);
1028 String paramType = checkAndGetParamClass(origParamType);
1029 if (callbackClasses.contains(origParamType)) { // Check if this has callback object
1030 isCallbackMethod = true;
1031 callbackType = origParamType;
1033 print(paramType + " " + methParams.get(i));
1034 // Check if this is the last element (don't print a comma)
1035 if (i != methParams.size() - 1) {
1040 // Now, write the body of skeleton!
1041 writeStdMethodBodyJavaSkeleton(methParams, methodId, intDecl.getMethodType(method));
1043 if (isCallbackMethod)
1044 writeInitCallbackJavaSkeleton(callbackSkeleton);
1050 * HELPER: writeCallbackJavaStubGeneration() writes the callback stub generation part
1052 private Map<Integer,String> writeCallbackJavaStubGeneration(List<String> methParams, List<String> methPrmTypes, String callbackType) {
1054 Map<Integer,String> mapStubParam = new HashMap<Integer,String>();
1055 // Iterate over callback objects
1056 for (int i = 0; i < methParams.size(); i++) {
1057 String paramType = methPrmTypes.get(i);
1058 String param = methParams.get(i);
1059 //if (callbackType.equals(paramType)) {
1060 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
1062 String exchParamType = checkAndGetParamClass(paramType);
1063 // Print array if this is array or list if this is a list of callback objects
1064 if (isArray(param)) {
1065 println("int numStubs" + i + " = (int) paramObj[" + i + "];");
1066 println(exchParamType + "[] stub" + i + " = new " + exchParamType + "[numStubs" + i + "];");
1067 } else if (isList(paramType)) {
1068 println("int numStubs" + i + " = (int) paramObj[" + i + "];");
1069 println("List<" + exchParamType + "> stub" + i + " = new ArrayList<" + exchParamType + ">();");
1071 println(exchParamType + " stub" + i + " = new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt);");
1072 println("objIdCnt++;");
1075 // Generate a loop if needed
1076 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
1077 String exchParamType = checkAndGetParamClass(paramType);
1078 if (isArray(param)) {
1079 println("for (int objId = 0; objId < numStubs" + i + "; objId++) {");
1080 println("stub" + i + "[objId] = new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt);");
1081 println("objIdCnt++;");
1083 } else if (isList(paramType)) {
1084 println("for (int objId = 0; objId < numStubs" + i + "; objId++) {");
1085 println("stub" + i + ".add(new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt));");
1086 println("objIdCnt++;");
1089 mapStubParam.put(i, "stub" + i); // List of all stub parameters
1092 return mapStubParam;
1097 * HELPER: checkAndWriteEnumTypeJavaSkeleton() writes the enum type (convert from enum to int)
1099 private void checkAndWriteEnumTypeJavaSkeleton(List<String> methParams, List<String> methPrmTypes) {
1101 // Iterate and find enum declarations
1102 for (int i = 0; i < methParams.size(); i++) {
1103 String paramType = methPrmTypes.get(i);
1104 String param = methParams.get(i);
1105 String simpleType = getSimpleType(paramType);
1106 if (isEnumClass(simpleType)) {
1107 // Check if this is enum type
1108 println("int paramInt" + i + "[] = (int[]) paramObj[" + i + "];");
1109 println(simpleType + "[] enumVals = " + simpleType + ".values();");
1110 if (isArray(param)) { // An array
1111 println("int len" + i + " = paramInt" + i + ".length;");
1112 println(simpleType + "[] paramEnum = new " + simpleType + "[len];");
1113 println("for (int i = 0; i < len" + i + "; i++) {");
1114 println("paramEnum[i] = enumVals[paramInt" + i + "[i]];");
1116 } else if (isList(paramType)) { // A list
1117 println("int len" + i + " = paramInt" + i + ".length;");
1118 println("List<" + simpleType + "> paramEnum = new ArrayList<" + simpleType + ">();");
1119 println("for (int i = 0; i < len" + i + "; i++) {");
1120 println("paramEnum.add(enumVals[paramInt" + i + "[i]]);");
1122 } else { // Just one element
1123 println(simpleType + " paramEnum" + i + " = enumVals[paramInt" + i + "[0]];");
1131 * HELPER: checkAndWriteEnumRetTypeJavaSkeleton() writes the enum return type (convert from enum to int)
1133 private void checkAndWriteEnumRetTypeJavaSkeleton(String retType, String methodId) {
1135 // Strips off array "[]" for return type
1136 String pureType = getSimpleArrayType(getSimpleType(retType));
1137 // Take the inner type of generic
1138 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
1139 pureType = getTypeOfGeneric(retType)[0];
1140 if (isEnumClass(pureType)) {
1141 // Check if this is enum type
1143 if (isArray(retType)) { // An array
1144 print(pureType + "[] retEnum = " + methodId + "(");
1145 } else if (isList(retType)) { // A list
1146 print("List<" + pureType + "> retEnum = " + methodId + "(");
1147 } else { // Just one element
1148 print(pureType + " retEnum = " + methodId + "(");
1155 * HELPER: checkAndWriteEnumRetConvJavaSkeleton() writes the enum return type (convert from enum to int)
1157 private void checkAndWriteEnumRetConvJavaSkeleton(String retType) {
1159 // Strips off array "[]" for return type
1160 String pureType = getSimpleArrayType(getSimpleType(retType));
1161 // Take the inner type of generic
1162 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
1163 pureType = getTypeOfGeneric(retType)[0];
1164 if (isEnumClass(pureType)) {
1165 // Check if this is enum type
1166 if (isArray(retType)) { // An array
1167 println("int retLen = retEnum.length;");
1168 println("int[] retEnumVal = new int[retLen];");
1169 println("for (int i = 0; i < retLen; i++) {");
1170 println("retEnumVal[i] = retEnum[i].ordinal();");
1172 } else if (isList(retType)) { // A list
1173 println("int retLen = retEnum.size();");
1174 println("List<" + pureType + "> retEnumVal = new ArrayList<" + pureType + ">();");
1175 println("for (int i = 0; i < retLen; i++) {");
1176 println("retEnumVal.add(retEnum[i].ordinal());");
1178 } else { // Just one element
1179 println("int[] retEnumVal = new int[1];");
1180 println("retEnumVal[0] = retEnum.ordinal();");
1182 println("Object retObj = retEnumVal;");
1188 * HELPER: writeStdMethodHelperBodyJavaSkeleton() writes the standard method body helper in the skeleton class
1190 private void writeStdMethodHelperBodyJavaSkeleton(InterfaceDecl intDecl, List<String> methParams,
1191 List<String> methPrmTypes, String method, Set<String> callbackClasses) {
1192 // Generate array of parameter objects
1193 boolean isCallbackMethod = false;
1194 String callbackType = null;
1195 print("Object[] paramObj = rmiObj.getMethodParams(new Class<?>[] { ");
1196 for (int i = 0; i < methParams.size(); i++) {
1198 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
1199 if (callbackClasses.contains(paramType)) {
1200 isCallbackMethod = true;
1201 callbackType = paramType;
1203 } else { // Generate normal classes if it's not a callback object
1204 String prmType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
1205 print(getSimpleType(getEnumType(prmType)) + ".class");
1207 if (i != methParams.size() - 1)
1211 // Generate generic class if it's a generic type.. null otherwise
1212 print("new Class<?>[] { ");
1213 for (int i = 0; i < methParams.size(); i++) {
1214 String prmType = methPrmTypes.get(i);
1215 if (getParamCategory(prmType) == ParamCategory.NONPRIMITIVES)
1216 print(getTypeOfGeneric(prmType)[0] + ".class");
1219 if (i != methParams.size() - 1)
1223 checkAndWriteEnumTypeJavaSkeleton(methParams, methPrmTypes);
1224 Map<Integer,String> mapStubParam = null;
1225 if (isCallbackMethod)
1226 mapStubParam = writeCallbackJavaStubGeneration(methParams, methPrmTypes, callbackType);
1227 // Check if this is "void"
1228 String retType = intDecl.getMethodType(method);
1229 if (retType.equals("void")) {
1230 print(intDecl.getMethodId(method) + "(");
1231 } else if (isEnumClass(getSimpleArrayType(getSimpleType(retType)))) { // Enum type
1232 checkAndWriteEnumRetTypeJavaSkeleton(retType, intDecl.getMethodId(method));
1233 } else { // We do have a return value
1234 print("Object retObj = " + intDecl.getMethodId(method) + "(");
1236 for (int i = 0; i < methParams.size(); i++) {
1238 if (isCallbackMethod) {
1239 print(mapStubParam.get(i)); // Get the callback parameter
1240 } else if (isEnumClass(getSimpleType(methPrmTypes.get(i)))) { // Enum class
1241 print(getEnumParam(methPrmTypes.get(i), methParams.get(i), i));
1243 String prmType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
1244 print("(" + prmType + ") paramObj[" + i + "]");
1246 if (i != methParams.size() - 1)
1250 if (!retType.equals("void")) {
1251 if (isEnumClass(getSimpleArrayType(getSimpleType(retType)))) // Enum type
1252 checkAndWriteEnumRetConvJavaSkeleton(retType);
1253 println("rmiObj.sendReturnObj(retObj);");
1255 if (isCallbackMethod) { // Catch exception if this is callback
1256 println("} catch(Exception ex) {");
1257 println("ex.printStackTrace();");
1258 println("throw new Error(\"Exception from callback object instantiation!\");");
1265 * HELPER: writeMethodHelperJavaSkeleton() writes the method helper of the skeleton class
1267 private void writeMethodHelperJavaSkeleton(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
1269 // Use this set to handle two same methodIds
1270 Set<String> uniqueMethodIds = new HashSet<String>();
1271 for (String method : methods) {
1273 List<String> methParams = intDecl.getMethodParams(method);
1274 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1275 String methodId = intDecl.getMethodId(method);
1276 print("public void ___");
1277 String helperMethod = methodId;
1278 if (uniqueMethodIds.contains(methodId))
1279 helperMethod = helperMethod + intDecl.getMethodNumId(method);
1281 uniqueMethodIds.add(methodId);
1282 // Check if this is "void"
1283 String retType = intDecl.getMethodType(method);
1284 if (retType.equals("void"))
1285 println(helperMethod + "() {");
1287 println(helperMethod + "() throws IOException {");
1288 // Now, write the helper body of skeleton!
1289 writeStdMethodHelperBodyJavaSkeleton(intDecl, methParams, methPrmTypes, method, callbackClasses);
1296 * HELPER: writeJavaMethodPermission() writes permission checks in skeleton
1298 private void writeJavaMethodPermission(String intface) {
1300 // Get all the different stubs
1301 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
1302 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
1303 String newIntface = intMeth.getKey();
1304 int newObjectId = mapNewIntfaceObjId.get(newIntface);
1305 println("if (_objectId == object" + newObjectId + "Id) {");
1306 println("if (!set" + newObjectId + "Allowed.contains(methodId)) {");
1307 println("throw new Error(\"Object with object Id: \" + _objectId + \" is not allowed to access method: \" + methodId);");
1310 println("throw new Error(\"Object Id: \" + _objectId + \" not recognized!\");");
1318 * HELPER: writeJavaWaitRequestInvokeMethod() writes the main loop of the skeleton class
1320 private void writeJavaWaitRequestInvokeMethod(Collection<String> methods, InterfaceDecl intDecl, boolean callbackExist, String intface) {
1322 // Use this set to handle two same methodIds
1323 Set<String> uniqueMethodIds = new HashSet<String>();
1324 println("private void ___waitRequestInvokeMethod() throws IOException {");
1325 // Write variables here if we have callbacks or enums or structs
1326 println("while (true) {");
1327 println("rmiObj.getMethodBytes();");
1328 println("int _objectId = rmiObj.getObjectId();");
1329 println("int methodId = rmiObj.getMethodId();");
1330 // Generate permission check
1331 writeJavaMethodPermission(intface);
1332 println("switch (methodId) {");
1333 // Print methods and method Ids
1334 for (String method : methods) {
1335 String methodId = intDecl.getMethodId(method);
1336 int methodNumId = intDecl.getMethodNumId(method);
1337 print("case " + methodNumId + ": ___");
1338 String helperMethod = methodId;
1339 if (uniqueMethodIds.contains(methodId))
1340 helperMethod = helperMethod + methodNumId;
1342 uniqueMethodIds.add(methodId);
1343 println(helperMethod + "(); break;");
1345 String method = "___initCallBack()";
1346 // Print case -9999 (callback handler) if callback exists
1347 if (callbackExist) {
1348 int methodId = intDecl.getHelperMethodNumId(method);
1349 println("case " + methodId + ": ___regCB(); break;");
1351 println("default: ");
1352 println("throw new Error(\"Method Id \" + methodId + \" not recognized!\");");
1360 * generateJavaSkeletonClass() generate skeletons based on the methods list in Java
1362 public void generateJavaSkeletonClass() throws IOException {
1364 // Create a new directory
1365 String path = createDirectories(dir, subdir);
1366 for (String intface : mapIntfacePTH.keySet()) {
1367 // Open a new file to write into
1368 String newSkelClass = intface + "_Skeleton";
1369 FileWriter fw = new FileWriter(path + "/" + newSkelClass + ".java");
1370 pw = new PrintWriter(new BufferedWriter(fw));
1371 // Pass in set of methods and get import classes
1372 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
1373 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
1374 List<String> methods = intDecl.getMethods();
1375 Set<String> importClasses = getImportClasses(methods, intDecl);
1376 List<String> stdImportClasses = getStandardJavaImportClasses();
1377 List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
1378 printImportStatements(allImportClasses);
1379 // Find out if there are callback objects
1380 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
1381 boolean callbackExist = !callbackClasses.isEmpty();
1382 // Write class header
1384 println("public class " + newSkelClass + " implements " + intface + " {\n");
1386 writePropertiesJavaSkeleton(intface, callbackExist, intDecl);
1387 // Write constructor
1388 writeConstructorJavaSkeleton(newSkelClass, intface);
1390 writeMethodJavaSkeleton(methods, intDecl, callbackClasses, false);
1391 // Write method helper
1392 writeMethodHelperJavaSkeleton(methods, intDecl, callbackClasses);
1393 // Write waitRequestInvokeMethod() - main loop
1394 writeJavaWaitRequestInvokeMethod(methods, intDecl, callbackExist, intface);
1397 System.out.println("IoTCompiler: Generated skeleton class " + newSkelClass + ".java...");
1403 * HELPER: writePropertiesJavaCallbackSkeleton() writes the properties of the callback skeleton class
1405 private void writePropertiesJavaCallbackSkeleton(String intface, boolean callbackExist) {
1407 println("private " + intface + " mainObj;");
1408 // For callback skeletons, this is its own object Id
1409 println("private static int objectId = 0;");
1411 if (callbackExist) {
1412 println("private static int objIdCnt = 0;");
1413 println("private IoTRMICall rmiCall;");
1420 * HELPER: writeConstructorJavaCallbackSkeleton() writes the constructor of the skeleton class
1422 private void writeConstructorJavaCallbackSkeleton(String newSkelClass, String intface) {
1424 println("public " + newSkelClass + "(" + intface + " _mainObj, int _objectId) throws Exception {");
1425 println("mainObj = _mainObj;");
1426 println("objectId = _objectId;");
1432 * HELPER: writeMethodHelperJavaCallbackSkeleton() writes the method helper of the callback skeleton class
1434 private void writeMethodHelperJavaCallbackSkeleton(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
1436 // Use this set to handle two same methodIds
1437 Set<String> uniqueMethodIds = new HashSet<String>();
1438 for (String method : methods) {
1440 List<String> methParams = intDecl.getMethodParams(method);
1441 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1442 String methodId = intDecl.getMethodId(method);
1443 print("public void ___");
1444 String helperMethod = methodId;
1445 if (uniqueMethodIds.contains(methodId))
1446 helperMethod = helperMethod + intDecl.getMethodNumId(method);
1448 uniqueMethodIds.add(methodId);
1449 // Check if this is "void"
1450 String retType = intDecl.getMethodType(method);
1451 if (retType.equals("void"))
1452 println(helperMethod + "(IoTRMIObject rmiObj) {");
1454 println(helperMethod + "(IoTRMIObject rmiObj) throws IOException {");
1455 // Now, write the helper body of skeleton!
1456 writeStdMethodHelperBodyJavaSkeleton(intDecl, methParams, methPrmTypes, method, callbackClasses);
1463 * HELPER: writeJavaCallbackWaitRequestInvokeMethod() writes the main loop of the skeleton class
1465 private void writeJavaCallbackWaitRequestInvokeMethod(Collection<String> methods, InterfaceDecl intDecl, boolean callbackExist) {
1467 // Use this set to handle two same methodIds
1468 Set<String> uniqueMethodIds = new HashSet<String>();
1469 println("public void invokeMethod(IoTRMIObject rmiObj) throws IOException {");
1470 // Write variables here if we have callbacks or enums or structs
1471 println("int methodId = rmiObj.getMethodId();");
1472 // TODO: code the permission check here!
1473 println("switch (methodId) {");
1474 // Print methods and method Ids
1475 for (String method : methods) {
1476 String methodId = intDecl.getMethodId(method);
1477 int methodNumId = intDecl.getMethodNumId(method);
1478 print("case " + methodNumId + ": ___");
1479 String helperMethod = methodId;
1480 if (uniqueMethodIds.contains(methodId))
1481 helperMethod = helperMethod + methodNumId;
1483 uniqueMethodIds.add(methodId);
1484 println(helperMethod + "(rmiObj); break;");
1486 String method = "___initCallBack()";
1487 // Print case -9999 (callback handler) if callback exists
1488 if (callbackExist) {
1489 int methodId = intDecl.getHelperMethodNumId(method);
1490 println("case " + methodId + ": ___regCB(rmiObj); break;");
1492 println("default: ");
1493 println("throw new Error(\"Method Id \" + methodId + \" not recognized!\");");
1500 * generateJavaCallbackSkeletonClass() generate callback skeletons based on the methods list in Java
1502 public void generateJavaCallbackSkeletonClass() throws IOException {
1504 // Create a new directory
1505 String path = createDirectories(dir, subdir);
1506 for (String intface : mapIntfacePTH.keySet()) {
1507 // Open a new file to write into
1508 String newSkelClass = intface + "_CallbackSkeleton";
1509 FileWriter fw = new FileWriter(path + "/" + newSkelClass + ".java");
1510 pw = new PrintWriter(new BufferedWriter(fw));
1511 // Pass in set of methods and get import classes
1512 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
1513 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
1514 List<String> methods = intDecl.getMethods();
1515 Set<String> importClasses = getImportClasses(methods, intDecl);
1516 List<String> stdImportClasses = getStandardJavaImportClasses();
1517 List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
1518 printImportStatements(allImportClasses);
1519 // Find out if there are callback objects
1520 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
1521 boolean callbackExist = !callbackClasses.isEmpty();
1522 // Write class header
1524 println("public class " + newSkelClass + " implements " + intface + " {\n");
1526 writePropertiesJavaCallbackSkeleton(intface, callbackExist);
1527 // Write constructor
1528 writeConstructorJavaCallbackSkeleton(newSkelClass, intface);
1530 writeMethodJavaSkeleton(methods, intDecl, callbackClasses, true);
1531 // Write method helper
1532 writeMethodHelperJavaCallbackSkeleton(methods, intDecl, callbackClasses);
1533 // Write waitRequestInvokeMethod() - main loop
1534 writeJavaCallbackWaitRequestInvokeMethod(methods, intDecl, callbackExist);
1537 System.out.println("IoTCompiler: Generated callback skeleton class " + newSkelClass + ".java...");
1543 * HELPER: writeMethodCplusLocalInterface() writes the method of the interface
1545 private void writeMethodCplusLocalInterface(Collection<String> methods, InterfaceDecl intDecl) {
1547 for (String method : methods) {
1549 List<String> methParams = intDecl.getMethodParams(method);
1550 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1551 print("virtual " + checkAndGetCplusType(intDecl.getMethodType(method)) + " " +
1552 intDecl.getMethodId(method) + "(");
1553 for (int i = 0; i < methParams.size(); i++) {
1554 // Check for params with driver class types and exchange it
1555 // with its remote interface
1556 String paramType = checkAndGetParamClass(methPrmTypes.get(i));
1557 paramType = checkAndGetCplusType(paramType);
1558 // Check for arrays - translate into vector in C++
1559 String paramComplete = checkAndGetCplusArray(paramType, methParams.get(i));
1560 print(paramComplete);
1561 // Check if this is the last element (don't print a comma)
1562 if (i != methParams.size() - 1) {
1572 * HELPER: writeMethodCplusInterface() writes the method of the interface
1574 private void writeMethodCplusInterface(Collection<String> methods, InterfaceDecl intDecl) {
1576 for (String method : methods) {
1578 List<String> methParams = intDecl.getMethodParams(method);
1579 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1580 print("virtual " + checkAndGetCplusType(intDecl.getMethodType(method)) + " " +
1581 intDecl.getMethodId(method) + "(");
1582 for (int i = 0; i < methParams.size(); i++) {
1583 // Check for params with driver class types and exchange it
1584 // with its remote interface
1585 String paramType = methPrmTypes.get(i);
1586 paramType = checkAndGetCplusType(paramType);
1587 // Check for arrays - translate into vector in C++
1588 String paramComplete = checkAndGetCplusArray(paramType, methParams.get(i));
1589 print(paramComplete);
1590 // Check if this is the last element (don't print a comma)
1591 if (i != methParams.size() - 1) {
1601 * HELPER: generateEnumCplus() writes the enumeration declaration
1603 public void generateEnumCplus() throws IOException {
1605 // Create a new directory
1606 createDirectory(dir);
1607 for (String intface : mapIntfacePTH.keySet()) {
1608 // Get the right StructDecl
1609 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
1610 EnumDecl enumDecl = (EnumDecl) decHandler.getEnumDecl(intface);
1611 Set<String> enumTypes = enumDecl.getEnumDeclarations();
1612 // Iterate over enum declarations
1613 for (String enType : enumTypes) {
1614 // Open a new file to write into
1615 FileWriter fw = new FileWriter(dir + "/" + enType + ".hpp");
1616 pw = new PrintWriter(new BufferedWriter(fw));
1617 // Write file headers
1618 println("#ifndef _" + enType.toUpperCase() + "_HPP__");
1619 println("#define _" + enType.toUpperCase() + "_HPP__");
1620 println("enum " + enType + " {");
1621 List<String> enumMembers = enumDecl.getMembers(enType);
1622 for (int i = 0; i < enumMembers.size(); i++) {
1624 String member = enumMembers.get(i);
1626 // Check if this is the last element (don't print a comma)
1627 if (i != enumMembers.size() - 1)
1635 System.out.println("IoTCompiler: Generated enum " + enType + ".hpp...");
1642 * HELPER: generateStructCplus() writes the struct declaration
1644 public void generateStructCplus() throws IOException {
1646 // Create a new directory
1647 createDirectory(dir);
1648 for (String intface : mapIntfacePTH.keySet()) {
1649 // Get the right StructDecl
1650 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
1651 StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
1652 List<String> structTypes = structDecl.getStructTypes();
1653 // Iterate over enum declarations
1654 for (String stType : structTypes) {
1655 // Open a new file to write into
1656 FileWriter fw = new FileWriter(dir + "/" + stType + ".hpp");
1657 pw = new PrintWriter(new BufferedWriter(fw));
1658 // Write file headers
1659 println("#ifndef _" + stType.toUpperCase() + "_HPP__");
1660 println("#define _" + stType.toUpperCase() + "_HPP__");
1661 println("struct " + stType + " {");
1662 List<String> structMemberTypes = structDecl.getMemberTypes(stType);
1663 List<String> structMembers = structDecl.getMembers(stType);
1664 for (int i = 0; i < structMembers.size(); i++) {
1666 String memberType = structMemberTypes.get(i);
1667 String member = structMembers.get(i);
1668 String structTypeC = checkAndGetCplusType(memberType);
1669 String structComplete = checkAndGetCplusArray(structTypeC, member);
1670 println(structComplete + ";");
1675 System.out.println("IoTCompiler: Generated struct " + stType + ".hpp...");
1682 * generateCplusLocalInterfaces() writes the local interfaces and provides type-checking.
1684 * It needs to rewrite and exchange USERDEFINED types in input parameters of stub
1685 * and original interfaces, e.g. exchange Camera and CameraWithVideoAndRecording.
1686 * The local interface has to be the input parameter for the stub and the stub
1687 * interface has to be the input parameter for the local class.
1689 public void generateCplusLocalInterfaces() throws IOException {
1691 // Create a new directory
1692 createDirectory(dir);
1693 for (String intface : mapIntfacePTH.keySet()) {
1694 // Open a new file to write into
1695 FileWriter fw = new FileWriter(dir + "/" + intface + ".hpp");
1696 pw = new PrintWriter(new BufferedWriter(fw));
1697 // Write file headers
1698 println("#ifndef _" + intface.toUpperCase() + "_HPP__");
1699 println("#define _" + intface.toUpperCase() + "_HPP__");
1700 println("#include <iostream>");
1701 // Pass in set of methods and get include classes
1702 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
1703 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
1704 List<String> methods = intDecl.getMethods();
1705 Set<String> includeClasses = getIncludeClasses(methods, intDecl, intface, true);
1706 printIncludeStatements(includeClasses); println("");
1707 println("using namespace std;\n");
1708 // Write enum if any...
1709 //EnumDecl enumDecl = (EnumDecl) decHandler.getEnumDecl(intface);
1710 //writeEnumCplus(enumDecl);
1711 // Write struct if any...
1712 //StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
1713 //writeStructCplus(structDecl);
1714 println("class " + intface); println("{");
1717 writeMethodCplusLocalInterface(methods, intDecl);
1721 System.out.println("IoTCompiler: Generated local interface " + intface + ".hpp...");
1727 * generateCPlusInterfaces() generate stub interfaces based on the methods list in C++
1729 * For C++ we use virtual classe as interface
1731 public void generateCPlusInterfaces() throws IOException {
1733 // Create a new directory
1734 String path = createDirectories(dir, subdir);
1735 for (String intface : mapIntfacePTH.keySet()) {
1737 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
1738 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
1740 // Open a new file to write into
1741 String newIntface = intMeth.getKey();
1742 FileWriter fw = new FileWriter(path + "/" + newIntface + ".hpp");
1743 pw = new PrintWriter(new BufferedWriter(fw));
1744 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
1745 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
1746 // Write file headers
1747 println("#ifndef _" + newIntface.toUpperCase() + "_HPP__");
1748 println("#define _" + newIntface.toUpperCase() + "_HPP__");
1749 println("#include <iostream>");
1750 // Pass in set of methods and get import classes
1751 Set<String> includeClasses = getIncludeClasses(intMeth.getValue(), intDecl, intface, false);
1752 List<String> stdIncludeClasses = getStandardCplusIncludeClasses();
1753 List<String> allIncludeClasses = getAllLibClasses(stdIncludeClasses, includeClasses);
1754 printIncludeStatements(allIncludeClasses); println("");
1755 println("using namespace std;\n");
1756 println("class " + newIntface);
1760 writeMethodCplusInterface(intMeth.getValue(), intDecl);
1764 System.out.println("IoTCompiler: Generated interface " + newIntface + ".hpp...");
1771 * HELPER: writeMethodCplusStub() writes the method of the stub
1773 private void writeMethodCplusStub(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
1775 for (String method : methods) {
1777 List<String> methParams = intDecl.getMethodParams(method);
1778 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1779 print(checkAndGetCplusType(intDecl.getMethodType(method)) + " " +
1780 intDecl.getMethodId(method) + "(");
1781 boolean isCallbackMethod = false;
1782 String callbackType = null;
1783 for (int i = 0; i < methParams.size(); i++) {
1785 String paramType = methPrmTypes.get(i);
1786 // Check if this has callback object
1787 if (callbackClasses.contains(paramType)) {
1788 isCallbackMethod = true;
1789 callbackType = paramType;
1790 // Even if there're 2 callback arguments, we expect them to be of the same interface
1792 String methPrmType = checkAndGetCplusType(methPrmTypes.get(i));
1793 String methParamComplete = checkAndGetCplusArray(methPrmType, methParams.get(i));
1794 print(methParamComplete);
1795 // Check if this is the last element (don't print a comma)
1796 if (i != methParams.size() - 1) {
1801 if (isCallbackMethod)
1802 writeCallbackMethodBodyCplusStub(intDecl, methParams, methPrmTypes, method, callbackType);
1804 writeStdMethodBodyCplusStub(intDecl, methParams, methPrmTypes, method);
1806 // Write the init callback helper method
1807 if (isCallbackMethod) {
1808 writeInitCallbackCplusStub(callbackType, intDecl);
1809 writeInitCallbackSendInfoCplusStub(intDecl);
1816 * HELPER: writeCallbackMethodBodyCplusStub() writes the callback method of the stub class
1818 private void writeCallbackMethodBodyCplusStub(InterfaceDecl intDecl, List<String> methParams,
1819 List<String> methPrmTypes, String method, String callbackType) {
1821 // Check if this is single object, array, or list of objects
1822 boolean isArrayOrList = false;
1823 String callbackParam = null;
1824 for (int i = 0; i < methParams.size(); i++) {
1826 String paramType = methPrmTypes.get(i);
1827 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
1828 String param = methParams.get(i);
1829 if (isArrayOrList(paramType, param)) { // Generate loop
1830 println("for (" + paramType + "* cb : " + getSimpleIdentifier(param) + ") {");
1831 println(callbackType + "_CallbackSkeleton* skel = new " + callbackType + "_CallbackSkeleton(cb, objIdCnt++);");
1832 isArrayOrList = true;
1833 callbackParam = getSimpleIdentifier(param);
1835 println(callbackType + "_CallbackSkeleton* skel = new " + callbackType + "_CallbackSkeleton(" +
1836 getSimpleIdentifier(param) + ", objIdCnt++);");
1837 println("vecCallbackObj.push_back(skel);");
1838 if (isArrayOrList(paramType, param))
1842 println("int numParam = " + methParams.size() + ";");
1843 println("int methodId = " + intDecl.getMethodNumId(method) + ";");
1844 String retType = intDecl.getMethodType(method);
1845 String retTypeC = checkAndGetCplusType(retType);
1846 println("string retType = \"" + checkAndGetCplusArrayType(retTypeC) + "\";");
1847 // Generate array of parameter types
1848 print("string paramCls[] = { ");
1849 for (int i = 0; i < methParams.size(); i++) {
1850 String paramType = methPrmTypes.get(i);
1851 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
1853 } else { // Generate normal classes if it's not a callback object
1854 String paramTypeC = checkAndGetCplusType(methPrmTypes.get(i));
1855 String prmType = checkAndGetCplusArrayType(paramTypeC, methParams.get(i));
1856 print("\"" + prmType + "\"");
1858 if (i != methParams.size() - 1) // Check if this is the last element
1862 print("int ___paramCB = ");
1864 println(callbackParam + ".size();");
1867 // Generate array of parameter objects
1868 print("void* paramObj[] = { ");
1869 for (int i = 0; i < methParams.size(); i++) {
1870 String paramType = methPrmTypes.get(i);
1871 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
1872 print("&___paramCB");
1874 print(getSimpleIdentifier(methParams.get(i)));
1875 if (i != methParams.size() - 1)
1879 // Check if this is "void"
1880 if (retType.equals("void")) {
1881 println("void* retObj = NULL;");
1882 println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
1883 } else { // We do have a return value
1884 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
1885 println(checkAndGetCplusType(retType) + " retVal;");
1887 println(checkAndGetCplusType(retType) + " retVal = " + generateCplusInitializer(retType) + ";");
1888 println("void* retObj = &retVal;");
1889 println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
1890 println("return retVal;");
1896 * HELPER: checkAndWriteEnumTypeCplusStub() writes the enum type (convert from enum to int)
1898 private void checkAndWriteEnumTypeCplusStub(List<String> methParams, List<String> methPrmTypes) {
1900 // Iterate and find enum declarations
1901 for (int i = 0; i < methParams.size(); i++) {
1902 String paramType = methPrmTypes.get(i);
1903 String param = methParams.get(i);
1904 String simpleType = getSimpleType(paramType);
1905 if (isEnumClass(simpleType)) {
1906 // Check if this is enum type
1907 if (isArrayOrList(paramType, param)) { // An array or vector
1908 println("int len" + i + " = " + param + ".size();");
1909 println("vector<int> paramEnum" + i + "(len);");
1910 println("for (int i = 0; i < len" + i + "; i++) {");
1911 println("paramEnum" + i + "[i] = (int) " + param + "[i];");
1913 } else { // Just one element
1914 println("vector<int> paramEnum" + i + "(1);");
1915 println("paramEnum" + i + "[0] = (int) " + param + ";");
1923 * HELPER: checkAndWriteEnumRetTypeCplusStub() writes the enum return type (convert from enum to int)
1925 private void checkAndWriteEnumRetTypeCplusStub(String retType) {
1927 // Strips off array "[]" for return type
1928 String pureType = getSimpleArrayType(getSimpleType(retType));
1929 // Take the inner type of generic
1930 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
1931 pureType = getTypeOfGeneric(retType)[0];
1932 if (isEnumClass(pureType)) {
1933 // Check if this is enum type
1934 println("vector<int> retEnumInt;");
1935 println("void* retObj = &retEnumInt;");
1936 println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
1937 if (isArrayOrList(retType, retType)) { // An array or vector
1938 println("int retLen = retEnumInt.size();");
1939 println("vector<" + pureType + "> retVal(retLen);");
1940 println("for (int i = 0; i < retLen; i++) {");
1941 println("retVal[i] = (" + pureType + ") retEnumInt[i];");
1943 } else { // Just one element
1944 println(pureType + " retVal = (" + pureType + ") retEnumInt[0];");
1946 println("return retVal;");
1952 * HELPER: writeStdMethodBodyCplusStub() writes the standard method body in the stub class
1954 private void writeStdMethodBodyCplusStub(InterfaceDecl intDecl, List<String> methParams,
1955 List<String> methPrmTypes, String method) {
1957 println("int numParam = " + methParams.size() + ";");
1958 println("int methodId = " + intDecl.getMethodNumId(method) + ";");
1959 String retType = intDecl.getMethodType(method);
1960 String retTypeC = checkAndGetCplusType(retType);
1961 println("string retType = \"" + checkAndGetCplusArrayType(getEnumType(retTypeC)) + "\";");
1962 // Generate array of parameter types
1963 print("string paramCls[] = { ");
1964 for (int i = 0; i < methParams.size(); i++) {
1965 String paramTypeC = checkAndGetCplusType(methPrmTypes.get(i));
1966 String paramType = checkAndGetCplusArrayType(paramTypeC, methParams.get(i));
1967 print("\"" + getEnumType(paramType) + "\"");
1968 // Check if this is the last element (don't print a comma)
1969 if (i != methParams.size() - 1) {
1974 checkAndWriteEnumTypeCplusStub(methParams, methPrmTypes);
1975 // Generate array of parameter objects
1976 print("void* paramObj[] = { ");
1977 for (int i = 0; i < methParams.size(); i++) {
1978 print("&" + getEnumParam(methPrmTypes.get(i), getSimpleIdentifier(methParams.get(i)), i));
1979 // Check if this is the last element (don't print a comma)
1980 if (i != methParams.size() - 1) {
1985 // Check if this is "void"
1986 if (retType.equals("void")) {
1987 println("void* retObj = NULL;");
1988 println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
1989 } else { // We do have a return value
1990 if (getParamCategory(retType) == ParamCategory.ENUM) {
1991 checkAndWriteEnumRetTypeCplusStub(retType);
1993 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
1994 println(checkAndGetCplusType(retType) + " retVal;");
1996 println(checkAndGetCplusType(retType) + " retVal = " + generateCplusInitializer(retType) + ";");
1997 println("void* retObj = &retVal;");
1998 println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
1999 println("return retVal;");
2006 * HELPER: writePropertiesCplusStub() writes the properties of the stub class
2008 private void writePropertiesCplusPermission(String intface) {
2010 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
2011 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
2012 String newIntface = intMeth.getKey();
2013 int newObjectId = mapNewIntfaceObjId.get(newIntface);
2014 println("const static int object" + newObjectId + "Id = " + newObjectId + ";");
2015 println("const static set<int> set" + newObjectId + "Allowed;");
2020 * HELPER: writePropertiesCplusStub() writes the properties of the stub class
2022 private void writePropertiesCplusStub(String intface, String newIntface, boolean callbackExist, Set<String> callbackClasses) {
2024 println("IoTRMICall *rmiCall;");
2025 //println("IoTRMIObject\t\t\t*rmiObj;");
2026 println("string address;");
2027 println("vector<int> ports;\n");
2028 // Get the object Id
2029 Integer objId = mapIntfaceObjId.get(intface);
2030 println("const static int objectId = " + objId + ";");
2031 mapNewIntfaceObjId.put(newIntface, objId);
2032 mapIntfaceObjId.put(intface, objId++);
2033 if (callbackExist) {
2034 // We assume that each class only has one callback interface for now
2035 Iterator it = callbackClasses.iterator();
2036 String callbackType = (String) it.next();
2037 println("// Callback properties");
2038 println("IoTRMIObject *rmiObj;");
2039 println("vector<" + callbackType + "*> vecCallbackObj;");
2040 println("static int objIdCnt;");
2041 // Generate permission stuff for callback stubs
2042 writePropertiesCplusPermission(callbackType);
2049 * HELPER: writeConstructorCplusStub() writes the constructor of the stub class
2051 private void writeConstructorCplusStub(String newStubClass, boolean callbackExist, Set<String> callbackClasses) {
2053 println(newStubClass +
2054 "(int _port, const char* _address, int _rev, bool* _bResult, vector<int> _ports) {");
2055 println("address = _address;");
2056 println("ports = _ports;");
2057 println("rmiCall = new IoTRMICall(_port, _address, _rev, _bResult);");
2058 if (callbackExist) {
2059 println("objIdCnt = 0;");
2060 Iterator it = callbackClasses.iterator();
2061 String callbackType = (String) it.next();
2062 println("thread th1 (&" + newStubClass + "::___initCallBack, this);");
2063 println("th1.detach();");
2064 println("___regCB();");
2071 * HELPER: writeDeconstructorCplusStub() writes the deconstructor of the stub class
2073 private void writeDeconstructorCplusStub(String newStubClass, boolean callbackExist, Set<String> callbackClasses) {
2075 println("~" + newStubClass + "() {");
2076 println("if (rmiCall != NULL) {");
2077 println("delete rmiCall;");
2078 println("rmiCall = NULL;");
2080 if (callbackExist) {
2081 // We assume that each class only has one callback interface for now
2082 println("if (rmiObj != NULL) {");
2083 println("delete rmiObj;");
2084 println("rmiObj = NULL;");
2086 Iterator it = callbackClasses.iterator();
2087 String callbackType = (String) it.next();
2088 println("for(" + callbackType + "* cb : vecCallbackObj) {");
2089 println("delete cb;");
2090 println("cb = NULL;");
2099 * HELPER: writeCplusMethodCallbackPermission() writes permission checks in stub for callbacks
2101 private void writeCplusMethodCallbackPermission(String intface) {
2103 println("int methodId = IoTRMIObject::getMethodId(method);");
2104 // Get all the different stubs
2105 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
2106 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
2107 String newIntface = intMeth.getKey();
2108 int newObjectId = mapNewIntfaceObjId.get(newIntface);
2109 println("if (set" + newObjectId + "Allowed.find(methodId) == set" + newObjectId + "Allowed.end()) {");
2110 println("cerr << \"Callback object for " + intface + " is not allowed to access method: \" << methodId;");
2111 println("exit(-1);");
2118 * HELPER: writeInitCallbackCplusStub() writes the initialization of callback
2120 private void writeInitCallbackCplusStub(String intface, InterfaceDecl intDecl) {
2122 println("void ___initCallBack() {");
2123 println("bool bResult = false;");
2124 println("rmiObj = new IoTRMIObject(ports[0], &bResult);");
2125 println("while (true) {");
2126 println("char* method = rmiObj->getMethodBytes();");
2127 writeCplusMethodCallbackPermission(intface);
2128 println("int objId = IoTRMIObject::getObjectId(method);");
2129 println("if (objId < vecCallbackObj.size()) { // Check if still within range");
2130 println(intface + "_CallbackSkeleton* skel = dynamic_cast<" + intface +
2131 "_CallbackSkeleton*> (vecCallbackObj.at(objId));");
2132 println("skel->invokeMethod(rmiObj);");
2133 println("} else {");
2134 println("cerr << \"Illegal object Id: \" << to_string(objId);");
2135 // TODO: perhaps need to change this into "throw" to make it cleaner (allow stack unfolding)
2136 println("exit(-1);");
2144 * HELPER: writeInitCallbackSendInfoCplusStub() writes the initialization of callback
2146 private void writeInitCallbackSendInfoCplusStub(InterfaceDecl intDecl) {
2148 // Generate info sending part
2149 println("void ___regCB() {");
2150 println("int numParam = 3;");
2151 String method = "___initCallBack()";
2152 println("int methodId = " + intDecl.getHelperMethodNumId(method) + ";");
2153 println("string retType = \"void\";");
2154 println("string paramCls[] = { \"int\", \"string\", \"int\" };");
2155 println("int rev = 0;");
2156 println("void* paramObj[] = { &ports[0], &address, &rev };");
2157 println("void* retObj = NULL;");
2158 println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
2164 * generateCPlusStubClasses() generate stubs based on the methods list in C++
2166 public void generateCPlusStubClasses() throws IOException {
2168 // Create a new directory
2169 String path = createDirectories(dir, subdir);
2170 for (String intface : mapIntfacePTH.keySet()) {
2172 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
2173 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
2174 // Open a new file to write into
2175 String newIntface = intMeth.getKey();
2176 String newStubClass = newIntface + "_Stub";
2177 FileWriter fw = new FileWriter(path + "/" + newStubClass + ".hpp");
2178 pw = new PrintWriter(new BufferedWriter(fw));
2179 // Write file headers
2180 println("#ifndef _" + newStubClass.toUpperCase() + "_HPP__");
2181 println("#define _" + newStubClass.toUpperCase() + "_HPP__");
2182 println("#include <iostream>");
2183 // Find out if there are callback objects
2184 Set<String> methods = intMeth.getValue();
2185 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2186 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
2187 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
2188 boolean callbackExist = !callbackClasses.isEmpty();
2189 if (callbackExist) // Need thread library if this has callback
2190 println("#include <thread>");
2191 println("#include \"" + newIntface + ".hpp\""); println("");
2192 println("using namespace std;"); println("");
2193 println("class " + newStubClass + " : public " + newIntface); println("{");
2194 println("private:\n");
2195 writePropertiesCplusStub(intface, newIntface, callbackExist, callbackClasses);
2196 println("public:\n");
2197 // Add default constructor and destructor
2198 println(newStubClass + "() { }"); println("");
2199 writeConstructorCplusStub(newStubClass, callbackExist, callbackClasses);
2200 writeDeconstructorCplusStub(newStubClass, callbackExist, callbackClasses);
2202 writeMethodCplusStub(methods, intDecl, callbackClasses);
2203 print("}"); println(";");
2205 writePermissionInitializationCplus(intface, newStubClass, intDecl);
2208 System.out.println("IoTCompiler: Generated stub class " + newStubClass + ".hpp...");
2215 * HELPER: writePropertiesCplusCallbackStub() writes the properties of the stub class
2217 private void writePropertiesCplusCallbackStub(String intface, String newIntface, boolean callbackExist, Set<String> callbackClasses) {
2219 println("IoTRMICall *rmiCall;");
2220 // Get the object Id
2221 println("static int objectId;");
2222 if (callbackExist) {
2223 // We assume that each class only has one callback interface for now
2224 Iterator it = callbackClasses.iterator();
2225 String callbackType = (String) it.next();
2226 println("// Callback properties");
2227 println("IoTRMIObject *rmiObj;");
2228 println("vector<" + callbackType + "*> vecCallbackObj;");
2229 println("static int objIdCnt;");
2230 // TODO: Need to initialize address and ports if we want to have callback-in-callback
2231 println("string address;");
2232 println("vector<int> ports;\n");
2233 writePropertiesCplusPermission(callbackType);
2240 * HELPER: writeConstructorCplusCallbackStub() writes the constructor of the stub class
2242 private void writeConstructorCplusCallbackStub(String newStubClass, boolean callbackExist, Set<String> callbackClasses) {
2244 println(newStubClass + "(IoTRMICall* _rmiCall, int _objectId) {");
2245 println("objectId = _objectId;");
2246 println("rmiCall = _rmiCall;");
2247 if (callbackExist) {
2248 Iterator it = callbackClasses.iterator();
2249 String callbackType = (String) it.next();
2250 println("thread th1 (&" + newStubClass + "::___initCallBack, this);");
2251 println("th1.detach();");
2252 println("___regCB();");
2259 * generateCPlusCallbackStubClasses() generate callback stubs based on the methods list in C++
2261 public void generateCPlusCallbackStubClasses() throws IOException {
2263 // Create a new directory
2264 String path = createDirectories(dir, subdir);
2265 for (String intface : mapIntfacePTH.keySet()) {
2267 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
2268 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
2269 // Open a new file to write into
2270 String newIntface = intMeth.getKey();
2271 String newStubClass = newIntface + "_CallbackStub";
2272 FileWriter fw = new FileWriter(path + "/" + newStubClass + ".hpp");
2273 pw = new PrintWriter(new BufferedWriter(fw));
2274 // Find out if there are callback objects
2275 Set<String> methods = intMeth.getValue();
2276 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2277 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
2278 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
2279 boolean callbackExist = !callbackClasses.isEmpty();
2280 // Write file headers
2281 println("#ifndef _" + newStubClass.toUpperCase() + "_HPP__");
2282 println("#define _" + newStubClass.toUpperCase() + "_HPP__");
2283 println("#include <iostream>");
2285 println("#include <thread>");
2286 println("#include \"" + newIntface + ".hpp\""); println("");
2287 println("using namespace std;"); println("");
2288 println("class " + newStubClass + " : public " + newIntface); println("{");
2289 println("private:\n");
2290 writePropertiesCplusCallbackStub(intface, newIntface, callbackExist, callbackClasses);
2291 println("public:\n");
2292 // Add default constructor and destructor
2293 println(newStubClass + "() { }"); println("");
2294 writeConstructorCplusCallbackStub(newStubClass, callbackExist, callbackClasses);
2295 writeDeconstructorCplusStub(newStubClass, callbackExist, callbackClasses);
2297 writeMethodCplusStub(methods, intDecl, callbackClasses);
2300 writePermissionInitializationCplus(intface, newStubClass, intDecl);
2303 System.out.println("IoTCompiler: Generated callback stub class " + newIntface + ".hpp...");
2310 * HELPER: writePropertiesCplusSkeleton() writes the properties of the skeleton class
2312 private void writePropertiesCplusSkeleton(String intface, boolean callbackExist, Set<String> callbackClasses) {
2314 println(intface + " *mainObj;");
2316 if (callbackExist) {
2317 Iterator it = callbackClasses.iterator();
2318 String callbackType = (String) it.next();
2319 String exchangeType = checkAndGetParamClass(callbackType);
2320 println("// Callback properties");
2321 println("static int objIdCnt;");
2322 println("vector<" + exchangeType + "*> vecCallbackObj;");
2323 println("IoTRMICall *rmiCall;");
2325 println("IoTRMIObject *rmiObj;\n");
2326 // Keep track of object Ids of all stubs registered to this interface
2327 writePropertiesCplusPermission(intface);
2333 * HELPER: writePermissionInitializationCplus() writes the initialization of permission set
2335 private void writePermissionInitializationCplus(String intface, String newSkelClass, InterfaceDecl intDecl) {
2337 // Keep track of object Ids of all stubs registered to this interface
2338 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
2339 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
2340 String newIntface = intMeth.getKey();
2341 int newObjectId = mapNewIntfaceObjId.get(newIntface);
2342 print("const set<int> " + newSkelClass + "::set" + newObjectId + "Allowed {");
2343 Set<String> methodIds = intMeth.getValue();
2345 for (String methodId : methodIds) {
2346 int methodNumId = intDecl.getMethodNumId(methodId);
2347 print(Integer.toString(methodNumId));
2348 // Check if this is the last element (don't print a comma)
2349 if (i != methodIds.size() - 1) {
2360 * HELPER: writeConstructorCplusSkeleton() writes the constructor of the skeleton class
2362 private void writeConstructorCplusSkeleton(String newSkelClass, String intface, boolean callbackExist) {
2364 println(newSkelClass + "(" + intface + " *_mainObj, int _port) {");
2365 println("bool _bResult = false;");
2366 println("mainObj = _mainObj;");
2367 println("rmiObj = new IoTRMIObject(_port, &_bResult);");
2369 if (callbackExist) {
2370 println("objIdCnt = 0;");
2372 //println("set0Allowed = Arrays.asList(object0Permission);");
2373 println("___waitRequestInvokeMethod();");
2379 * HELPER: writeDeconstructorCplusSkeleton() writes the deconstructor of the skeleton class
2381 private void writeDeconstructorCplusSkeleton(String newSkelClass, boolean callbackExist, Set<String> callbackClasses) {
2383 println("~" + newSkelClass + "() {");
2384 println("if (rmiObj != NULL) {");
2385 println("delete rmiObj;");
2386 println("rmiObj = NULL;");
2388 if (callbackExist) {
2389 // We assume that each class only has one callback interface for now
2390 println("if (rmiCall != NULL) {");
2391 println("delete rmiCall;");
2392 println("rmiCall = NULL;");
2394 Iterator it = callbackClasses.iterator();
2395 String callbackType = (String) it.next();
2396 String exchangeType = checkAndGetParamClass(callbackType);
2397 println("for(" + exchangeType + "* cb : vecCallbackObj) {");
2398 println("delete cb;");
2399 println("cb = NULL;");
2408 * HELPER: writeStdMethodBodyCplusSkeleton() writes the standard method body in the skeleton class
2410 private void writeStdMethodBodyCplusSkeleton(List<String> methParams, String methodId, String methodType) {
2412 if (methodType.equals("void"))
2413 print("mainObj->" + methodId + "(");
2415 print("return mainObj->" + methodId + "(");
2416 for (int i = 0; i < methParams.size(); i++) {
2418 print(getSimpleIdentifier(methParams.get(i)));
2419 // Check if this is the last element (don't print a comma)
2420 if (i != methParams.size() - 1) {
2429 * HELPER: writeInitCallbackCplusSkeleton() writes the init callback method for skeleton class
2431 private void writeInitCallbackCplusSkeleton(boolean callbackSkeleton) {
2433 // This is a callback skeleton generation
2434 if (callbackSkeleton)
2435 println("void ___regCB(IoTRMIObject* rmiObj) {");
2437 println("void ___regCB() {");
2438 println("int numParam = 3;");
2439 println("int param1 = 0;");
2440 println("string param2 = \"\";");
2441 println("int param3 = 0;");
2442 println("void* paramObj[] = { ¶m1, ¶m2, ¶m3 };");
2443 println("bool bResult = false;");
2444 println("rmiCall = new IoTRMICall(param1, param2.c_str(), param3, &bResult);");
2450 * HELPER: writeMethodCplusSkeleton() writes the method of the skeleton class
2452 private void writeMethodCplusSkeleton(Collection<String> methods, InterfaceDecl intDecl,
2453 Set<String> callbackClasses, boolean callbackSkeleton) {
2455 for (String method : methods) {
2457 List<String> methParams = intDecl.getMethodParams(method);
2458 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2459 String methodId = intDecl.getMethodId(method);
2460 String methodType = checkAndGetCplusType(intDecl.getMethodType(method));
2461 print(methodType + " " + methodId + "(");
2462 boolean isCallbackMethod = false;
2463 String callbackType = null;
2464 for (int i = 0; i < methParams.size(); i++) {
2466 String origParamType = methPrmTypes.get(i);
2467 if (callbackClasses.contains(origParamType)) { // Check if this has callback object
2468 isCallbackMethod = true;
2469 callbackType = origParamType;
2471 String paramType = checkAndGetParamClass(methPrmTypes.get(i));
2472 String methPrmType = checkAndGetCplusType(paramType);
2473 String methParamComplete = checkAndGetCplusArray(methPrmType, methParams.get(i));
2474 print(methParamComplete);
2475 // Check if this is the last element (don't print a comma)
2476 if (i != methParams.size() - 1) {
2481 // Now, write the body of skeleton!
2482 writeStdMethodBodyCplusSkeleton(methParams, methodId, intDecl.getMethodType(method));
2484 if (isCallbackMethod)
2485 writeInitCallbackCplusSkeleton(callbackSkeleton);
2491 * HELPER: writeCallbackCplusNumStubs() writes the numStubs variable
2493 private void writeCallbackCplusNumStubs(List<String> methParams, List<String> methPrmTypes, String callbackType) {
2495 for (int i = 0; i < methParams.size(); i++) {
2496 String paramType = methPrmTypes.get(i);
2497 String param = methParams.get(i);
2498 //if (callbackType.equals(paramType)) {
2499 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
2500 String exchParamType = checkAndGetParamClass(paramType);
2501 // Print array if this is array or list if this is a list of callback objects
2502 println("int numStubs" + i + " = 0;");
2509 * HELPER: writeCallbackCplusStubGeneration() writes the callback stub generation part
2511 private void writeCallbackCplusStubGeneration(List<String> methParams, List<String> methPrmTypes, String callbackType) {
2513 // Iterate over callback objects
2514 for (int i = 0; i < methParams.size(); i++) {
2515 String paramType = methPrmTypes.get(i);
2516 String param = methParams.get(i);
2517 // Generate a loop if needed
2518 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
2519 String exchParamType = checkAndGetParamClass(paramType);
2520 if (isArrayOrList(paramType, param)) {
2521 println("vector<" + exchParamType + "> stub;");
2522 println("for (int objId = 0; objId < numStubs" + i + "; objId++) {");
2523 println(exchParamType + "* cb" + i + " = new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt);");
2524 println("stub" + i + ".push_back(cb);");
2525 println("vecCallbackObj.push_back(cb);");
2526 println("objIdCnt++;");
2529 println(exchParamType + "* stub" + i + " = new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt);");
2530 println("vecCallbackObj.push_back(stub" + i + ");");
2531 println("objIdCnt++;");
2539 * HELPER: checkAndWriteEnumTypeCplusSkeleton() writes the enum type (convert from enum to int)
2541 private void checkAndWriteEnumTypeCplusSkeleton(List<String> methParams, List<String> methPrmTypes) {
2543 // Iterate and find enum declarations
2544 for (int i = 0; i < methParams.size(); i++) {
2545 String paramType = methPrmTypes.get(i);
2546 String param = methParams.get(i);
2547 String simpleType = getSimpleType(paramType);
2548 if (isEnumClass(simpleType)) {
2549 // Check if this is enum type
2550 if (isArrayOrList(paramType, param)) { // An array
2551 println("int len" + i + " = paramEnumInt" + i + ".size();");
2552 println("vector<" + simpleType + "> paramEnum" + i + "(len" + i + ");");
2553 println("for (int i=0; i < len" + i + "; i++) {");
2554 println("paramEnum" + i + "[i] = (" + simpleType + ") paramEnumInt" + i + "[i];");
2556 } else { // Just one element
2557 println(simpleType + " paramEnum" + i + ";");
2558 println("paramEnum" + i + " = (" + simpleType + ") paramEnumInt" + i + "[0];");
2566 * HELPER: checkAndWriteEnumRetTypeCplusSkeleton() writes the enum return type (convert from enum to int)
2568 private void checkAndWriteEnumRetTypeCplusSkeleton(String retType) {
2570 // Strips off array "[]" for return type
2571 String pureType = getSimpleArrayType(getSimpleType(retType));
2572 // Take the inner type of generic
2573 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
2574 pureType = getTypeOfGeneric(retType)[0];
2575 if (isEnumClass(pureType)) {
2576 // Check if this is enum type
2578 if (isArrayOrList(retType, retType)) { // An array
2579 println("int retLen = retEnum.size();");
2580 println("vector<int> retEnumInt(retLen);");
2581 println("for (int i=0; i < retLen; i++) {");
2582 println("retEnumInt[i] = (int) retEnum[i];");
2584 } else { // Just one element
2585 println("vector<int> retEnumInt(1);");
2586 println("retEnumInt[0] = (int) retEnum;");
2593 * HELPER: writeStdMethodHelperBodyCplusSkeleton() writes the standard method body helper in the skeleton class
2595 private void writeStdMethodHelperBodyCplusSkeleton(InterfaceDecl intDecl, List<String> methParams,
2596 List<String> methPrmTypes, String method, String methodId, Set<String> callbackClasses) {
2598 // Generate array of parameter types
2599 boolean isCallbackMethod = false;
2600 String callbackType = null;
2601 print("string paramCls[] = { ");
2602 for (int i = 0; i < methParams.size(); i++) {
2603 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
2604 if (callbackClasses.contains(paramType)) {
2605 isCallbackMethod = true;
2606 callbackType = paramType;
2608 } else { // Generate normal classes if it's not a callback object
2609 String paramTypeC = checkAndGetCplusType(methPrmTypes.get(i));
2610 String prmType = checkAndGetCplusArrayType(paramTypeC, methParams.get(i));
2611 print("\"" + getEnumType(prmType) + "\"");
2613 if (i != methParams.size() - 1) {
2618 println("int numParam = " + methParams.size() + ";");
2619 if (isCallbackMethod)
2620 writeCallbackCplusNumStubs(methParams, methPrmTypes, callbackType);
2621 // Generate parameters
2622 for (int i = 0; i < methParams.size(); i++) {
2623 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
2624 if (!callbackClasses.contains(paramType)) {
2625 String methPrmType = checkAndGetCplusType(methPrmTypes.get(i));
2626 if (isEnumClass(getSimpleType(methPrmType))) { // Check if this is enum type
2627 println("vector<int> paramEnumInt" + i + ";");
2629 String methParamComplete = checkAndGetCplusArray(methPrmType, methParams.get(i));
2630 println(methParamComplete + ";");
2634 // Generate array of parameter objects
2635 print("void* paramObj[] = { ");
2636 for (int i = 0; i < methParams.size(); i++) {
2637 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
2638 if (callbackClasses.contains(paramType))
2639 print("&numStubs" + i);
2640 else if (isEnumClass(getSimpleType(paramType))) // Check if this is enum type
2641 print("¶mEnumInt" + i);
2643 print("&" + getSimpleIdentifier(methParams.get(i)));
2644 if (i != methParams.size() - 1) {
2649 println("rmiObj->getMethodParams(paramCls, numParam, paramObj);");
2650 if (isCallbackMethod)
2651 writeCallbackCplusStubGeneration(methParams, methPrmTypes, callbackType);
2652 checkAndWriteEnumTypeCplusSkeleton(methParams, methPrmTypes);
2653 String retType = intDecl.getMethodType(method);
2654 // Check if this is "void"
2655 if (retType.equals("void")) {
2656 print(methodId + "(");
2657 for (int i = 0; i < methParams.size(); i++) {
2658 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
2659 if (callbackClasses.contains(paramType))
2661 else if (isEnumClass(getSimpleType(paramType))) // Check if this is enum type
2662 print("paramEnum" + i);
2664 print(getSimpleIdentifier(methParams.get(i)));
2665 if (i != methParams.size() - 1) {
2670 } else { // We do have a return value
2671 if (isEnumClass(getSimpleArrayType(getSimpleType(retType)))) // Enum type
2672 print(checkAndGetCplusType(retType) + " retEnum = ");
2674 print(checkAndGetCplusType(retType) + " retVal = ");
2675 print(methodId + "(");
2676 for (int i = 0; i < methParams.size(); i++) {
2677 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
2678 if (callbackClasses.contains(paramType))
2680 else if (isEnumClass(getSimpleType(paramType))) // Check if this is enum type
2681 print("paramEnum" + i);
2683 print(getSimpleIdentifier(methParams.get(i)));
2684 if (i != methParams.size() - 1) {
2689 checkAndWriteEnumRetTypeCplusSkeleton(retType);
2690 if (isEnumClass(getSimpleArrayType(getSimpleType(retType)))) // Enum type
2691 println("void* retObj = &retEnumInt;");
2693 println("void* retObj = &retVal;");
2694 String retTypeC = checkAndGetCplusType(retType);
2695 println("rmiObj->sendReturnObj(retObj, \"" + getEnumType(checkAndGetCplusArrayType(retTypeC)) + "\");");
2701 * HELPER: writeMethodHelperCplusSkeleton() writes the method helper of the skeleton class
2703 private void writeMethodHelperCplusSkeleton(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
2705 // Use this set to handle two same methodIds
2706 Set<String> uniqueMethodIds = new HashSet<String>();
2707 for (String method : methods) {
2709 List<String> methParams = intDecl.getMethodParams(method);
2710 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2711 String methodId = intDecl.getMethodId(method);
2713 String helperMethod = methodId;
2714 if (uniqueMethodIds.contains(methodId))
2715 helperMethod = helperMethod + intDecl.getMethodNumId(method);
2717 uniqueMethodIds.add(methodId);
2718 // Check if this is "void"
2719 String retType = intDecl.getMethodType(method);
2720 println(helperMethod + "() {");
2721 // Now, write the helper body of skeleton!
2722 writeStdMethodHelperBodyCplusSkeleton(intDecl, methParams, methPrmTypes, method, methodId, callbackClasses);
2729 * HELPER: writeCplusMethodPermission() writes permission checks in skeleton
2731 private void writeCplusMethodPermission(String intface) {
2733 // Get all the different stubs
2734 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
2735 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
2736 String newIntface = intMeth.getKey();
2737 int newObjectId = mapNewIntfaceObjId.get(newIntface);
2738 println("if (_objectId == object" + newObjectId + "Id) {");
2739 println("if (set" + newObjectId + "Allowed.find(methodId) == set" + newObjectId + "Allowed.end()) {");
2740 println("cerr << \"Object with object Id: \" << _objectId << \" is not allowed to access method: \" << methodId << endl;");
2741 println("exit(-1);");
2744 println("cerr << \"Object Id: \" << _objectId << \" not recognized!\" << endl;");
2745 println("exit(-1);");
2753 * HELPER: writeCplusWaitRequestInvokeMethod() writes the main loop of the skeleton class
2755 private void writeCplusWaitRequestInvokeMethod(Collection<String> methods, InterfaceDecl intDecl, boolean callbackExist, String intface) {
2757 // Use this set to handle two same methodIds
2758 Set<String> uniqueMethodIds = new HashSet<String>();
2759 println("void ___waitRequestInvokeMethod() {");
2760 // Write variables here if we have callbacks or enums or structs
2761 println("while (true) {");
2762 println("rmiObj->getMethodBytes();");
2763 println("int _objectId = rmiObj->getObjectId();");
2764 println("int methodId = rmiObj->getMethodId();");
2765 // Generate permission check
2766 writeCplusMethodPermission(intface);
2767 println("switch (methodId) {");
2768 // Print methods and method Ids
2769 for (String method : methods) {
2770 String methodId = intDecl.getMethodId(method);
2771 int methodNumId = intDecl.getMethodNumId(method);
2772 print("case " + methodNumId + ": ___");
2773 String helperMethod = methodId;
2774 if (uniqueMethodIds.contains(methodId))
2775 helperMethod = helperMethod + methodNumId;
2777 uniqueMethodIds.add(methodId);
2778 println(helperMethod + "(); break;");
2780 String method = "___initCallBack()";
2781 // Print case -9999 (callback handler) if callback exists
2782 if (callbackExist) {
2783 int methodId = intDecl.getHelperMethodNumId(method);
2784 println("case " + methodId + ": ___regCB(); break;");
2786 println("default: ");
2787 println("cerr << \"Method Id \" << methodId << \" not recognized!\" << endl;");
2788 println("throw exception();");
2796 * generateCplusSkeletonClass() generate skeletons based on the methods list in C++
2798 public void generateCplusSkeletonClass() throws IOException {
2800 // Create a new directory
2801 String path = createDirectories(dir, subdir);
2802 for (String intface : mapIntfacePTH.keySet()) {
2803 // Open a new file to write into
2804 String newSkelClass = intface + "_Skeleton";
2805 FileWriter fw = new FileWriter(path + "/" + newSkelClass + ".hpp");
2806 pw = new PrintWriter(new BufferedWriter(fw));
2807 // Write file headers
2808 println("#ifndef _" + newSkelClass.toUpperCase() + "_HPP__");
2809 println("#define _" + newSkelClass.toUpperCase() + "_HPP__");
2810 println("#include <iostream>");
2811 println("#include \"" + intface + ".hpp\"\n");
2812 // Pass in set of methods and get import classes
2813 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2814 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
2815 List<String> methods = intDecl.getMethods();
2816 Set<String> includeClasses = getIncludeClasses(methods, intDecl, intface, true);
2817 List<String> stdIncludeClasses = getStandardCplusIncludeClasses();
2818 List<String> allIncludeClasses = getAllLibClasses(stdIncludeClasses, includeClasses);
2819 printIncludeStatements(allIncludeClasses); println("");
2820 println("using namespace std;\n");
2821 // Find out if there are callback objects
2822 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
2823 boolean callbackExist = !callbackClasses.isEmpty();
2824 // Write class header
2825 println("class " + newSkelClass + " : public " + intface); println("{");
2826 println("private:\n");
2828 writePropertiesCplusSkeleton(intface, callbackExist, callbackClasses);
2829 println("public:\n");
2830 // Write constructor
2831 writeConstructorCplusSkeleton(newSkelClass, intface, callbackExist);
2832 // Write deconstructor
2833 writeDeconstructorCplusSkeleton(newSkelClass, callbackExist, callbackClasses);
2835 writeMethodCplusSkeleton(methods, intDecl, callbackClasses, false);
2836 // Write method helper
2837 writeMethodHelperCplusSkeleton(methods, intDecl, callbackClasses);
2838 // Write waitRequestInvokeMethod() - main loop
2839 writeCplusWaitRequestInvokeMethod(methods, intDecl, callbackExist, intface);
2841 writePermissionInitializationCplus(intface, newSkelClass, intDecl);
2844 System.out.println("IoTCompiler: Generated skeleton class " + newSkelClass + ".hpp...");
2850 * HELPER: writePropertiesCplusCallbackSkeleton() writes the properties of the callback skeleton class
2852 private void writePropertiesCplusCallbackSkeleton(String intface, boolean callbackExist, Set<String> callbackClasses) {
2854 println(intface + " *mainObj;");
2855 // Keep track of object Ids of all stubs registered to this interface
2856 println("static int objectId;");
2858 if (callbackExist) {
2859 Iterator it = callbackClasses.iterator();
2860 String callbackType = (String) it.next();
2861 String exchangeType = checkAndGetParamClass(callbackType);
2862 println("// Callback properties");
2863 println("IoTRMICall* rmiCall;");
2864 println("vector<" + exchangeType + "*> vecCallbackObj;");
2865 println("static int objIdCnt;");
2872 * HELPER: writeConstructorCplusCallbackSkeleton() writes the constructor of the skeleton class
2874 private void writeConstructorCplusCallbackSkeleton(String newSkelClass, String intface, boolean callbackExist) {
2876 println(newSkelClass + "(" + intface + " *_mainObj, int _objectId) {");
2877 println("mainObj = _mainObj;");
2878 println("objectId = _objectId;");
2880 if (callbackExist) {
2881 println("objIdCnt = 0;");
2888 * HELPER: writeDeconstructorCplusStub() writes the deconstructor of the stub class
2890 private void writeDeconstructorCplusCallbackSkeleton(String newStubClass, boolean callbackExist,
2891 Set<String> callbackClasses) {
2893 println("~" + newStubClass + "() {");
2894 if (callbackExist) {
2895 // We assume that each class only has one callback interface for now
2896 println("if (rmiCall != NULL) {");
2897 println("delete rmiCall;");
2898 println("rmiCall = NULL;");
2900 Iterator it = callbackClasses.iterator();
2901 String callbackType = (String) it.next();
2902 String exchangeType = checkAndGetParamClass(callbackType);
2903 println("for(" + exchangeType + "* cb : vecCallbackObj) {");
2904 println("delete cb;");
2905 println("cb = NULL;");
2914 * HELPER: writeMethodHelperCplusCallbackSkeleton() writes the method helper of the callback skeleton class
2916 private void writeMethodHelperCplusCallbackSkeleton(Collection<String> methods, InterfaceDecl intDecl,
2917 Set<String> callbackClasses) {
2919 // Use this set to handle two same methodIds
2920 Set<String> uniqueMethodIds = new HashSet<String>();
2921 for (String method : methods) {
2923 List<String> methParams = intDecl.getMethodParams(method);
2924 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2925 String methodId = intDecl.getMethodId(method);
2927 String helperMethod = methodId;
2928 if (uniqueMethodIds.contains(methodId))
2929 helperMethod = helperMethod + intDecl.getMethodNumId(method);
2931 uniqueMethodIds.add(methodId);
2932 // Check if this is "void"
2933 String retType = intDecl.getMethodType(method);
2934 println(helperMethod + "(IoTRMIObject* rmiObj) {");
2935 // Now, write the helper body of skeleton!
2936 writeStdMethodHelperBodyCplusSkeleton(intDecl, methParams, methPrmTypes, method, methodId, callbackClasses);
2943 * HELPER: writeCplusCallbackWaitRequestInvokeMethod() writes the main loop of the skeleton class
2945 private void writeCplusCallbackWaitRequestInvokeMethod(Collection<String> methods, InterfaceDecl intDecl,
2946 boolean callbackExist) {
2948 // Use this set to handle two same methodIds
2949 Set<String> uniqueMethodIds = new HashSet<String>();
2950 println("void invokeMethod(IoTRMIObject* rmiObj) {");
2951 // Write variables here if we have callbacks or enums or structs
2952 println("int methodId = rmiObj->getMethodId();");
2953 // TODO: code the permission check here!
2954 println("switch (methodId) {");
2955 // Print methods and method Ids
2956 for (String method : methods) {
2957 String methodId = intDecl.getMethodId(method);
2958 int methodNumId = intDecl.getMethodNumId(method);
2959 print("case " + methodNumId + ": ___");
2960 String helperMethod = methodId;
2961 if (uniqueMethodIds.contains(methodId))
2962 helperMethod = helperMethod + methodNumId;
2964 uniqueMethodIds.add(methodId);
2965 println(helperMethod + "(rmiObj); break;");
2967 String method = "___initCallBack()";
2968 // Print case -9999 (callback handler) if callback exists
2969 if (callbackExist) {
2970 int methodId = intDecl.getHelperMethodNumId(method);
2971 println("case " + methodId + ": ___regCB(rmiObj); break;");
2973 println("default: ");
2974 println("cerr << \"Method Id \" << methodId << \" not recognized!\" << endl;");
2975 println("throw exception();");
2983 * generateCplusCallbackSkeletonClass() generate callback skeletons based on the methods list in C++
2985 public void generateCplusCallbackSkeletonClass() throws IOException {
2987 // Create a new directory
2988 String path = createDirectories(dir, subdir);
2989 for (String intface : mapIntfacePTH.keySet()) {
2990 // Open a new file to write into
2991 String newSkelClass = intface + "_CallbackSkeleton";
2992 FileWriter fw = new FileWriter(path + "/" + newSkelClass + ".hpp");
2993 pw = new PrintWriter(new BufferedWriter(fw));
2994 // Write file headers
2995 println("#ifndef _" + newSkelClass.toUpperCase() + "_HPP__");
2996 println("#define _" + newSkelClass.toUpperCase() + "_HPP__");
2997 println("#include <iostream>");
2998 println("#include \"" + intface + ".hpp\"\n");
2999 // Pass in set of methods and get import classes
3000 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
3001 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
3002 List<String> methods = intDecl.getMethods();
3003 Set<String> includeClasses = getIncludeClasses(methods, intDecl, intface, true);
3004 List<String> stdIncludeClasses = getStandardCplusIncludeClasses();
3005 List<String> allIncludeClasses = getAllLibClasses(stdIncludeClasses, includeClasses);
3006 printIncludeStatements(allIncludeClasses); println("");
3007 // Find out if there are callback objects
3008 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
3009 boolean callbackExist = !callbackClasses.isEmpty();
3010 println("using namespace std;\n");
3011 // Write class header
3012 println("class " + newSkelClass + " : public " + intface); println("{");
3013 println("private:\n");
3015 writePropertiesCplusCallbackSkeleton(intface, callbackExist, callbackClasses);
3016 println("public:\n");
3017 // Write constructor
3018 writeConstructorCplusCallbackSkeleton(newSkelClass, intface, callbackExist);
3019 // Write deconstructor
3020 writeDeconstructorCplusCallbackSkeleton(newSkelClass, callbackExist, callbackClasses);
3022 writeMethodCplusSkeleton(methods, intDecl, callbackClasses, true);
3023 // Write method helper
3024 writeMethodHelperCplusCallbackSkeleton(methods, intDecl, callbackClasses);
3025 // Write waitRequestInvokeMethod() - main loop
3026 writeCplusCallbackWaitRequestInvokeMethod(methods, intDecl, callbackExist);
3030 System.out.println("IoTCompiler: Generated callback skeleton class " + newSkelClass + ".hpp...");
3036 * generateInitializer() generate initializer based on type
3038 public String generateCplusInitializer(String type) {
3040 // Generate dummy returns for now
3041 if (type.equals("short")||
3042 type.equals("int") ||
3043 type.equals("long") ||
3044 type.equals("float")||
3045 type.equals("double")) {
3048 } else if ( type.equals("String") ||
3049 type.equals("string")) {
3052 } else if ( type.equals("char") ||
3053 type.equals("byte")) {
3056 } else if ( type.equals("boolean")) {
3066 * generateReturnStmt() generate return statement based on methType
3068 public String generateReturnStmt(String methType) {
3070 // Generate dummy returns for now
3071 if (methType.equals("short")||
3072 methType.equals("int") ||
3073 methType.equals("long") ||
3074 methType.equals("float")||
3075 methType.equals("double")) {
3078 } else if ( methType.equals("String")) {
3081 } else if ( methType.equals("char") ||
3082 methType.equals("byte")) {
3085 } else if ( methType.equals("boolean")) {
3095 * setDirectory() sets a new directory for stub files
3097 public void setDirectory(String _subdir) {
3104 * printUsage() prints the usage of this compiler
3106 public static void printUsage() {
3108 System.out.println();
3109 System.out.println("Sentinel interface and stub compiler version 1.0");
3110 System.out.println("Copyright (c) 2015-2016 University of California, Irvine - Programming Language Group.");
3111 System.out.println("All rights reserved.");
3112 System.out.println("Usage:");
3113 System.out.println("\tjava IoTCompiler -help / --help / -h\n");
3114 System.out.println("\t\tDisplay this help texts\n\n");
3115 System.out.println("\tjava IoTCompiler [<main-policy-file> <req-policy-file>]");
3116 System.out.println("\tjava IoTCompiler [<main-policy-file> <req-policy-file>] [options]\n");
3117 System.out.println("\t\tTake one or more pairs of main-req policy files, and generate Java and/or C++ files\n");
3118 System.out.println("Options:");
3119 System.out.println("\t-java\t<directory>\tGenerate Java stub files");
3120 System.out.println("\t-cplus\t<directory>\tGenerate C++ stub files");
3121 System.out.println();
3126 * parseFile() prepares Lexer and Parser objects, then parses the file
3128 public static ParseNode parseFile(String file) {
3130 ParseNode pn = null;
3132 ComplexSymbolFactory csf = new ComplexSymbolFactory();
3133 ScannerBuffer lexer =
3134 new ScannerBuffer(new Lexer(new BufferedReader(new FileReader(file)),csf));
3135 Parser parse = new Parser(lexer,csf);
3136 pn = (ParseNode) parse.parse().value;
3137 } catch (Exception e) {
3138 e.printStackTrace();
3139 throw new Error("IoTCompiler: ERROR parsing policy file or wrong command line option: " + file);
3150 boolean newline=true;
3153 private void print(String str) {
3156 if (str.equals("}"))
3158 for(int i=0; i<tab; i++)
3168 * This function converts Java to C++ type for compilation
3170 private String convertType(String jType) {
3172 return mapPrimitives.get(jType);
3176 private void println(String str) {
3179 if (str.contains("}") && !str.contains("{"))
3181 for(int i=0; i<tab; i++)
3190 private void updatetabbing(String str) {
3192 tablevel+=count(str,'{')-count(str,'}');
3196 private int count(String str, char key) {
3197 char[] array = str.toCharArray();
3199 for(int i=0; i<array.length; i++) {
3200 if (array[i] == key)
3207 private void createDirectory(String dirName) {
3209 File file = new File(dirName);
3210 if (!file.exists()) {
3212 System.out.println("IoTCompiler: Directory " + dirName + " has been created!");
3214 System.out.println("IoTCompiler: Failed to create directory " + dirName + "!");
3217 System.out.println("IoTCompiler: Directory " + dirName + " exists...");
3222 // Create a directory and possibly a sub directory
3223 private String createDirectories(String dir, String subdir) {
3226 createDirectory(path);
3227 if (subdir != null) {
3228 path = path + "/" + subdir;
3229 createDirectory(path);
3235 // Inserting array members into a Map object
3236 // that maps arrKey to arrVal objects
3237 private void arraysToMap(Map map, Object[] arrKey, Object[] arrVal) {
3239 for(int i = 0; i < arrKey.length; i++) {
3241 map.put(arrKey[i], arrVal[i]);
3246 // Return parameter category, i.e. PRIMITIVES, NONPRIMITIVES, or USERDEFINED
3247 private ParamCategory getParamCategory(String paramType) {
3249 if (mapPrimitives.containsKey(paramType)) {
3250 return ParamCategory.PRIMITIVES;
3251 // We can either use mapNonPrimitivesJava or mapNonPrimitivesCplus here
3252 } else if (mapNonPrimitivesJava.containsKey(getSimpleType(paramType))) {
3253 return ParamCategory.NONPRIMITIVES;
3254 } else if (isEnumClass(paramType)) {
3255 return ParamCategory.ENUM;
3256 } else if (isStructClass(paramType)) {
3257 return ParamCategory.STRUCT;
3259 return ParamCategory.USERDEFINED;
3263 // Return full class name for non-primitives to generate Java import statements
3264 // e.g. java.util.Set for Set, java.util.Map for Map
3265 private String getNonPrimitiveJavaClass(String paramNonPrimitives) {
3267 return mapNonPrimitivesJava.get(paramNonPrimitives);
3271 // Return full class name for non-primitives to generate Cplus include statements
3272 // e.g. #include <set> for Set, #include <map> for Map
3273 private String getNonPrimitiveCplusClass(String paramNonPrimitives) {
3275 return mapNonPrimitivesCplus.get(paramNonPrimitives);
3279 // Get simple types, e.g. HashSet for HashSet<...>
3280 // Basically strip off the "<...>"
3281 private String getSimpleType(String paramType) {
3283 // Check if this is generics
3284 if(paramType.contains("<")) {
3285 String[] type = paramType.split("<");
3292 // Generate a set of standard classes for import statements
3293 private List<String> getStandardJavaImportClasses() {
3295 List<String> importClasses = new ArrayList<String>();
3296 // Add the standard list first
3297 importClasses.add("java.io.IOException");
3298 importClasses.add("java.util.List");
3299 importClasses.add("java.util.ArrayList");
3300 importClasses.add("java.util.Arrays");
3301 importClasses.add("iotrmi.Java.IoTRMICall");
3302 importClasses.add("iotrmi.Java.IoTRMIObject");
3304 return importClasses;
3308 // Generate a set of standard classes for import statements
3309 private List<String> getStandardCplusIncludeClasses() {
3311 List<String> importClasses = new ArrayList<String>();
3312 // Add the standard list first
3313 importClasses.add("<vector>");
3314 importClasses.add("<set>");
3315 importClasses.add("\"IoTRMICall.hpp\"");
3316 importClasses.add("\"IoTRMIObject.hpp\"");
3318 return importClasses;
3322 // Generate a set of standard classes for import statements
3323 private List<String> getAllLibClasses(Collection<String> stdLibClasses, Collection<String> libClasses) {
3325 List<String> allLibClasses = new ArrayList<String>(stdLibClasses);
3326 // Iterate over the list of import classes
3327 for (String str : libClasses) {
3328 if (!allLibClasses.contains(str)) {
3329 allLibClasses.add(str);
3333 return allLibClasses;
3338 // Generate a set of classes for import statements
3339 private Set<String> getImportClasses(Collection<String> methods, InterfaceDecl intDecl) {
3341 Set<String> importClasses = new HashSet<String>();
3342 for (String method : methods) {
3343 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
3344 for (String paramType : methPrmTypes) {
3346 String simpleType = getSimpleType(paramType);
3347 if (getParamCategory(simpleType) == ParamCategory.NONPRIMITIVES) {
3348 importClasses.add(getNonPrimitiveJavaClass(simpleType));
3352 return importClasses;
3356 // Handle and return the correct enum declaration
3357 // In Java, if we declare enum in Camera interface, then it becomes "Camera.<enum>"
3358 private String getEnumParamDecl(String type, InterfaceDecl intDecl) {
3360 // Strips off array "[]" for return type
3361 String pureType = getSimpleArrayType(type);
3362 // Take the inner type of generic
3363 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
3364 pureType = getTypeOfGeneric(type)[0];
3365 if (isEnumClass(pureType)) {
3366 String enumType = intDecl.getInterface() + "." + type;
3373 // Handle and return the correct type
3374 private String getEnumParam(String type, String param, int i) {
3376 // Strips off array "[]" for return type
3377 String pureType = getSimpleArrayType(type);
3378 // Take the inner type of generic
3379 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
3380 pureType = getTypeOfGeneric(type)[0];
3381 if (isEnumClass(pureType)) {
3382 String enumParam = "paramEnum" + i;
3389 // Handle and return the correct enum declaration translate into int[]
3390 private String getEnumType(String type) {
3392 // Strips off array "[]" for return type
3393 String pureType = getSimpleArrayType(type);
3394 // Take the inner type of generic
3395 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
3396 pureType = getTypeOfGeneric(type)[0];
3397 if (isEnumClass(pureType)) {
3398 String enumType = "int[]";
3405 // Handle and return the correct struct declaration
3406 private String getStructType(String type) {
3408 if (isStructClass(type)) {
3409 // TODO: complete this method
3416 // Check if this an enum declaration
3417 private boolean isEnumClass(String type) {
3419 // Just iterate over the set of interfaces
3420 for (String intface : mapIntfacePTH.keySet()) {
3421 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
3422 EnumDecl enumDecl = (EnumDecl) decHandler.getEnumDecl(intface);
3423 Set<String> setEnumDecl = enumDecl.getEnumDeclarations();
3424 if (setEnumDecl.contains(type))
3431 // Check if this an struct declaration
3432 private boolean isStructClass(String type) {
3434 // Just iterate over the set of interfaces
3435 for (String intface : mapIntfacePTH.keySet()) {
3436 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
3437 StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
3438 List<String> listStructDecl = structDecl.getStructTypes();
3439 if (listStructDecl.contains(type))
3446 // Generate a set of classes for include statements
3447 private Set<String> getIncludeClasses(Collection<String> methods, InterfaceDecl intDecl, String intface, boolean needExchange) {
3449 Set<String> includeClasses = new HashSet<String>();
3450 for (String method : methods) {
3452 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
3453 List<String> methParams = intDecl.getMethodParams(method);
3454 for (int i = 0; i < methPrmTypes.size(); i++) {
3456 String simpleType = getSimpleType(methPrmTypes.get(i));
3457 String param = methParams.get(i);
3458 if (getParamCategory(simpleType) == ParamCategory.NONPRIMITIVES) {
3459 includeClasses.add("<" + getNonPrimitiveCplusClass(simpleType) + ">");
3460 } else if (getParamCategory(simpleType) == ParamCategory.USERDEFINED) {
3461 // For original interface, we need it exchanged... not for stub interfaces
3463 includeClasses.add("\"" + exchangeParamType(simpleType) + ".hpp\"");
3464 includeClasses.add("\"" + exchangeParamType(simpleType) + "_CallbackStub.hpp\"");
3466 includeClasses.add("\"" + simpleType + ".hpp\"");
3467 includeClasses.add("\"" + simpleType + "_CallbackSkeleton.hpp\"");
3469 } else if (getParamCategory(getSimpleArrayType(simpleType)) == ParamCategory.ENUM) {
3470 includeClasses.add("\"" + simpleType + ".hpp\"");
3471 } else if (param.contains("[]")) {
3472 // Check if this is array for C++; translate into vector
3473 includeClasses.add("<vector>");
3477 return includeClasses;
3481 // Generate a set of callback classes
3482 private Set<String> getCallbackClasses(Collection<String> methods, InterfaceDecl intDecl) {
3484 Set<String> callbackClasses = new HashSet<String>();
3485 for (String method : methods) {
3487 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
3488 List<String> methParams = intDecl.getMethodParams(method);
3489 for (int i = 0; i < methPrmTypes.size(); i++) {
3491 String type = methPrmTypes.get(i);
3492 if (getParamCategory(type) == ParamCategory.USERDEFINED) {
3493 callbackClasses.add(type);
3494 } else if (getParamCategory(type) == ParamCategory.NONPRIMITIVES) {
3495 // Can be a List<...> of callback objects ...
3496 String genericType = getTypeOfGeneric(type)[0];
3497 if (getParamCategory(type) == ParamCategory.USERDEFINED) {
3498 callbackClasses.add(type);
3503 return callbackClasses;
3507 private void printImportStatements(Collection<String> importClasses) {
3509 for(String cls : importClasses) {
3510 println("import " + cls + ";");
3515 private void printIncludeStatements(Collection<String> includeClasses) {
3517 for(String cls : includeClasses) {
3518 println("#include " + cls);
3523 // Get the C++ version of a non-primitive type
3524 // e.g. set for Set and map for Map
3525 // Input nonPrimitiveType has to be generics in format
3526 private String[] getTypeOfGeneric(String nonPrimitiveType) {
3528 // Handle <, >, and , for 2-type generic/template
3529 String[] substr = nonPrimitiveType.split("<")[1].split(">")[0].split(",");
3534 // This helper function strips off array declaration, e.g. int[] becomes int
3535 private String getSimpleArrayType(String type) {
3537 // Handle [ for array declaration
3538 String substr = type;
3539 if (type.contains("[]")) {
3540 substr = type.split("\\[\\]")[0];
3546 // This helper function strips off array declaration, e.g. D[] becomes D
3547 private String getSimpleIdentifier(String ident) {
3549 // Handle [ for array declaration
3550 String substr = ident;
3551 if (ident.contains("[]")) {
3552 substr = ident.split("\\[\\]")[0];
3558 private String checkAndGetCplusType(String paramType) {
3560 if (getParamCategory(paramType) == ParamCategory.PRIMITIVES) {
3561 return convertType(paramType);
3562 } else if (getParamCategory(paramType) == ParamCategory.NONPRIMITIVES) {
3564 // Check for generic/template format
3565 if (paramType.contains("<") && paramType.contains(">")) {
3567 String genericClass = getSimpleType(paramType);
3568 String[] genericType = getTypeOfGeneric(paramType);
3569 String cplusTemplate = null;
3570 if (genericType.length == 1) // Generic/template with one type
3571 cplusTemplate = getNonPrimitiveCplusClass(genericClass) +
3572 "<" + convertType(genericType[0]) + ">";
3573 else // Generic/template with two types
3574 cplusTemplate = getNonPrimitiveCplusClass(genericClass) +
3575 "<" + convertType(genericType[0]) + "," + convertType(genericType[1]) + ">";
3576 return cplusTemplate;
3578 return getNonPrimitiveCplusClass(paramType);
3579 } else if(getParamCategory(paramType) == ParamCategory.USERDEFINED) {
3580 return paramType + "*";
3582 // Just return it as is if it's not non-primitives
3584 //return checkAndGetParamClass(paramType, true);
3588 // Detect array declaration, e.g. int A[],
3589 // then generate "int A[]" in C++ as "vector<int> A"
3590 private String checkAndGetCplusArray(String paramType, String param) {
3592 String paramComplete = null;
3593 // Check for array declaration
3594 if (param.contains("[]")) {
3595 paramComplete = "vector<" + paramType + "> " + param.replace("[]","");
3597 // Just return it as is if it's not an array
3598 paramComplete = paramType + " " + param;
3600 return paramComplete;
3604 // Detect array declaration, e.g. int A[],
3605 // then generate "int A[]" in C++ as "vector<int> A"
3606 // This method just returns the type
3607 private String checkAndGetCplusArrayType(String paramType) {
3609 String paramTypeRet = null;
3610 // Check for array declaration
3611 if (paramType.contains("[]")) {
3612 String type = paramType.split("\\[\\]")[0];
3613 paramTypeRet = checkAndGetCplusType(type) + "[]";
3614 } else if (paramType.contains("vector")) {
3615 // Just return it as is if it's not an array
3616 String type = paramType.split("<")[1].split(">")[0];
3617 paramTypeRet = checkAndGetCplusType(type) + "[]";
3619 paramTypeRet = paramType;
3621 return paramTypeRet;
3625 // Detect array declaration, e.g. int A[],
3626 // then generate "int A[]" in C++ as "vector<int> A"
3627 // This method just returns the type
3628 private String checkAndGetCplusArrayType(String paramType, String param) {
3630 String paramTypeRet = null;
3631 // Check for array declaration
3632 if (param.contains("[]")) {
3633 paramTypeRet = checkAndGetCplusType(paramType) + "[]";
3634 } else if (paramType.contains("vector")) {
3635 // Just return it as is if it's not an array
3636 String type = paramType.split("<")[1].split(">")[0];
3637 paramTypeRet = checkAndGetCplusType(type) + "[]";
3639 paramTypeRet = paramType;
3641 return paramTypeRet;
3645 // Detect array declaration, e.g. int A[],
3646 // then generate type "int[]"
3647 private String checkAndGetArray(String paramType, String param) {
3649 String paramTypeRet = null;
3650 // Check for array declaration
3651 if (param.contains("[]")) {
3652 paramTypeRet = paramType + "[]";
3654 // Just return it as is if it's not an array
3655 paramTypeRet = paramType;
3657 return paramTypeRet;
3661 // Is array or list?
3662 private boolean isArrayOrList(String paramType, String param) {
3664 // Check for array declaration
3667 else if (isList(paramType))
3674 // Is array? For return type we put the return type as input parameter
3675 private boolean isArray(String param) {
3677 // Check for array declaration
3678 if (param.contains("[]"))
3686 private boolean isList(String paramType) {
3688 // Check for array declaration
3689 if (paramType.contains("List"))
3696 // Get the right type for a callback object
3697 private String checkAndGetParamClass(String paramType) {
3699 // Check if this is generics
3700 if(getParamCategory(paramType) == ParamCategory.USERDEFINED) {
3701 return exchangeParamType(paramType);
3707 // Returns the other interface for type-checking purposes for USERDEFINED
3708 // classes based on the information provided in multiple policy files
3709 // e.g. return CameraWithXXX instead of Camera
3710 private String exchangeParamType(String intface) {
3712 // Param type that's passed is the interface name we need to look for
3713 // in the map of interfaces, based on available policy files.
3714 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
3715 if (decHandler != null) {
3716 // We've found the required interface policy files
3717 RequiresDecl reqDecl = (RequiresDecl) decHandler.getRequiresDecl(intface);
3718 Set<String> setExchInt = reqDecl.getInterfaces();
3719 if (setExchInt.size() == 1) {
3720 Iterator iter = setExchInt.iterator();
3721 return (String) iter.next();
3723 throw new Error("IoTCompiler: Ambiguous stub interfaces: " + setExchInt.toString() +
3724 ". Only one new interface can be declared if the object " + intface +
3725 " needs to be passed in as an input parameter!");
3728 // NULL value - this means policy files missing
3729 throw new Error("IoTCompiler: Parameter type lookup failed for " + intface +
3730 "... Please provide the necessary policy files for user-defined types." +
3731 " If this is an array please type the brackets after the variable name," +
3732 " e.g. \"String str[]\", not \"String[] str\"." +
3733 " If this is a Collections (Java) / STL (C++) type, this compiler only" +
3734 " supports List/ArrayList (Java) or list (C++).");
3739 public static void main(String[] args) throws Exception {
3741 // If there is no argument or just "--help" or "-h", then invoke printUsage()
3742 if ((args[0].equals("-help") ||
3743 args[0].equals("--help")||
3744 args[0].equals("-h")) ||
3745 (args.length == 0)) {
3747 IoTCompiler.printUsage();
3749 } else if (args.length > 1) {
3751 IoTCompiler comp = new IoTCompiler();
3754 // Parse main policy file
3755 ParseNode pnPol = IoTCompiler.parseFile(args[i]);
3756 // Parse "requires" policy file
3757 ParseNode pnReq = IoTCompiler.parseFile(args[i+1]);
3758 // Get interface name
3759 String intface = ParseTreeHandler.getOrigIntface(pnPol);
3760 comp.setDataStructures(intface, pnPol, pnReq);
3761 comp.getMethodsForIntface(intface);
3763 // 1) Check if this is the last option before "-java" or "-cplus"
3764 // 2) Check if this is really the last option (no "-java" or "-cplus")
3765 } while(!args[i].equals("-java") &&
3766 !args[i].equals("-cplus") &&
3769 // Generate everything if we don't see "-java" or "-cplus"
3770 if (i == args.length) {
3771 comp.generateEnumJava();
3772 comp.generateStructJava();
3773 comp.generateJavaLocalInterfaces();
3774 comp.generateJavaInterfaces();
3775 comp.generateJavaStubClasses();
3776 comp.generateJavaCallbackStubClasses();
3777 comp.generateJavaSkeletonClass();
3778 comp.generateJavaCallbackSkeletonClass();
3779 comp.generateEnumCplus();
3780 comp.generateStructCplus();
3781 comp.generateCplusLocalInterfaces();
3782 comp.generateCPlusInterfaces();
3783 comp.generateCPlusStubClasses();
3784 comp.generateCPlusCallbackStubClasses();
3785 comp.generateCplusSkeletonClass();
3786 comp.generateCplusCallbackSkeletonClass();
3788 // Check other options
3789 while(i < args.length) {
3791 if (!args[i].equals("-java") &&
3792 !args[i].equals("-cplus")) {
3793 throw new Error("IoTCompiler: ERROR - unrecognized command line option: " + args[i]);
3795 if (i + 1 < args.length) {
3796 comp.setDirectory(args[i+1]);
3798 throw new Error("IoTCompiler: ERROR - please provide <directory> after option: " + args[i]);
3800 if (args[i].equals("-java")) {
3801 comp.generateEnumJava();
3802 comp.generateStructJava();
3803 comp.generateJavaLocalInterfaces();
3804 comp.generateJavaInterfaces();
3805 comp.generateJavaStubClasses();
3806 comp.generateJavaCallbackStubClasses();
3807 comp.generateJavaSkeletonClass();
3808 comp.generateJavaCallbackSkeletonClass();
3810 comp.generateEnumCplus();
3811 comp.generateStructCplus();
3812 comp.generateCplusLocalInterfaces();
3813 comp.generateCPlusInterfaces();
3814 comp.generateCPlusStubClasses();
3815 comp.generateCPlusCallbackStubClasses();
3816 comp.generateCplusSkeletonClass();
3817 comp.generateCplusCallbackSkeletonClass();
3824 // Need to at least have exactly 2 parameters, i.e. main policy file and requires file
3825 IoTCompiler.printUsage();
3826 throw new Error("IoTCompiler: At least two arguments (main and requires policy files) have to be provided!");