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;
66 private final static String OUTPUT_DIRECTORY = "output_files";
68 private enum ParamCategory {
70 PRIMITIVES, // All the primitive types, e.g. byte, short, int, long, etc.
71 NONPRIMITIVES, // Non-primitive types, e.g. Set, Map, List, etc.
73 STRUCT, // Struct type
74 USERDEFINED // Assumed as driver classes
81 public IoTCompiler() {
83 mapIntfacePTH = new HashMap<String,ParseTreeHandler>();
84 mapIntDeclHand = new HashMap<String,DeclarationHandler>();
85 mapInt2NewInts = new HashMap<String,Map<String,Set<String>>>();
86 mapIntfaceObjId = new HashMap<String,Integer>();
87 mapNewIntfaceObjId = new HashMap<String,Integer>();
88 mapPrimitives = new HashMap<String,String>();
89 arraysToMap(mapPrimitives, IoTRMITypes.primitivesJava, IoTRMITypes.primitivesCplus);
90 mapNonPrimitivesJava = new HashMap<String,String>();
91 arraysToMap(mapNonPrimitivesJava, IoTRMITypes.nonPrimitivesJava, IoTRMITypes.nonPrimitiveJavaLibs);
92 mapNonPrimitivesCplus = new HashMap<String,String>();
93 arraysToMap(mapNonPrimitivesCplus, IoTRMITypes.nonPrimitivesJava, IoTRMITypes.nonPrimitivesCplus);
95 dir = OUTPUT_DIRECTORY;
101 * setDataStructures() sets parse tree and other data structures based on policy files.
103 * It also generates parse tree (ParseTreeHandler) and
104 * copies useful information from parse tree into
105 * InterfaceDecl, CapabilityDecl, and RequiresDecl
107 * Additionally, the data structure handles are
108 * returned from tree-parsing for further process.
110 public void setDataStructures(String origInt, ParseNode pnPol, ParseNode pnReq) {
112 ParseTreeHandler ptHandler = new ParseTreeHandler(origInt, pnPol, pnReq);
113 DeclarationHandler decHandler = new DeclarationHandler();
114 // Process ParseNode and generate Declaration objects
116 ptHandler.processInterfaceDecl();
117 InterfaceDecl intDecl = ptHandler.getInterfaceDecl();
118 decHandler.addInterfaceDecl(origInt, intDecl);
120 ptHandler.processCapabilityDecl();
121 CapabilityDecl capDecl = ptHandler.getCapabilityDecl();
122 decHandler.addCapabilityDecl(origInt, capDecl);
124 ptHandler.processRequiresDecl();
125 RequiresDecl reqDecl = ptHandler.getRequiresDecl();
126 decHandler.addRequiresDecl(origInt, reqDecl);
128 ptHandler.processEnumDecl();
129 EnumDecl enumDecl = ptHandler.getEnumDecl();
130 decHandler.addEnumDecl(origInt, enumDecl);
132 ptHandler.processStructDecl();
133 StructDecl structDecl = ptHandler.getStructDecl();
134 decHandler.addStructDecl(origInt, structDecl);
136 mapIntfacePTH.put(origInt, ptHandler);
137 mapIntDeclHand.put(origInt, decHandler);
138 // Set object Id counter to 0 for each interface
139 mapIntfaceObjId.put(origInt, new Integer(0));
144 * getMethodsForIntface() reads for methods in the data structure
146 * It is going to give list of methods for a certain interface
147 * based on the declaration of capabilities.
149 public void getMethodsForIntface(String origInt) {
151 ParseTreeHandler ptHandler = mapIntfacePTH.get(origInt);
152 Map<String,Set<String>> mapNewIntMethods = new HashMap<String,Set<String>>();
153 // Get set of new interfaces, e.g. CameraWithCaptureAndData
154 // Generate this new interface with all the methods it needs
155 // from different capabilities it declares
156 DeclarationHandler decHandler = mapIntDeclHand.get(origInt);
157 RequiresDecl reqDecl = (RequiresDecl) decHandler.getRequiresDecl(origInt);
158 Set<String> setIntfaces = reqDecl.getInterfaces();
159 for (String strInt : setIntfaces) {
161 // Initialize a set of methods
162 Set<String> setMethods = new HashSet<String>();
163 // Get list of capabilities, e.g. ImageCapture, VideoRecording, etc.
164 List<String> listCapab = reqDecl.getCapabList(strInt);
165 for (String strCap : listCapab) {
167 // Get list of methods for each capability
168 CapabilityDecl capDecl = (CapabilityDecl) decHandler.getCapabilityDecl(origInt);
169 List<String> listCapabMeth = capDecl.getMethods(strCap);
170 for (String strMeth : listCapabMeth) {
172 // Add methods into setMethods
173 // This is to also handle redundancies (say two capabilities
174 // share the same methods)
175 setMethods.add(strMeth);
178 // Add interface and methods information into map
179 mapNewIntMethods.put(strInt, setMethods);
181 // Map the map of interface-methods to the original interface
182 mapInt2NewInts.put(origInt, mapNewIntMethods);
187 * HELPER: writeMethodJavaLocalInterface() writes the method of the local interface
189 private void writeMethodJavaLocalInterface(Collection<String> methods, InterfaceDecl intDecl) {
191 for (String method : methods) {
193 List<String> methParams = intDecl.getMethodParams(method);
194 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
195 print("public " + intDecl.getMethodType(method) + " " +
196 intDecl.getMethodId(method) + "(");
197 for (int i = 0; i < methParams.size(); i++) {
198 // Check for params with driver class types and exchange it
199 // with its remote interface
200 String paramType = checkAndGetParamClass(methPrmTypes.get(i));
201 print(paramType + " " + methParams.get(i));
202 // Check if this is the last element (don't print a comma)
203 if (i != methParams.size() - 1) {
213 * HELPER: writeMethodJavaInterface() writes the method of the interface
215 private void writeMethodJavaInterface(Collection<String> methods, InterfaceDecl intDecl) {
217 for (String method : methods) {
219 List<String> methParams = intDecl.getMethodParams(method);
220 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
221 print("public " + intDecl.getMethodType(method) + " " +
222 intDecl.getMethodId(method) + "(");
223 for (int i = 0; i < methParams.size(); i++) {
224 // Check for params with driver class types and exchange it
225 // with its remote interface
226 String paramType = methPrmTypes.get(i);
227 print(paramType + " " + methParams.get(i));
228 // Check if this is the last element (don't print a comma)
229 if (i != methParams.size() - 1) {
239 * HELPER: generateEnumJava() writes the enumeration declaration
241 private void generateEnumJava() throws IOException {
243 // Create a new directory
244 createDirectory(dir);
245 for (String intface : mapIntfacePTH.keySet()) {
246 // Get the right EnumDecl
247 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
248 EnumDecl enumDecl = (EnumDecl) decHandler.getEnumDecl(intface);
249 Set<String> enumTypes = enumDecl.getEnumDeclarations();
250 // Iterate over enum declarations
251 for (String enType : enumTypes) {
252 // Open a new file to write into
253 FileWriter fw = new FileWriter(dir + "/" + enType + ".java");
254 pw = new PrintWriter(new BufferedWriter(fw));
255 println("public enum " + enType + " {");
256 List<String> enumMembers = enumDecl.getMembers(enType);
257 for (int i = 0; i < enumMembers.size(); i++) {
259 String member = enumMembers.get(i);
261 // Check if this is the last element (don't print a comma)
262 if (i != enumMembers.size() - 1)
269 System.out.println("IoTCompiler: Generated enum class " + enType + ".java...");
276 * HELPER: generateStructJava() writes the struct declaration
278 private void generateStructJava() throws IOException {
280 // Create a new directory
281 createDirectory(dir);
282 for (String intface : mapIntfacePTH.keySet()) {
283 // Get the right StructDecl
284 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
285 StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
286 List<String> structTypes = structDecl.getStructTypes();
287 // Iterate over enum declarations
288 for (String stType : structTypes) {
289 // Open a new file to write into
290 FileWriter fw = new FileWriter(dir + "/" + stType + ".java");
291 pw = new PrintWriter(new BufferedWriter(fw));
292 println("public class " + stType + " {");
293 List<String> structMemberTypes = structDecl.getMemberTypes(stType);
294 List<String> structMembers = structDecl.getMembers(stType);
295 for (int i = 0; i < structMembers.size(); i++) {
297 String memberType = structMemberTypes.get(i);
298 String member = structMembers.get(i);
299 println("public static " + memberType + " " + member + ";");
303 System.out.println("IoTCompiler: Generated struct class " + stType + ".java...");
310 * generateJavaLocalInterface() writes the local interface and provides type-checking.
312 * It needs to rewrite and exchange USERDEFINED types in input parameters of stub
313 * and original interfaces, e.g. exchange Camera and CameraWithVideoAndRecording.
314 * The local interface has to be the input parameter for the stub and the stub
315 * interface has to be the input parameter for the local class.
317 public void generateJavaLocalInterfaces() throws IOException {
319 // Create a new directory
320 createDirectory(dir);
321 for (String intface : mapIntfacePTH.keySet()) {
322 // Open a new file to write into
323 FileWriter fw = new FileWriter(dir + "/" + intface + ".java");
324 pw = new PrintWriter(new BufferedWriter(fw));
325 // Pass in set of methods and get import classes
326 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
327 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
328 List<String> methods = intDecl.getMethods();
329 Set<String> importClasses = getImportClasses(methods, intDecl);
330 List<String> stdImportClasses = getStandardJavaIntfaceImportClasses();
331 List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
332 printImportStatements(allImportClasses);
333 // Write interface header
335 println("public interface " + intface + " {");
337 writeMethodJavaLocalInterface(methods, intDecl);
340 System.out.println("IoTCompiler: Generated local interface " + intface + ".java...");
346 * generateJavaInterfaces() generate stub interfaces based on the methods list in Java
348 public void generateJavaInterfaces() throws IOException {
350 // Create a new directory
351 String path = createDirectories(dir, subdir);
352 for (String intface : mapIntfacePTH.keySet()) {
354 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
355 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
357 // Open a new file to write into
358 String newIntface = intMeth.getKey();
359 FileWriter fw = new FileWriter(path + "/" + newIntface + ".java");
360 pw = new PrintWriter(new BufferedWriter(fw));
361 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
362 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
363 // Pass in set of methods and get import classes
364 List<String> methods = intDecl.getMethods();
365 Set<String> importClasses = getImportClasses(methods, intDecl);
366 List<String> stdImportClasses = getStandardJavaIntfaceImportClasses();
367 List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
368 printImportStatements(allImportClasses);
369 // Write interface header
371 println("public interface " + newIntface + " {\n");
373 writeMethodJavaInterface(methods, 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 = getNewIntfaceObjectId(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 static 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 callbackAddress;");
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 = getNewIntfaceObjectId(newIntface);
450 println("set" + newObjectId + "Allowed = new ArrayList<Integer>(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 _skeletonAddress, String _callbackAddress, int _rev, int[] _ports) throws Exception {");
461 println("callbackAddress = _callbackAddress;");
462 println("ports = _ports;");
463 println("rmiCall = new IoTRMICall(_port, _skeletonAddress, _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 = getNewIntfaceObjectId(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: writeJavaInitCallbackPermission() writes the permission for callback
496 private void writeJavaInitCallbackPermission(String intface, InterfaceDecl intDecl, boolean callbackExist) {
499 String method = "___initCallBack()";
500 int methodNumId = intDecl.getHelperMethodNumId(method);
501 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
502 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
503 String newIntface = intMeth.getKey();
504 int newObjectId = getNewIntfaceObjectId(newIntface);
505 println("set" + newObjectId + "Allowed.add(" + methodNumId + ");");
512 * HELPER: writeInitCallbackJavaStub() writes callback initialization in stub
514 private void writeInitCallbackJavaStub(String intface, InterfaceDecl intDecl) {
516 println("public void ___initCallBack() {");
517 // Generate main thread for callbacks
518 println("Thread thread = new Thread() {");
519 println("public void run() {");
521 println("rmiObj = new IoTRMIObject(ports[0]);");
522 println("while (true) {");
523 println("byte[] method = rmiObj.getMethodBytes();");
524 writeJavaMethodCallbackPermission(intface);
525 println("int objId = IoTRMIObject.getObjectId(method);");
526 println(intface + "_CallbackSkeleton skel = (" + intface + "_CallbackSkeleton) listCallbackObj.get(objId);");
527 println("if (skel != null) {");
528 println("skel.invokeMethod(rmiObj);");
531 println("throw new Error(\"" + intface + ": Object with Id \" + objId + \" not found!\");");
535 println(" catch (Exception ex) {");
536 println("ex.printStackTrace();");
537 println("throw new Error(\"Error instantiating class " + intface + "_CallbackSkeleton!\");");
541 println("thread.start();\n");
542 // Generate info sending part
543 String method = "___initCallBack()";
544 int methodNumId = intDecl.getHelperMethodNumId(method);
545 println("int methodId = " + methodNumId + ";");
546 println("Class<?> retType = void.class;");
547 println("Class<?>[] paramCls = new Class<?>[] { int.class, String.class, int.class };");
548 println("Object[] paramObj = new Object[] { ports[0], callbackAddress, 0 };");
549 println("rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
555 * HELPER: checkAndWriteEnumTypeJavaStub() writes the enum type (convert from enum to int)
557 private void checkAndWriteEnumTypeJavaStub(List<String> methParams, List<String> methPrmTypes) {
559 // Iterate and find enum declarations
560 for (int i = 0; i < methParams.size(); i++) {
561 String paramType = methPrmTypes.get(i);
562 String param = methParams.get(i);
563 String simpleType = getGenericType(paramType);
564 if (isEnumClass(simpleType)) {
565 // Check if this is enum type
566 if (isArray(param)) { // An array
567 println("int len" + i + " = " + getSimpleIdentifier(param) + ".length;");
568 println("int paramEnum" + i + "[] = new int[len" + i + "];");
569 println("for (int i = 0; i < len" + i + "; i++) {");
570 println("paramEnum" + i + "[i] = " + getSimpleIdentifier(param) + "[i].ordinal();");
572 } else if (isList(paramType)) { // A list
573 println("int len" + i + " = " + getSimpleIdentifier(param) + ".size();");
574 println("int paramEnum" + i + "[] = new int[len" + i + "];");
575 println("for (int i = 0; i < len" + i + "; i++) {");
576 println("paramEnum" + i + "[i] = " + getSimpleIdentifier(param) + ".get(i).ordinal();");
578 } else { // Just one element
579 println("int paramEnum" + i + "[] = new int[1];");
580 println("paramEnum" + i + "[0] = " + param + ".ordinal();");
588 * HELPER: checkAndWriteEnumRetTypeJavaStub() writes the enum return type (convert from enum to int)
590 private void checkAndWriteEnumRetTypeJavaStub(String retType) {
592 // Strips off array "[]" for return type
593 String pureType = getSimpleArrayType(getGenericType(retType));
594 // Take the inner type of generic
595 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
596 pureType = getGenericType(retType);
597 if (isEnumClass(pureType)) {
598 // Check if this is enum type
600 println("int[] retEnum = (int[]) retObj;");
601 println(pureType + "[] enumVals = " + pureType + ".values();");
602 if (isArray(retType)) { // An array
603 println("int retLen = retEnum.length;");
604 println(pureType + "[] enumRetVal = new " + pureType + "[retLen];");
605 println("for (int i = 0; i < retLen; i++) {");
606 println("enumRetVal[i] = enumVals[retEnum[i]];");
608 } else if (isList(retType)) { // A list
609 println("int retLen = retEnum.length;");
610 println("List<" + pureType + "> enumRetVal = new ArrayList<" + pureType + ">();");
611 println("for (int i = 0; i < retLen; i++) {");
612 println("enumRetVal.add(enumVals[retEnum[i]]);");
614 } else { // Just one element
615 println(pureType + " enumRetVal = enumVals[retEnum[0]];");
617 println("return enumRetVal;");
623 * HELPER: checkAndWriteStructSetupJavaStub() writes the struct type setup
625 private void checkAndWriteStructSetupJavaStub(List<String> methParams, List<String> methPrmTypes,
626 InterfaceDecl intDecl, String method) {
628 // Iterate and find struct declarations
629 for (int i = 0; i < methParams.size(); i++) {
630 String paramType = methPrmTypes.get(i);
631 String param = methParams.get(i);
632 String simpleType = getGenericType(paramType);
633 if (isStructClass(simpleType)) {
634 // Check if this is enum type
635 int methodNumId = intDecl.getMethodNumId(method);
636 String helperMethod = methodNumId + "struct" + i;
637 println("int methodIdStruct" + i + " = " + intDecl.getHelperMethodNumId(helperMethod) + ";");
638 println("Class<?> retTypeStruct" + i + " = void.class;");
639 println("Class<?>[] paramClsStruct" + i + " = new Class<?>[] { int.class };");
640 if (isArray(param)) { // An array
641 println("Object[] paramObjStruct" + i + " = new Object[] { " + getSimpleArrayType(param) + ".length };");
642 } else if (isList(paramType)) { // A list
643 println("Object[] paramObjStruct" + i + " = new Object[] { " + getSimpleArrayType(param) + ".size() };");
644 } else { // Just one element
645 println("Object[] paramObjStruct" + i + " = new Object[] { new Integer(1) };");
647 println("rmiCall.remoteCall(objectId, methodIdStruct" + i +
648 ", retTypeStruct" + i + ", null, paramClsStruct" + i +
649 ", paramObjStruct" + i + ");\n");
656 * HELPER: isStructPresent() checks presence of struct
658 private boolean isStructPresent(List<String> methParams, List<String> methPrmTypes) {
660 // Iterate and find enum declarations
661 for (int i = 0; i < methParams.size(); i++) {
662 String paramType = methPrmTypes.get(i);
663 String param = methParams.get(i);
664 String simpleType = getGenericType(paramType);
665 if (isStructClass(simpleType))
673 * HELPER: writeLengthStructParamClassJavaStub() writes lengths of parameters
675 private void writeLengthStructParamClassJavaStub(List<String> methParams, List<String> methPrmTypes) {
677 // Iterate and find struct declarations - count number of params
678 for (int i = 0; i < methParams.size(); i++) {
679 String paramType = methPrmTypes.get(i);
680 String param = methParams.get(i);
681 String simpleType = getGenericType(paramType);
682 if (isStructClass(simpleType)) {
683 int members = getNumOfMembers(simpleType);
684 if (isArray(param)) { // An array
685 String structLen = getSimpleArrayType(param) + ".length";
686 print(members + "*" + structLen);
687 } else if (isList(paramType)) { // A list
688 String structLen = getSimpleArrayType(param) + ".size()";
689 print(members + "*" + structLen);
691 print(Integer.toString(members));
694 if (i != methParams.size() - 1) {
702 * HELPER: writeStructMembersJavaStub() writes parameters of struct
704 private void writeStructMembersJavaStub(String simpleType, String paramType, String param) {
706 // Get the struct declaration for this struct and generate initialization code
707 StructDecl structDecl = getStructDecl(simpleType);
708 List<String> memTypes = structDecl.getMemberTypes(simpleType);
709 List<String> members = structDecl.getMembers(simpleType);
710 if (isArray(param)) { // An array
711 println("for(int i = 0; i < " + getSimpleIdentifier(param) + ".length; i++) {");
712 for (int i = 0; i < members.size(); i++) {
713 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
714 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
715 print("paramObj[pos++] = " + getSimpleIdentifier(param) + "[i].");
716 print(getSimpleIdentifier(members.get(i)));
720 } else if (isList(paramType)) { // A list
721 println("for(int i = 0; i < " + getSimpleIdentifier(param) + ".size(); i++) {");
722 for (int i = 0; i < members.size(); i++) {
723 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
724 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
725 print("paramObj[pos++] = " + getSimpleIdentifier(param) + ".get(i).");
726 print(getSimpleIdentifier(members.get(i)));
730 } else { // Just one struct element
731 for (int i = 0; i < members.size(); i++) {
732 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
733 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
734 print("paramObj[pos++] = " + getSimpleIdentifier(param) + ".");
735 print(getSimpleIdentifier(members.get(i)));
743 * HELPER: writeStructParamClassJavaStub() writes parameters if struct is present
745 private void writeStructParamClassJavaStub(List<String> methParams, List<String> methPrmTypes, String callbackType) {
747 print("int paramLen = ");
748 writeLengthStructParamClassJavaStub(methParams, methPrmTypes);
750 println("Object[] paramObj = new Object[paramLen];");
751 println("Class<?>[] paramCls = new Class<?>[paramLen];");
752 println("int pos = 0;");
753 // Iterate again over the parameters
754 for (int i = 0; i < methParams.size(); i++) {
755 String paramType = methPrmTypes.get(i);
756 String param = methParams.get(i);
757 String simpleType = getGenericType(paramType);
758 if (isStructClass(simpleType)) {
759 writeStructMembersJavaStub(simpleType, paramType, param);
760 } else if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
761 println("paramCls[pos] = int.class;");
762 print("paramObj[pos++] = ");
763 if (isArray(methParams.get(i)))
764 print(getSimpleIdentifier(methParams.get(i)) + ".length");
765 else if (isList(methPrmTypes.get(i)))
766 print(getSimpleIdentifier(methParams.get(i)) + ".size()");
768 print("new Integer(1)");
771 String prmType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
772 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
773 print("paramObj[pos++] = ");
774 print(getEnumParam(methPrmTypes.get(i), getSimpleIdentifier(methParams.get(i)), i));
783 * HELPER: writeStructRetMembersJavaStub() writes parameters of struct for return statement
785 private void writeStructRetMembersJavaStub(String simpleType, String retType) {
787 // Get the struct declaration for this struct and generate initialization code
788 StructDecl structDecl = getStructDecl(simpleType);
789 List<String> memTypes = structDecl.getMemberTypes(simpleType);
790 List<String> members = structDecl.getMembers(simpleType);
791 if (isArrayOrList(retType, retType)) { // An array or list
792 println("for(int i = 0; i < retLen; i++) {");
794 if (isArray(retType)) { // An array
795 for (int i = 0; i < members.size(); i++) {
796 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
797 print("structRet[i]." + getSimpleIdentifier(members.get(i)));
798 println(" = (" + getSimpleType(getEnumType(prmType)) + ") retObj[retObjPos++];");
801 } else if (isList(retType)) { // A list
802 println(simpleType + " structRetMem = new " + simpleType + "();");
803 for (int i = 0; i < members.size(); i++) {
804 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
805 print("structRetMem." + getSimpleIdentifier(members.get(i)));
806 println(" = (" + getSimpleType(getEnumType(prmType)) + ") retObj[retObjPos++];");
808 println("structRet.add(structRetMem);");
810 } else { // Just one struct element
811 for (int i = 0; i < members.size(); i++) {
812 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
813 print("structRet." + getSimpleIdentifier(members.get(i)));
814 println(" = (" + getSimpleType(getEnumType(prmType)) + ") retObj[retObjPos++];");
817 println("return structRet;");
822 * HELPER: writeStructReturnJavaStub() writes parameters if struct is present for return statement
824 private void writeStructReturnJavaStub(String simpleType, String retType) {
826 // Handle the returned struct!!!
827 println("Object retLenObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
828 // Minimum retLen is 1 if this is a single struct object
829 println("int retLen = (int) retLenObj;");
830 int numMem = getNumOfMembers(simpleType);
831 println("Class<?>[] retCls = new Class<?>[" + numMem + "*retLen];");
832 println("Class<?>[] retClsVal = new Class<?>[" + numMem + "*retLen];");
833 println("int retPos = 0;");
834 // Get the struct declaration for this struct and generate initialization code
835 StructDecl structDecl = getStructDecl(simpleType);
836 List<String> memTypes = structDecl.getMemberTypes(simpleType);
837 List<String> members = structDecl.getMembers(simpleType);
838 if (isArrayOrList(retType, retType)) { // An array or list
839 println("for(int i = 0; i < retLen; i++) {");
840 for (int i = 0; i < members.size(); i++) {
841 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
842 println("retCls[retPos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
843 println("retClsVal[retPos++] = null;");
846 } else { // Just one struct element
847 for (int i = 0; i < members.size(); i++) {
848 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
849 println("retCls[retPos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
850 println("retClsVal[retPos++] = null;");
853 println("Object[] retObj = rmiCall.getStructObjects(retCls, retClsVal);");
854 if (isArray(retType)) { // An array
855 println(simpleType + "[] structRet = new " + simpleType + "[retLen];");
856 println("for(int i = 0; i < retLen; i++) {");
857 println("structRet[i] = new " + simpleType + "();");
859 } else if (isList(retType)) { // A list
860 println("List<" + simpleType + "> structRet = new ArrayList<" + simpleType + ">();");
862 println(simpleType + " structRet = new " + simpleType + "();");
863 println("int retObjPos = 0;");
864 writeStructRetMembersJavaStub(simpleType, retType);
869 * HELPER: writeStdMethodBodyJavaStub() writes the standard method body in the stub class
871 private void writeStdMethodBodyJavaStub(InterfaceDecl intDecl, List<String> methParams,
872 List<String> methPrmTypes, String method, String callbackType) {
874 checkAndWriteStructSetupJavaStub(methParams, methPrmTypes, intDecl, method);
875 println("int methodId = " + intDecl.getMethodNumId(method) + ";");
876 String retType = intDecl.getMethodType(method);
877 println("Class<?> retType = " + getSimpleType(getStructType(getEnumType(retType))) + ".class;");
878 checkAndWriteEnumTypeJavaStub(methParams, methPrmTypes);
879 // Generate array of parameter types
880 if (isStructPresent(methParams, methPrmTypes)) {
881 writeStructParamClassJavaStub(methParams, methPrmTypes, callbackType);
883 print("Class<?>[] paramCls = new Class<?>[] { ");
884 for (int i = 0; i < methParams.size(); i++) {
885 String prmType = methPrmTypes.get(i);
886 if (checkCallbackType(prmType, callbackType)) { // Check if this has callback object
888 } else { // Generate normal classes if it's not a callback object
889 String paramType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
890 print(getSimpleType(getEnumType(paramType)) + ".class");
892 // Check if this is the last element (don't print a comma)
893 if (i != methParams.size() - 1) {
898 // Generate array of parameter objects
899 print("Object[] paramObj = new Object[] { ");
900 for (int i = 0; i < methParams.size(); i++) {
901 String paramType = methPrmTypes.get(i);
902 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
903 //if (isArray(methPrmTypes.get(i), methParams.get(i)))
904 if (isArray(methParams.get(i)))
905 print(getSimpleIdentifier(methParams.get(i)) + ".length");
906 else if (isList(methPrmTypes.get(i)))
907 print(getSimpleIdentifier(methParams.get(i)) + ".size()");
909 print("new Integer(1)");
911 print(getEnumParam(methPrmTypes.get(i), getSimpleIdentifier(methParams.get(i)), i));
912 // Check if this is the last element (don't print a comma)
913 if (i != methParams.size() - 1) {
919 // Check if this is "void"
920 if (retType.equals("void")) {
921 println("rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
922 } else { // We do have a return value
923 // Generate array of parameter types
924 if (isStructClass(getGenericType(getSimpleArrayType(retType)))) {
925 writeStructReturnJavaStub(getGenericType(getSimpleArrayType(retType)), retType);
927 // This is an enum type
928 if (getParamCategory(getGenericType(getSimpleArrayType(retType))) == ParamCategory.ENUM) {
929 println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
930 checkAndWriteEnumRetTypeJavaStub(retType);
931 } else if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES) {
932 // Check if the return value NONPRIMITIVES
933 String retGenValType = getGenericType(retType);
934 println("Class<?> retGenValType = " + retGenValType + ".class;");
935 println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, retGenValType, paramCls, paramObj);");
936 println("return (" + retType + ")retObj;");
938 println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
939 println("return (" + retType + ")retObj;");
947 * HELPER: returnGenericCallbackType() returns the callback type
949 private String returnGenericCallbackType(String paramType) {
951 if (getParamCategory(paramType) == ParamCategory.NONPRIMITIVES)
952 return getGenericType(paramType);
959 * HELPER: checkCallbackType() checks the callback type
961 private boolean checkCallbackType(String paramType, String callbackType) {
963 String prmType = returnGenericCallbackType(paramType);
964 if (callbackType == null) // If there is no callbackType it means not a callback method
967 return callbackType.equals(prmType);
972 * HELPER: writeCallbackMethodBodyJavaStub() writes the callback method of the stub class
974 private void writeCallbackMethodBodyJavaStub(InterfaceDecl intDecl, List<String> methParams,
975 List<String> methPrmTypes, String method, String callbackType) {
978 // Check if this is single object, array, or list of objects
979 for (int i = 0; i < methParams.size(); i++) {
980 String paramType = methPrmTypes.get(i);
981 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
982 String param = methParams.get(i);
983 if (isArrayOrList(paramType, param)) { // Generate loop
984 println("for (" + getGenericType(paramType) + " cb : " + getSimpleIdentifier(param) + ") {");
985 println(callbackType + "_CallbackSkeleton skel" + i + " = new " + callbackType + "_CallbackSkeleton(cb, objIdCnt++);");
987 println(callbackType + "_CallbackSkeleton skel" + i + " = new " + callbackType + "_CallbackSkeleton(" +
988 getSimpleIdentifier(param) + ", objIdCnt++);");
989 println("listCallbackObj.add(skel" + i + ");");
990 if (isArrayOrList(paramType, param))
995 println(" catch (Exception ex) {");
996 println("ex.printStackTrace();");
997 println("throw new Error(\"Exception when generating skeleton objects!\");");
1002 /* private void writeCallbackMethodBodyJavaStub(InterfaceDecl intDecl, List<String> methParams,
1003 List<String> methPrmTypes, String method, String callbackType) {
1006 // Check if this is single object, array, or list of objects
1007 for (int i = 0; i < methParams.size(); i++) {
1008 String paramType = methPrmTypes.get(i);
1009 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
1010 String param = methParams.get(i);
1011 if (isArrayOrList(paramType, param)) { // Generate loop
1012 println("for (" + getGenericType(paramType) + " cb : " + getSimpleIdentifier(param) + ") {");
1013 println(callbackType + "_CallbackSkeleton skel" + i + " = new " + callbackType + "_CallbackSkeleton(cb, objIdCnt++);");
1015 println(callbackType + "_CallbackSkeleton skel" + i + " = new " + callbackType + "_CallbackSkeleton(" +
1016 getSimpleIdentifier(param) + ", objIdCnt++);");
1017 println("listCallbackObj.add(skel" + i + ");");
1018 if (isArrayOrList(paramType, param))
1023 println(" catch (Exception ex) {");
1024 println("ex.printStackTrace();");
1025 println("throw new Error(\"Exception when generating skeleton objects!\");");
1027 println("int methodId = " + intDecl.getMethodNumId(method) + ";");
1028 String retType = intDecl.getMethodType(method);
1029 println("Class<?> retType = " + getSimpleType(getEnumType(retType)) + ".class;");
1030 // Generate array of parameter types
1031 print("Class<?>[] paramCls = new Class<?>[] { ");
1032 for (int i = 0; i < methParams.size(); i++) {
1033 String paramType = methPrmTypes.get(i);
1034 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
1036 } else { // Generate normal classes if it's not a callback object
1037 String prmType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
1038 print(getSimpleType(prmType) + ".class");
1040 if (i != methParams.size() - 1) // Check if this is the last element
1044 // Generate array of parameter objects
1045 print("Object[] paramObj = new Object[] { ");
1046 for (int i = 0; i < methParams.size(); i++) {
1047 String paramType = methPrmTypes.get(i);
1048 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
1049 //if (isArray(methPrmTypes.get(i), methParams.get(i)))
1050 if (isArray(methParams.get(i)))
1051 print(getSimpleIdentifier(methParams.get(i)) + ".length");
1052 else if (isList(methPrmTypes.get(i)))
1053 print(getSimpleIdentifier(methParams.get(i)) + ".size()");
1055 print("new Integer(1)");
1057 print(getSimpleIdentifier(methParams.get(i)));
1058 if (i != methParams.size() - 1)
1062 // Check if this is "void"
1063 if (retType.equals("void")) {
1064 println("rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
1065 } else { // We do have a return value
1066 // Check if the return value NONPRIMITIVES
1067 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES) {
1068 String[] retGenValType = getTypeOfGeneric(retType);
1069 println("Class<?> retGenValType = " + retGenValType[0] + ".class;");
1070 println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, retGenValType, paramCls, paramObj);");
1071 println("return (" + retType + ")retObj;");
1073 println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
1074 println("return (" + retType + ")retObj;");
1081 * HELPER: writeMethodJavaStub() writes the methods of the stub class
1083 private void writeMethodJavaStub(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
1085 boolean isDefined = false;
1086 for (String method : methods) {
1088 List<String> methParams = intDecl.getMethodParams(method);
1089 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1090 print("public " + intDecl.getMethodType(method) + " " +
1091 intDecl.getMethodId(method) + "(");
1092 boolean isCallbackMethod = false;
1093 String callbackType = null;
1094 for (int i = 0; i < methParams.size(); i++) {
1096 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
1097 // Check if this has callback object
1098 if (callbackClasses.contains(paramType)) {
1099 isCallbackMethod = true;
1100 callbackType = paramType;
1101 // Even if there're 2 callback arguments, we expect them to be of the same interface
1103 print(methPrmTypes.get(i) + " " + methParams.get(i));
1104 // Check if this is the last element (don't print a comma)
1105 if (i != methParams.size() - 1) {
1110 // Now, write the body of stub!
1111 if (isCallbackMethod)
1112 writeCallbackMethodBodyJavaStub(intDecl, methParams, methPrmTypes, method, callbackType);
1114 writeStdMethodBodyJavaStub(intDecl, methParams, methPrmTypes, method, callbackType);
1116 // Write the init callback helper method
1117 if (isCallbackMethod && !isDefined) {
1118 writeInitCallbackJavaStub(callbackType, intDecl);
1126 * generateJavaStubClasses() generate stubs based on the methods list in Java
1128 public void generateJavaStubClasses() throws IOException {
1130 // Create a new directory
1131 String path = createDirectories(dir, subdir);
1132 for (String intface : mapIntfacePTH.keySet()) {
1134 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
1135 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
1137 // Open a new file to write into
1138 String newIntface = intMeth.getKey();
1139 String newStubClass = newIntface + "_Stub";
1140 FileWriter fw = new FileWriter(path + "/" + newStubClass + ".java");
1141 pw = new PrintWriter(new BufferedWriter(fw));
1142 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
1143 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
1144 // Pass in set of methods and get import classes
1145 Set<String> methods = intMeth.getValue();
1146 Set<String> importClasses = getImportClasses(methods, intDecl);
1147 List<String> stdImportClasses = getStandardJavaImportClasses();
1148 List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
1149 printImportStatements(allImportClasses); println("");
1150 // Find out if there are callback objects
1151 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
1152 boolean callbackExist = !callbackClasses.isEmpty();
1153 // Write class header
1154 println("public class " + newStubClass + " implements " + newIntface + " {\n");
1156 writePropertiesJavaStub(intface, newIntface, callbackExist, callbackClasses);
1157 // Write constructor
1158 writeConstructorJavaStub(intface, newStubClass, callbackExist, callbackClasses);
1160 writeMethodJavaStub(intMeth.getValue(), intDecl, callbackClasses);
1163 System.out.println("IoTCompiler: Generated stub class " + newStubClass + ".java...");
1170 * HELPER: writePropertiesJavaCallbackStub() writes the properties of the callback stub class
1172 private void writePropertiesJavaCallbackStub(String intface, String newIntface, boolean callbackExist, Set<String> callbackClasses) {
1174 println("private IoTRMICall rmiCall;");
1175 println("private String address;");
1176 println("private int[] ports;\n");
1177 // Get the object Id
1178 println("private int objectId = 0;");
1179 if (callbackExist) {
1180 // We assume that each class only has one callback interface for now
1181 Iterator it = callbackClasses.iterator();
1182 String callbackType = (String) it.next();
1183 println("// Callback properties");
1184 println("private IoTRMIObject rmiObj;");
1185 println("List<" + callbackType + "> listCallbackObj;");
1186 println("private static int objIdCnt = 0;");
1187 // Generate permission stuff for callback stubs
1188 DeclarationHandler decHandler = mapIntDeclHand.get(callbackType);
1189 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(callbackType);
1190 writePropertiesJavaPermission(callbackType, intDecl);
1197 * HELPER: writeConstructorJavaCallbackStub() writes the constructor of the callback stub class
1199 private void writeConstructorJavaCallbackStub(String intface, String newStubClass, boolean callbackExist, Set<String> callbackClasses) {
1201 // TODO: If we want callback in callback, then we need to add address and port initializations
1202 println("public " + newStubClass + "(IoTRMICall _rmiCall, int _objectId) throws Exception {");
1203 println("objectId = _objectId;");
1204 println("rmiCall = _rmiCall;");
1205 if (callbackExist) {
1206 Iterator it = callbackClasses.iterator();
1207 String callbackType = (String) it.next();
1208 writeConstructorJavaPermission(intface);
1209 println("listCallbackObj = new ArrayList<" + callbackType + ">();");
1210 println("___initCallBack();");
1211 println("// TODO: Add address and port initialization here if we want callback in callback!");
1218 * generateJavaCallbackStubClasses() generate callback stubs based on the methods list in Java
1220 * Callback stubs gets the IoTRMICall objects from outside of the class as contructor input
1221 * because all these stubs are populated by the class that takes in this object as a callback
1222 * object. In such a class, we only use one socket, hence one IoTRMICall, for all callback objects.
1224 public void generateJavaCallbackStubClasses() throws IOException {
1226 // Create a new directory
1227 String path = createDirectories(dir, subdir);
1228 for (String intface : mapIntfacePTH.keySet()) {
1230 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
1231 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
1233 // Open a new file to write into
1234 String newIntface = intMeth.getKey();
1235 String newStubClass = newIntface + "_CallbackStub";
1236 FileWriter fw = new FileWriter(path + "/" + newStubClass + ".java");
1237 pw = new PrintWriter(new BufferedWriter(fw));
1238 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
1239 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
1240 // Pass in set of methods and get import classes
1241 Set<String> methods = intMeth.getValue();
1242 Set<String> importClasses = getImportClasses(methods, intDecl);
1243 List<String> stdImportClasses = getStandardJavaImportClasses();
1244 List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
1245 printImportStatements(allImportClasses); println("");
1246 // Find out if there are callback objects
1247 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
1248 boolean callbackExist = !callbackClasses.isEmpty();
1249 // Write class header
1250 println("public class " + newStubClass + " implements " + newIntface + " {\n");
1252 writePropertiesJavaCallbackStub(intface, newIntface, callbackExist, callbackClasses);
1253 // Write constructor
1254 writeConstructorJavaCallbackStub(intface, newStubClass, callbackExist, callbackClasses);
1256 // TODO: perhaps need to generate callback for callback
1257 writeMethodJavaStub(intMeth.getValue(), intDecl, callbackClasses);
1260 System.out.println("IoTCompiler: Generated callback stub class " + newStubClass + ".java...");
1267 * HELPER: writePropertiesJavaSkeleton() writes the properties of the skeleton class
1269 private void writePropertiesJavaSkeleton(String intface, boolean callbackExist, InterfaceDecl intDecl) {
1271 println("private " + intface + " mainObj;");
1272 //println("private int ports;");
1273 println("private IoTRMIObject rmiObj;\n");
1275 if (callbackExist) {
1276 println("private static int objIdCnt = 0;");
1277 println("private IoTRMICall rmiCall;");
1279 writePropertiesJavaPermission(intface, intDecl);
1285 * HELPER: writeStructPermissionJavaSkeleton() writes permission for struct helper
1287 private void writeStructPermissionJavaSkeleton(Collection<String> methods, InterfaceDecl intDecl, String intface) {
1289 // Use this set to handle two same methodIds
1290 for (String method : methods) {
1291 List<String> methParams = intDecl.getMethodParams(method);
1292 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1293 // Check for params with structs
1294 for (int i = 0; i < methParams.size(); i++) {
1295 String paramType = methPrmTypes.get(i);
1296 String param = methParams.get(i);
1297 String simpleType = getGenericType(paramType);
1298 if (isStructClass(simpleType)) {
1299 int methodNumId = intDecl.getMethodNumId(method);
1300 String helperMethod = methodNumId + "struct" + i;
1301 int methodHelperNumId = intDecl.getHelperMethodNumId(helperMethod);
1302 // Iterate over interfaces to give permissions to
1303 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
1304 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
1305 String newIntface = intMeth.getKey();
1306 int newObjectId = getNewIntfaceObjectId(newIntface);
1307 println("set" + newObjectId + "Allowed.add(" + methodHelperNumId + ");");
1316 * HELPER: writeConstructorJavaSkeleton() writes the constructor of the skeleton class
1318 private void writeConstructorJavaSkeleton(String newSkelClass, String intface, InterfaceDecl intDecl, Collection<String> methods, boolean callbackExist) {
1320 println("public " + newSkelClass + "(" + intface + " _mainObj, int _port) throws Exception {");
1321 println("mainObj = _mainObj;");
1322 println("rmiObj = new IoTRMIObject(_port);");
1323 // Generate permission control initialization
1324 writeConstructorJavaPermission(intface);
1325 writeJavaInitCallbackPermission(intface, intDecl, callbackExist);
1326 writeStructPermissionJavaSkeleton(methods, intDecl, intface);
1327 println("___waitRequestInvokeMethod();");
1333 * HELPER: writeStdMethodBodyJavaSkeleton() writes the standard method body in the skeleton class
1335 private void writeStdMethodBodyJavaSkeleton(List<String> methParams, String methodId, String methodType) {
1337 if (methodType.equals("void"))
1338 print("mainObj." + methodId + "(");
1340 print("return mainObj." + methodId + "(");
1341 for (int i = 0; i < methParams.size(); i++) {
1343 print(getSimpleIdentifier(methParams.get(i)));
1344 // Check if this is the last element (don't print a comma)
1345 if (i != methParams.size() - 1) {
1354 * HELPER: writeInitCallbackJavaSkeleton() writes the init callback method for skeleton class
1356 private void writeInitCallbackJavaSkeleton(boolean callbackSkeleton) {
1358 // This is a callback skeleton generation
1359 if (callbackSkeleton)
1360 println("public void ___regCB(IoTRMIObject rmiObj) throws IOException {");
1362 println("public void ___regCB() throws IOException {");
1363 print("Object[] paramObj = rmiObj.getMethodParams(new Class<?>[] { int.class, String.class, int.class },");
1364 println("new Class<?>[] { null, null, null });");
1365 println("rmiCall = new IoTRMICall((int) paramObj[0], (String) paramObj[1], (int) paramObj[2]);");
1371 * HELPER: writeMethodJavaSkeleton() writes the method of the skeleton class
1373 private void writeMethodJavaSkeleton(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses,
1374 boolean callbackSkeleton) {
1376 boolean isDefined = false;
1377 for (String method : methods) {
1379 List<String> methParams = intDecl.getMethodParams(method);
1380 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1381 String methodId = intDecl.getMethodId(method);
1382 print("public " + intDecl.getMethodType(method) + " " + methodId + "(");
1383 boolean isCallbackMethod = false;
1384 String callbackType = null;
1385 for (int i = 0; i < methParams.size(); i++) {
1387 String origParamType = methPrmTypes.get(i);
1388 String paramType = checkAndGetParamClass(origParamType);
1389 if (callbackClasses.contains(origParamType)) { // Check if this has callback object
1390 isCallbackMethod = true;
1391 callbackType = origParamType;
1393 print(paramType + " " + methParams.get(i));
1394 // Check if this is the last element (don't print a comma)
1395 if (i != methParams.size() - 1) {
1400 // Now, write the body of skeleton!
1401 writeStdMethodBodyJavaSkeleton(methParams, methodId, intDecl.getMethodType(method));
1403 if (isCallbackMethod && !isDefined) { // Make sure that this function is only defined once!
1404 writeInitCallbackJavaSkeleton(callbackSkeleton);
1412 * HELPER: writeCallbackJavaStubGeneration() writes the callback stub generation part
1414 private Map<Integer,String> writeCallbackJavaStubGeneration(List<String> methParams, List<String> methPrmTypes,
1415 String callbackType, boolean isStructMethod) {
1417 Map<Integer,String> mapStubParam = new HashMap<Integer,String>();
1418 String offsetPfx = "";
1420 offsetPfx = "offset";
1421 // Iterate over callback objects
1422 for (int i = 0; i < methParams.size(); i++) {
1423 String paramType = methPrmTypes.get(i);
1424 String param = methParams.get(i);
1425 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
1426 String exchParamType = checkAndGetParamClass(getGenericType(paramType));
1427 // Print array if this is array or list if this is a list of callback objects
1428 if (isArray(param)) {
1429 println("int numStubs" + i + " = (int) paramObj[" + offsetPfx + i + "];");
1430 println(exchParamType + "[] stub" + i + " = new " + exchParamType + "[numStubs" + i + "];");
1431 } else if (isList(paramType)) {
1432 println("int numStubs" + i + " = (int) paramObj[" + offsetPfx + i + "];");
1433 println("List<" + exchParamType + "> stub" + i + " = new ArrayList<" + exchParamType + ">();");
1435 println(exchParamType + " stub" + i + " = new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt);");
1436 println("objIdCnt++;");
1439 // Generate a loop if needed
1440 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
1441 String exchParamType = checkAndGetParamClass(getGenericType(paramType));
1442 if (isArray(param)) {
1443 println("for (int objId = 0; objId < numStubs" + i + "; objId++) {");
1444 println("stub" + i + "[objId] = new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt);");
1445 println("objIdCnt++;");
1447 } else if (isList(paramType)) {
1448 println("for (int objId = 0; objId < numStubs" + i + "; objId++) {");
1449 println("stub" + i + ".add(new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt));");
1450 println("objIdCnt++;");
1453 mapStubParam.put(i, "stub" + i); // List of all stub parameters
1456 return mapStubParam;
1461 * HELPER: checkAndWriteEnumTypeJavaSkeleton() writes the enum type (convert from enum to int)
1463 private void checkAndWriteEnumTypeJavaSkeleton(List<String> methParams, List<String> methPrmTypes, boolean isStructMethod) {
1465 String offsetPfx = "";
1467 offsetPfx = "offset";
1468 // Iterate and find enum declarations
1469 boolean printed = false;
1470 for (int i = 0; i < methParams.size(); i++) {
1471 String paramType = methPrmTypes.get(i);
1472 String param = methParams.get(i);
1473 String simpleType = getGenericType(paramType);
1474 if (isEnumClass(simpleType)) {
1475 // Check if this is enum type
1476 println("int paramInt" + i + "[] = (int[]) paramObj[" + offsetPfx + i + "];");
1478 println(simpleType + "[] enumVals = " + simpleType + ".values();");
1481 if (isArray(param)) { // An array
1482 println("int len" + i + " = paramInt" + i + ".length;");
1483 println(simpleType + "[] paramEnum" + i + " = new " + simpleType + "[len" + i + "];");
1484 println("for (int i = 0; i < len" + i + "; i++) {");
1485 println("paramEnum" + i + "[i] = enumVals[paramInt" + i + "[i]];");
1487 } else if (isList(paramType)) { // A list
1488 println("int len" + i + " = paramInt" + i + ".length;");
1489 println("List<" + simpleType + "> paramEnum" + i + " = new ArrayList<" + simpleType + ">();");
1490 println("for (int i = 0; i < len" + i + "; i++) {");
1491 println("paramEnum" + i + ".add(enumVals[paramInt" + i + "[i]]);");
1493 } else { // Just one element
1494 println(simpleType + " paramEnum" + i + " = enumVals[paramInt" + i + "[0]];");
1502 * HELPER: checkAndWriteEnumRetTypeJavaSkeleton() writes the enum return type (convert from enum to int)
1504 private void checkAndWriteEnumRetTypeJavaSkeleton(String retType, String methodId) {
1506 // Strips off array "[]" for return type
1507 String pureType = getSimpleArrayType(getGenericType(retType));
1508 // Take the inner type of generic
1509 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
1510 pureType = getGenericType(retType);
1511 if (isEnumClass(pureType)) {
1512 // Check if this is enum type
1514 if (isArray(retType)) { // An array
1515 print(pureType + "[] retEnum = " + methodId + "(");
1516 } else if (isList(retType)) { // A list
1517 print("List<" + pureType + "> retEnum = " + methodId + "(");
1518 } else { // Just one element
1519 print(pureType + " retEnum = " + methodId + "(");
1526 * HELPER: checkAndWriteEnumRetConvJavaSkeleton() writes the enum return type (convert from enum to int)
1528 private void checkAndWriteEnumRetConvJavaSkeleton(String retType) {
1530 // Strips off array "[]" for return type
1531 String pureType = getSimpleArrayType(getGenericType(retType));
1532 // Take the inner type of generic
1533 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
1534 pureType = getGenericType(retType);
1535 if (isEnumClass(pureType)) {
1536 // Check if this is enum type
1537 if (isArray(retType)) { // An array
1538 println("int retLen = retEnum.length;");
1539 println("int[] retEnumVal = new int[retLen];");
1540 println("for (int i = 0; i < retLen; i++) {");
1541 println("retEnumVal[i] = retEnum[i].ordinal();");
1543 } else if (isList(retType)) { // A list
1544 println("int retLen = retEnum.size();");
1545 println("int[] retEnumVal = new int[retLen];");
1546 println("for (int i = 0; i < retLen; i++) {");
1547 println("retEnumVal[i] = retEnum.get(i).ordinal();");
1549 } else { // Just one element
1550 println("int[] retEnumVal = new int[1];");
1551 println("retEnumVal[0] = retEnum.ordinal();");
1553 println("Object retObj = retEnumVal;");
1559 * HELPER: writeLengthStructParamClassSkeleton() writes lengths of params
1561 private void writeLengthStructParamClassSkeleton(List<String> methParams, List<String> methPrmTypes,
1562 String method, InterfaceDecl intDecl) {
1564 // Iterate and find struct declarations - count number of params
1565 for (int i = 0; i < methParams.size(); i++) {
1566 String paramType = methPrmTypes.get(i);
1567 String param = methParams.get(i);
1568 String simpleType = getGenericType(paramType);
1569 if (isStructClass(simpleType)) {
1570 int members = getNumOfMembers(simpleType);
1571 print(Integer.toString(members) + "*");
1572 int methodNumId = intDecl.getMethodNumId(method);
1573 print("struct" + methodNumId + "Size" + i);
1576 if (i != methParams.size() - 1) {
1584 * HELPER: writeStructMembersJavaSkeleton() writes member parameters of struct
1586 private void writeStructMembersJavaSkeleton(String simpleType, String paramType,
1587 String param, String method, InterfaceDecl intDecl, int iVar) {
1589 // Get the struct declaration for this struct and generate initialization code
1590 StructDecl structDecl = getStructDecl(simpleType);
1591 List<String> memTypes = structDecl.getMemberTypes(simpleType);
1592 List<String> members = structDecl.getMembers(simpleType);
1593 if (isArrayOrList(paramType, param)) { // An array or list
1594 int methodNumId = intDecl.getMethodNumId(method);
1595 String counter = "struct" + methodNumId + "Size" + iVar;
1596 println("for(int i = 0; i < " + counter + "; i++) {");
1598 if (isArrayOrList(paramType, param)) { // An array or list
1599 for (int i = 0; i < members.size(); i++) {
1600 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
1601 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
1602 println("paramClsGen[pos++] = null;");
1605 } else { // Just one struct element
1606 for (int i = 0; i < members.size(); i++) {
1607 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
1608 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
1609 println("paramClsGen[pos++] = null;");
1616 * HELPER: writeStructMembersInitJavaSkeleton() writes member parameters initialization of struct
1618 private void writeStructMembersInitJavaSkeleton(InterfaceDecl intDecl, List<String> methParams,
1619 List<String> methPrmTypes, String method) {
1621 println("int objPos = 0;");
1622 for (int i = 0; i < methParams.size(); i++) {
1623 String paramType = methPrmTypes.get(i);
1624 String param = methParams.get(i);
1625 String simpleType = getGenericType(paramType);
1626 if (isStructClass(simpleType)) {
1627 int methodNumId = intDecl.getMethodNumId(method);
1628 String counter = "struct" + methodNumId + "Size" + i;
1630 if (isArray(param)) { // An array
1631 println(simpleType + "[] paramStruct" + i + " = new " + simpleType + "[" + counter + "];");
1632 println("for(int i = 0; i < " + counter + "; i++) {");
1633 println("paramStruct" + i + "[i] = new " + simpleType + "();");
1635 } else if (isList(paramType)) { // A list
1636 println("List<" + simpleType + "> paramStruct" + i + " = new ArrayList<" + simpleType + ">();");
1638 println(simpleType + " paramStruct" + i + " = new " + simpleType + "();");
1639 // Initialize members
1640 StructDecl structDecl = getStructDecl(simpleType);
1641 List<String> members = structDecl.getMembers(simpleType);
1642 List<String> memTypes = structDecl.getMemberTypes(simpleType);
1643 if (isArrayOrList(paramType, param)) { // An array or list
1644 println("for(int i = 0; i < " + counter + "; i++) {");
1646 if (isArray(param)) { // An array
1647 for (int j = 0; j < members.size(); j++) {
1648 String prmType = checkAndGetArray(memTypes.get(j), members.get(j));
1649 print("paramStruct" + i + "[i]." + getSimpleIdentifier(members.get(j)));
1650 println(" = (" + getSimpleType(getEnumType(prmType)) + ") paramObj[objPos++];");
1653 } else if (isList(paramType)) { // A list
1654 println(simpleType + " paramStructMem = new " + simpleType + "();");
1655 for (int j = 0; j < members.size(); j++) {
1656 String prmType = checkAndGetArray(memTypes.get(j), members.get(j));
1657 print("paramStructMem." + getSimpleIdentifier(members.get(j)));
1658 println(" = (" + getSimpleType(getEnumType(prmType)) + ") paramObj[objPos++];");
1660 println("paramStruct" + i + ".add(paramStructMem);");
1662 } else { // Just one struct element
1663 for (int j = 0; j < members.size(); j++) {
1664 String prmType = checkAndGetArray(memTypes.get(j), members.get(j));
1665 print("paramStruct" + i + "." + getSimpleIdentifier(members.get(j)));
1666 println(" = (" + getSimpleType(getEnumType(prmType)) + ") paramObj[objPos++];");
1670 // Take offsets of parameters
1671 println("int offset" + i +" = objPos++;");
1678 * HELPER: writeStructReturnJavaSkeleton() writes struct for return statement
1680 private void writeStructReturnJavaSkeleton(String simpleType, String retType) {
1682 // Minimum retLen is 1 if this is a single struct object
1683 if (isArray(retType))
1684 println("int retLen = retStruct.length;");
1685 else if (isList(retType))
1686 println("int retLen = retStruct.size();");
1687 else // Just single struct object
1688 println("int retLen = 1;");
1689 println("Object retLenObj = retLen;");
1690 println("rmiObj.sendReturnObj(retLenObj);");
1691 int numMem = getNumOfMembers(simpleType);
1692 println("Class<?>[] retCls = new Class<?>[" + numMem + "*retLen];");
1693 println("Object[] retObj = new Object[" + numMem + "*retLen];");
1694 println("int retPos = 0;");
1695 // Get the struct declaration for this struct and generate initialization code
1696 StructDecl structDecl = getStructDecl(simpleType);
1697 List<String> memTypes = structDecl.getMemberTypes(simpleType);
1698 List<String> members = structDecl.getMembers(simpleType);
1699 if (isArray(retType)) { // An array or list
1700 println("for(int i = 0; i < retLen; i++) {");
1701 for (int i = 0; i < members.size(); i++) {
1702 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
1703 println("retCls[retPos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
1704 print("retObj[retPos++] = retStruct[i].");
1705 print(getEnumParam(memTypes.get(i), getSimpleIdentifier(members.get(i)), i));
1709 } else if (isList(retType)) { // An array or list
1710 println("for(int i = 0; i < retLen; i++) {");
1711 for (int i = 0; i < members.size(); i++) {
1712 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
1713 println("retCls[retPos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
1714 print("retObj[retPos++] = retStruct.get(i).");
1715 print(getEnumParam(memTypes.get(i), getSimpleIdentifier(members.get(i)), i));
1719 } else { // Just one struct element
1720 for (int i = 0; i < members.size(); i++) {
1721 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
1722 println("retCls[retPos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
1723 print("retObj[retPos++] = retStruct.");
1724 print(getEnumParam(memTypes.get(i), getSimpleIdentifier(members.get(i)), i));
1733 * HELPER: writeMethodHelperReturnJavaSkeleton() writes return statement part in skeleton
1735 private void writeMethodHelperReturnJavaSkeleton(InterfaceDecl intDecl, List<String> methParams,
1736 List<String> methPrmTypes, String method, boolean isCallbackMethod, String callbackType,
1737 boolean isStructMethod) {
1739 checkAndWriteEnumTypeJavaSkeleton(methParams, methPrmTypes, isStructMethod);
1740 Map<Integer,String> mapStubParam = null;
1741 if (isCallbackMethod) {
1743 mapStubParam = writeCallbackJavaStubGeneration(methParams, methPrmTypes, callbackType, isStructMethod);
1745 // Check if this is "void"
1746 String retType = intDecl.getMethodType(method);
1747 if (retType.equals("void")) {
1748 print(intDecl.getMethodId(method) + "(");
1749 } else if (isEnumClass(getSimpleArrayType(getGenericType(retType)))) { // Enum type
1750 checkAndWriteEnumRetTypeJavaSkeleton(retType, intDecl.getMethodId(method));
1751 } else if (isStructClass(getSimpleArrayType(getGenericType(retType)))) { // Struct type
1752 print(retType + " retStruct = " + intDecl.getMethodId(method) + "(");
1753 } else { // We do have a return value
1754 print("Object retObj = " + intDecl.getMethodId(method) + "(");
1756 for (int i = 0; i < methParams.size(); i++) {
1758 String paramType = methPrmTypes.get(i);
1759 if (isCallbackMethod && checkCallbackType(paramType, callbackType)) {
1760 print(mapStubParam.get(i)); // Get the callback parameter
1761 } else if (isEnumClass(getGenericType(paramType))) { // Enum class
1762 print(getEnumParam(paramType, methParams.get(i), i));
1763 } else if (isStructClass(getGenericType(paramType))) {
1764 print("paramStruct" + i);
1766 String prmType = checkAndGetArray(paramType, methParams.get(i));
1768 print("(" + prmType + ") paramObj[offset" + i + "]");
1770 print("(" + prmType + ") paramObj[" + i + "]");
1772 if (i != methParams.size() - 1)
1776 if (!retType.equals("void")) {
1777 if (isEnumClass(getSimpleArrayType(getGenericType(retType)))) { // Enum type
1778 checkAndWriteEnumRetConvJavaSkeleton(retType);
1779 println("rmiObj.sendReturnObj(retObj);");
1780 } else if (isStructClass(getSimpleArrayType(getGenericType(retType)))) { // Struct type
1781 writeStructReturnJavaSkeleton(getSimpleArrayType(getGenericType(retType)), retType);
1782 println("rmiObj.sendReturnObj(retCls, retObj);");
1784 println("rmiObj.sendReturnObj(retObj);");
1786 if (isCallbackMethod) { // Catch exception if this is callback
1788 println(" catch(Exception ex) {");
1789 println("ex.printStackTrace();");
1790 println("throw new Error(\"Exception from callback object instantiation!\");");
1797 * HELPER: writeMethodHelperStructJavaSkeleton() writes the struct in skeleton
1799 private void writeMethodHelperStructJavaSkeleton(InterfaceDecl intDecl, List<String> methParams,
1800 List<String> methPrmTypes, String method, Set<String> callbackClasses) {
1802 // Generate array of parameter objects
1803 boolean isCallbackMethod = false;
1804 String callbackType = null;
1805 print("int paramLen = ");
1806 writeLengthStructParamClassSkeleton(methParams, methPrmTypes, method, intDecl);
1808 println("Class<?>[] paramCls = new Class<?>[paramLen];");
1809 println("Class<?>[] paramClsGen = new Class<?>[paramLen];");
1810 println("int pos = 0;");
1811 // Iterate again over the parameters
1812 for (int i = 0; i < methParams.size(); i++) {
1813 String paramType = methPrmTypes.get(i);
1814 String param = methParams.get(i);
1815 String simpleType = getGenericType(paramType);
1816 if (isStructClass(simpleType)) {
1817 writeStructMembersJavaSkeleton(simpleType, paramType, param, method, intDecl, i);
1819 String prmType = returnGenericCallbackType(methPrmTypes.get(i));
1820 if (callbackClasses.contains(prmType)) {
1821 isCallbackMethod = true;
1822 callbackType = prmType;
1823 println("paramCls[pos] = int.class;");
1824 println("paramClsGen[pos++] = null;");
1825 } else { // Generate normal classes if it's not a callback object
1826 String paramTypeOth = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
1827 println("paramCls[pos] = " + getSimpleType(getEnumType(paramTypeOth)) + ".class;");
1828 print("paramClsGen[pos++] = ");
1829 String prmTypeOth = methPrmTypes.get(i);
1830 if (getParamCategory(prmTypeOth) == ParamCategory.NONPRIMITIVES)
1831 println(getTypeOfGeneric(prmType)[0] + ".class;");
1837 println("Object[] paramObj = rmiObj.getMethodParams(paramCls, paramClsGen);");
1838 writeStructMembersInitJavaSkeleton(intDecl, methParams, methPrmTypes, method);
1839 // Write the return value part
1840 writeMethodHelperReturnJavaSkeleton(intDecl, methParams, methPrmTypes, method, isCallbackMethod, callbackType, true);
1845 * HELPER: writeStdMethodHelperBodyJavaSkeleton() writes the standard method body helper in the skeleton class
1847 private void writeStdMethodHelperBodyJavaSkeleton(InterfaceDecl intDecl, List<String> methParams,
1848 List<String> methPrmTypes, String method, Set<String> callbackClasses) {
1850 // Generate array of parameter objects
1851 boolean isCallbackMethod = false;
1852 String callbackType = null;
1853 print("Object[] paramObj = rmiObj.getMethodParams(new Class<?>[] { ");
1854 for (int i = 0; i < methParams.size(); i++) {
1856 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
1857 if (callbackClasses.contains(paramType)) {
1858 isCallbackMethod = true;
1859 callbackType = paramType;
1861 } else { // Generate normal classes if it's not a callback object
1862 String prmType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
1863 print(getSimpleType(getEnumType(prmType)) + ".class");
1865 if (i != methParams.size() - 1)
1869 // Generate generic class if it's a generic type.. null otherwise
1870 print("new Class<?>[] { ");
1871 for (int i = 0; i < methParams.size(); i++) {
1872 String prmType = methPrmTypes.get(i);
1873 if ((getParamCategory(prmType) == ParamCategory.NONPRIMITIVES) &&
1874 !isEnumClass(getGenericType(prmType)) &&
1875 !callbackClasses.contains(getGenericType(prmType)))
1876 print(getGenericType(prmType) + ".class");
1879 if (i != methParams.size() - 1)
1883 // Write the return value part
1884 writeMethodHelperReturnJavaSkeleton(intDecl, methParams, methPrmTypes, method, isCallbackMethod, callbackType, false);
1889 * HELPER: writeMethodHelperJavaSkeleton() writes the method helper of the skeleton class
1891 private void writeMethodHelperJavaSkeleton(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
1893 // Use this set to handle two same methodIds
1894 Set<String> uniqueMethodIds = new HashSet<String>();
1895 for (String method : methods) {
1897 List<String> methParams = intDecl.getMethodParams(method);
1898 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1899 if (isStructPresent(methParams, methPrmTypes)) { // Treat struct differently
1900 String methodId = intDecl.getMethodId(method);
1901 print("public void ___");
1902 String helperMethod = methodId;
1903 if (uniqueMethodIds.contains(methodId))
1904 helperMethod = helperMethod + intDecl.getMethodNumId(method);
1906 uniqueMethodIds.add(methodId);
1907 String retType = intDecl.getMethodType(method);
1908 print(helperMethod + "(");
1909 boolean begin = true;
1910 for (int i = 0; i < methParams.size(); i++) { // Print size variables
1911 String paramType = methPrmTypes.get(i);
1912 String param = methParams.get(i);
1913 String simpleType = getGenericType(paramType);
1914 if (isStructClass(simpleType)) {
1915 if (!begin) // Generate comma for not the beginning variable
1919 int methodNumId = intDecl.getMethodNumId(method);
1920 print("int struct" + methodNumId + "Size" + i);
1923 // Check if this is "void"
1924 if (retType.equals("void"))
1927 println(") throws IOException {");
1928 writeMethodHelperStructJavaSkeleton(intDecl, methParams, methPrmTypes, method, callbackClasses);
1931 String methodId = intDecl.getMethodId(method);
1932 print("public void ___");
1933 String helperMethod = methodId;
1934 if (uniqueMethodIds.contains(methodId))
1935 helperMethod = helperMethod + intDecl.getMethodNumId(method);
1937 uniqueMethodIds.add(methodId);
1938 // Check if this is "void"
1939 String retType = intDecl.getMethodType(method);
1940 if (retType.equals("void"))
1941 println(helperMethod + "() {");
1943 println(helperMethod + "() throws IOException {");
1944 // Now, write the helper body of skeleton!
1945 writeStdMethodHelperBodyJavaSkeleton(intDecl, methParams, methPrmTypes, method, callbackClasses);
1949 // Write method helper for structs
1950 writeMethodHelperStructSetupJavaSkeleton(methods, intDecl);
1955 * HELPER: writeMethodHelperStructSetupJavaSkeleton() writes the method helper of struct setup in skeleton class
1957 private void writeMethodHelperStructSetupJavaSkeleton(Collection<String> methods,
1958 InterfaceDecl intDecl) {
1960 // Use this set to handle two same methodIds
1961 for (String method : methods) {
1963 List<String> methParams = intDecl.getMethodParams(method);
1964 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1965 // Check for params with structs
1966 for (int i = 0; i < methParams.size(); i++) {
1967 String paramType = methPrmTypes.get(i);
1968 String param = methParams.get(i);
1969 String simpleType = getGenericType(paramType);
1970 if (isStructClass(simpleType)) {
1971 int methodNumId = intDecl.getMethodNumId(method);
1972 print("public int ___");
1973 String helperMethod = methodNumId + "struct" + i;
1974 println(helperMethod + "() {");
1975 // Now, write the helper body of skeleton!
1976 println("Object[] paramObj = rmiObj.getMethodParams(new Class<?>[] { int.class }, new Class<?>[] { null });");
1977 println("return (int) paramObj[0];");
1986 * HELPER: writeMethodHelperStructSetupJavaCallbackSkeleton() writes the method helper of struct setup in callback skeleton class
1988 private void writeMethodHelperStructSetupJavaCallbackSkeleton(Collection<String> methods,
1989 InterfaceDecl intDecl) {
1991 // Use this set to handle two same methodIds
1992 for (String method : methods) {
1994 List<String> methParams = intDecl.getMethodParams(method);
1995 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1996 // Check for params with structs
1997 for (int i = 0; i < methParams.size(); i++) {
1998 String paramType = methPrmTypes.get(i);
1999 String param = methParams.get(i);
2000 String simpleType = getGenericType(paramType);
2001 if (isStructClass(simpleType)) {
2002 int methodNumId = intDecl.getMethodNumId(method);
2003 print("public int ___");
2004 String helperMethod = methodNumId + "struct" + i;
2005 println(helperMethod + "(IoTRMIObject rmiObj) {");
2006 // Now, write the helper body of skeleton!
2007 println("Object[] paramObj = rmiObj.getMethodParams(new Class<?>[] { int.class }, new Class<?>[] { null });");
2008 println("return (int) paramObj[0];");
2017 * HELPER: writeCountVarStructSkeleton() writes counter variable of struct for skeleton
2019 private void writeCountVarStructSkeleton(Collection<String> methods, InterfaceDecl intDecl) {
2021 // Use this set to handle two same methodIds
2022 for (String method : methods) {
2024 List<String> methParams = intDecl.getMethodParams(method);
2025 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2026 // Check for params with structs
2027 for (int i = 0; i < methParams.size(); i++) {
2028 String paramType = methPrmTypes.get(i);
2029 String param = methParams.get(i);
2030 String simpleType = getGenericType(paramType);
2031 if (isStructClass(simpleType)) {
2032 int methodNumId = intDecl.getMethodNumId(method);
2033 println("int struct" + methodNumId + "Size" + i + " = 0;");
2041 * HELPER: writeInputCountVarStructSkeleton() writes input counter variable of struct for skeleton
2043 private boolean writeInputCountVarStructSkeleton(String method, InterfaceDecl intDecl) {
2045 List<String> methParams = intDecl.getMethodParams(method);
2046 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2047 boolean structExist = false;
2048 boolean begin = true;
2049 // Check for params with structs
2050 for (int i = 0; i < methParams.size(); i++) {
2051 String paramType = methPrmTypes.get(i);
2052 String param = methParams.get(i);
2053 String simpleType = getGenericType(paramType);
2054 if (isStructClass(simpleType)) {
2060 int methodNumId = intDecl.getMethodNumId(method);
2061 print("struct" + methodNumId + "Size" + i);
2069 * HELPER: writeMethodCallStructSkeleton() writes method call for wait invoke in skeleton
2071 private void writeMethodCallStructSkeleton(Collection<String> methods, InterfaceDecl intDecl) {
2073 // Use this set to handle two same methodIds
2074 for (String method : methods) {
2076 List<String> methParams = intDecl.getMethodParams(method);
2077 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2078 // Check for params with structs
2079 for (int i = 0; i < methParams.size(); i++) {
2080 String paramType = methPrmTypes.get(i);
2081 String param = methParams.get(i);
2082 String simpleType = getGenericType(paramType);
2083 if (isStructClass(simpleType)) {
2084 int methodNumId = intDecl.getMethodNumId(method);
2086 String helperMethod = methodNumId + "struct" + i;
2087 String tempVar = "struct" + methodNumId + "Size" + i;
2088 print(intDecl.getHelperMethodNumId(helperMethod) + ": ");
2089 print(tempVar + " = ___");
2090 println(helperMethod + "(); break;");
2098 * HELPER: writeMethodCallStructCallbackSkeleton() writes method call for wait invoke in skeleton
2100 private void writeMethodCallStructCallbackSkeleton(Collection<String> methods, InterfaceDecl intDecl) {
2102 // Use this set to handle two same methodIds
2103 for (String method : methods) {
2105 List<String> methParams = intDecl.getMethodParams(method);
2106 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2107 // Check for params with structs
2108 for (int i = 0; i < methParams.size(); i++) {
2109 String paramType = methPrmTypes.get(i);
2110 String param = methParams.get(i);
2111 String simpleType = getGenericType(paramType);
2112 if (isStructClass(simpleType)) {
2113 int methodNumId = intDecl.getMethodNumId(method);
2115 String helperMethod = methodNumId + "struct" + i;
2116 String tempVar = "struct" + methodNumId + "Size" + i;
2117 print(intDecl.getHelperMethodNumId(helperMethod) + ": ");
2118 print(tempVar + " = ___");
2119 println(helperMethod + "(rmiObj); break;");
2127 * HELPER: writeJavaMethodPermission() writes permission checks in skeleton
2129 private void writeJavaMethodPermission(String intface) {
2131 // Get all the different stubs
2132 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
2133 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
2134 String newIntface = intMeth.getKey();
2135 int newObjectId = getNewIntfaceObjectId(newIntface);
2136 println("if (_objectId == object" + newObjectId + "Id) {");
2137 println("if (!set" + newObjectId + "Allowed.contains(methodId)) {");
2138 println("throw new Error(\"Object with object Id: \" + _objectId + \" is not allowed to access method: \" + methodId);");
2142 println("throw new Error(\"Object Id: \" + _objectId + \" not recognized!\");");
2149 * HELPER: writeJavaWaitRequestInvokeMethod() writes the main loop of the skeleton class
2151 private void writeJavaWaitRequestInvokeMethod(Collection<String> methods, InterfaceDecl intDecl, boolean callbackExist, String intface) {
2153 // Use this set to handle two same methodIds
2154 Set<String> uniqueMethodIds = new HashSet<String>();
2155 println("private void ___waitRequestInvokeMethod() throws IOException {");
2156 // Write variables here if we have callbacks or enums or structs
2157 writeCountVarStructSkeleton(methods, intDecl);
2158 println("while (true) {");
2159 println("rmiObj.getMethodBytes();");
2160 println("int _objectId = rmiObj.getObjectId();");
2161 println("int methodId = rmiObj.getMethodId();");
2162 // Generate permission check
2163 writeJavaMethodPermission(intface);
2164 println("switch (methodId) {");
2165 // Print methods and method Ids
2166 for (String method : methods) {
2167 String methodId = intDecl.getMethodId(method);
2168 int methodNumId = intDecl.getMethodNumId(method);
2169 print("case " + methodNumId + ": ___");
2170 String helperMethod = methodId;
2171 if (uniqueMethodIds.contains(methodId))
2172 helperMethod = helperMethod + methodNumId;
2174 uniqueMethodIds.add(methodId);
2175 print(helperMethod + "(");
2176 writeInputCountVarStructSkeleton(method, intDecl);
2177 println("); break;");
2179 String method = "___initCallBack()";
2180 // Print case -9999 (callback handler) if callback exists
2181 if (callbackExist) {
2182 int methodId = intDecl.getHelperMethodNumId(method);
2183 println("case " + methodId + ": ___regCB(); break;");
2185 writeMethodCallStructSkeleton(methods, intDecl);
2186 println("default: ");
2187 println("throw new Error(\"Method Id \" + methodId + \" not recognized!\");");
2195 * generateJavaSkeletonClass() generate skeletons based on the methods list in Java
2197 public void generateJavaSkeletonClass() throws IOException {
2199 // Create a new directory
2200 String path = createDirectories(dir, subdir);
2201 for (String intface : mapIntfacePTH.keySet()) {
2202 // Open a new file to write into
2203 String newSkelClass = intface + "_Skeleton";
2204 FileWriter fw = new FileWriter(path + "/" + newSkelClass + ".java");
2205 pw = new PrintWriter(new BufferedWriter(fw));
2206 // Pass in set of methods and get import classes
2207 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2208 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
2209 List<String> methods = intDecl.getMethods();
2210 Set<String> importClasses = getImportClasses(methods, intDecl);
2211 List<String> stdImportClasses = getStandardJavaImportClasses();
2212 List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
2213 printImportStatements(allImportClasses);
2214 // Find out if there are callback objects
2215 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
2216 boolean callbackExist = !callbackClasses.isEmpty();
2217 // Write class header
2219 println("public class " + newSkelClass + " implements " + intface + " {\n");
2221 writePropertiesJavaSkeleton(intface, callbackExist, intDecl);
2222 // Write constructor
2223 writeConstructorJavaSkeleton(newSkelClass, intface, intDecl, methods, callbackExist);
2225 writeMethodJavaSkeleton(methods, intDecl, callbackClasses, false);
2226 // Write method helper
2227 writeMethodHelperJavaSkeleton(methods, intDecl, callbackClasses);
2228 // Write waitRequestInvokeMethod() - main loop
2229 writeJavaWaitRequestInvokeMethod(methods, intDecl, callbackExist, intface);
2232 System.out.println("IoTCompiler: Generated skeleton class " + newSkelClass + ".java...");
2238 * HELPER: writePropertiesJavaCallbackSkeleton() writes the properties of the callback skeleton class
2240 private void writePropertiesJavaCallbackSkeleton(String intface, boolean callbackExist) {
2242 println("private " + intface + " mainObj;");
2243 // For callback skeletons, this is its own object Id
2244 println("private int objectId = 0;");
2246 if (callbackExist) {
2247 println("private static int objIdCnt = 0;");
2248 println("private IoTRMICall rmiCall;");
2255 * HELPER: writeConstructorJavaCallbackSkeleton() writes the constructor of the skeleton class
2257 private void writeConstructorJavaCallbackSkeleton(String newSkelClass, String intface, InterfaceDecl intDecl, Collection<String> methods) {
2259 println("public " + newSkelClass + "(" + intface + " _mainObj, int _objectId) throws Exception {");
2260 println("mainObj = _mainObj;");
2261 println("objectId = _objectId;");
2267 * HELPER: writeMethodHelperJavaCallbackSkeleton() writes the method helper of the callback skeleton class
2269 private void writeMethodHelperJavaCallbackSkeleton(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
2271 // Use this set to handle two same methodIds
2272 Set<String> uniqueMethodIds = new HashSet<String>();
2273 for (String method : methods) {
2275 List<String> methParams = intDecl.getMethodParams(method);
2276 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2277 if (isStructPresent(methParams, methPrmTypes)) { // Treat struct differently
2278 String methodId = intDecl.getMethodId(method);
2279 print("public void ___");
2280 String helperMethod = methodId;
2281 if (uniqueMethodIds.contains(methodId))
2282 helperMethod = helperMethod + intDecl.getMethodNumId(method);
2284 uniqueMethodIds.add(methodId);
2285 String retType = intDecl.getMethodType(method);
2286 print(helperMethod + "(");
2287 boolean begin = true;
2288 for (int i = 0; i < methParams.size(); i++) { // Print size variables
2289 String paramType = methPrmTypes.get(i);
2290 String param = methParams.get(i);
2291 String simpleType = getGenericType(paramType);
2292 if (isStructClass(simpleType)) {
2293 if (!begin) // Generate comma for not the beginning variable
2297 int methodNumId = intDecl.getMethodNumId(method);
2298 print("int struct" + methodNumId + "Size" + i);
2301 // Check if this is "void"
2302 if (retType.equals("void"))
2303 println(", IoTRMIObject rmiObj) {");
2305 println(", IoTRMIObject rmiObj) throws IOException {");
2306 writeMethodHelperStructJavaSkeleton(intDecl, methParams, methPrmTypes, method, callbackClasses);
2309 String methodId = intDecl.getMethodId(method);
2310 print("public void ___");
2311 String helperMethod = methodId;
2312 if (uniqueMethodIds.contains(methodId))
2313 helperMethod = helperMethod + intDecl.getMethodNumId(method);
2315 uniqueMethodIds.add(methodId);
2316 // Check if this is "void"
2317 String retType = intDecl.getMethodType(method);
2318 if (retType.equals("void"))
2319 println(helperMethod + "(IoTRMIObject rmiObj) {");
2321 println(helperMethod + "(IoTRMIObject rmiObj) throws IOException {");
2322 // Now, write the helper body of skeleton!
2323 writeStdMethodHelperBodyJavaSkeleton(intDecl, methParams, methPrmTypes, method, callbackClasses);
2327 // Write method helper for structs
2328 writeMethodHelperStructSetupJavaCallbackSkeleton(methods, intDecl);
2333 * HELPER: writeJavaCallbackWaitRequestInvokeMethod() writes the request invoke method of the callback skeleton class
2335 private void writeJavaCallbackWaitRequestInvokeMethod(Collection<String> methods, InterfaceDecl intDecl, boolean callbackExist) {
2337 // Use this set to handle two same methodIds
2338 Set<String> uniqueMethodIds = new HashSet<String>();
2339 println("public void invokeMethod(IoTRMIObject rmiObj) throws IOException {");
2340 // Write variables here if we have callbacks or enums or structs
2341 writeCountVarStructSkeleton(methods, intDecl);
2342 // Write variables here if we have callbacks or enums or structs
2343 println("int methodId = rmiObj.getMethodId();");
2344 // TODO: code the permission check here!
2345 println("switch (methodId) {");
2346 // Print methods and method Ids
2347 for (String method : methods) {
2348 String methodId = intDecl.getMethodId(method);
2349 int methodNumId = intDecl.getMethodNumId(method);
2350 print("case " + methodNumId + ": ___");
2351 String helperMethod = methodId;
2352 if (uniqueMethodIds.contains(methodId))
2353 helperMethod = helperMethod + methodNumId;
2355 uniqueMethodIds.add(methodId);
2356 print(helperMethod + "(");
2357 if (writeInputCountVarStructSkeleton(method, intDecl))
2358 println(", rmiObj); break;");
2360 println("rmiObj); break;");
2362 String method = "___initCallBack()";
2363 // Print case -9999 (callback handler) if callback exists
2364 if (callbackExist) {
2365 int methodId = intDecl.getHelperMethodNumId(method);
2366 println("case " + methodId + ": ___regCB(rmiObj); break;");
2368 writeMethodCallStructCallbackSkeleton(methods, intDecl);
2369 println("default: ");
2370 println("throw new Error(\"Method Id \" + methodId + \" not recognized!\");");
2377 * generateJavaCallbackSkeletonClass() generate callback skeletons based on the methods list in Java
2379 public void generateJavaCallbackSkeletonClass() throws IOException {
2381 // Create a new directory
2382 String path = createDirectories(dir, subdir);
2383 for (String intface : mapIntfacePTH.keySet()) {
2384 // Open a new file to write into
2385 String newSkelClass = intface + "_CallbackSkeleton";
2386 FileWriter fw = new FileWriter(path + "/" + newSkelClass + ".java");
2387 pw = new PrintWriter(new BufferedWriter(fw));
2388 // Pass in set of methods and get import classes
2389 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2390 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
2391 List<String> methods = intDecl.getMethods();
2392 Set<String> importClasses = getImportClasses(methods, intDecl);
2393 List<String> stdImportClasses = getStandardJavaImportClasses();
2394 List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
2395 printImportStatements(allImportClasses);
2396 // Find out if there are callback objects
2397 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
2398 boolean callbackExist = !callbackClasses.isEmpty();
2399 // Write class header
2401 println("public class " + newSkelClass + " implements " + intface + " {\n");
2403 writePropertiesJavaCallbackSkeleton(intface, callbackExist);
2404 // Write constructor
2405 writeConstructorJavaCallbackSkeleton(newSkelClass, intface, intDecl, methods);
2407 writeMethodJavaSkeleton(methods, intDecl, callbackClasses, true);
2408 // Write method helper
2409 writeMethodHelperJavaCallbackSkeleton(methods, intDecl, callbackClasses);
2410 // Write waitRequestInvokeMethod() - main loop
2411 writeJavaCallbackWaitRequestInvokeMethod(methods, intDecl, callbackExist);
2414 System.out.println("IoTCompiler: Generated callback skeleton class " + newSkelClass + ".java...");
2420 * HELPER: writeMethodCplusLocalInterface() writes the method of the local interface
2422 private void writeMethodCplusLocalInterface(Collection<String> methods, InterfaceDecl intDecl) {
2424 for (String method : methods) {
2426 List<String> methParams = intDecl.getMethodParams(method);
2427 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2428 print("virtual " + checkAndGetCplusType(intDecl.getMethodType(method)) + " " +
2429 intDecl.getMethodId(method) + "(");
2430 for (int i = 0; i < methParams.size(); i++) {
2431 // Check for params with driver class types and exchange it
2432 // with its remote interface
2433 String paramType = checkAndGetParamClass(methPrmTypes.get(i));
2434 paramType = checkAndGetCplusType(paramType);
2435 // Check for arrays - translate into vector in C++
2436 String paramComplete = checkAndGetCplusArray(paramType, methParams.get(i));
2437 print(paramComplete);
2438 // Check if this is the last element (don't print a comma)
2439 if (i != methParams.size() - 1) {
2449 * HELPER: writeMethodCplusInterface() writes the method of the interface
2451 private void writeMethodCplusInterface(Collection<String> methods, InterfaceDecl intDecl) {
2453 for (String method : methods) {
2455 List<String> methParams = intDecl.getMethodParams(method);
2456 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2457 print("virtual " + checkAndGetCplusType(intDecl.getMethodType(method)) + " " +
2458 intDecl.getMethodId(method) + "(");
2459 for (int i = 0; i < methParams.size(); i++) {
2460 // Check for params with driver class types and exchange it
2461 // with its remote interface
2462 String paramType = methPrmTypes.get(i);
2463 paramType = checkAndGetCplusType(paramType);
2464 // Check for arrays - translate into vector in C++
2465 String paramComplete = checkAndGetCplusArray(paramType, methParams.get(i));
2466 print(paramComplete);
2467 // Check if this is the last element (don't print a comma)
2468 if (i != methParams.size() - 1) {
2478 * HELPER: generateEnumCplus() writes the enumeration declaration
2480 public void generateEnumCplus() throws IOException {
2482 // Create a new directory
2483 createDirectory(dir);
2484 for (String intface : mapIntfacePTH.keySet()) {
2485 // Get the right StructDecl
2486 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2487 EnumDecl enumDecl = (EnumDecl) decHandler.getEnumDecl(intface);
2488 Set<String> enumTypes = enumDecl.getEnumDeclarations();
2489 // Iterate over enum declarations
2490 for (String enType : enumTypes) {
2491 // Open a new file to write into
2492 FileWriter fw = new FileWriter(dir + "/" + enType + ".hpp");
2493 pw = new PrintWriter(new BufferedWriter(fw));
2494 // Write file headers
2495 println("#ifndef _" + enType.toUpperCase() + "_HPP__");
2496 println("#define _" + enType.toUpperCase() + "_HPP__");
2497 println("enum " + enType + " {");
2498 List<String> enumMembers = enumDecl.getMembers(enType);
2499 for (int i = 0; i < enumMembers.size(); i++) {
2501 String member = enumMembers.get(i);
2503 // Check if this is the last element (don't print a comma)
2504 if (i != enumMembers.size() - 1)
2512 System.out.println("IoTCompiler: Generated enum " + enType + ".hpp...");
2519 * HELPER: generateStructCplus() writes the struct declaration
2521 public void generateStructCplus() throws IOException {
2523 // Create a new directory
2524 createDirectory(dir);
2525 for (String intface : mapIntfacePTH.keySet()) {
2526 // Get the right StructDecl
2527 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2528 StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
2529 List<String> structTypes = structDecl.getStructTypes();
2530 // Iterate over enum declarations
2531 for (String stType : structTypes) {
2532 // Open a new file to write into
2533 FileWriter fw = new FileWriter(dir + "/" + stType + ".hpp");
2534 pw = new PrintWriter(new BufferedWriter(fw));
2535 // Write file headers
2536 println("#ifndef _" + stType.toUpperCase() + "_HPP__");
2537 println("#define _" + stType.toUpperCase() + "_HPP__");
2538 println("using namespace std;");
2539 println("struct " + stType + " {");
2540 List<String> structMemberTypes = structDecl.getMemberTypes(stType);
2541 List<String> structMembers = structDecl.getMembers(stType);
2542 for (int i = 0; i < structMembers.size(); i++) {
2544 String memberType = structMemberTypes.get(i);
2545 String member = structMembers.get(i);
2546 String structTypeC = checkAndGetCplusType(memberType);
2547 String structComplete = checkAndGetCplusArray(structTypeC, member);
2548 println(structComplete + ";");
2553 System.out.println("IoTCompiler: Generated struct " + stType + ".hpp...");
2560 * generateCplusLocalInterfaces() writes the local interfaces and provides type-checking.
2562 * It needs to rewrite and exchange USERDEFINED types in input parameters of stub
2563 * and original interfaces, e.g. exchange Camera and CameraWithVideoAndRecording.
2564 * The local interface has to be the input parameter for the stub and the stub
2565 * interface has to be the input parameter for the local class.
2567 public void generateCplusLocalInterfaces() throws IOException {
2569 // Create a new directory
2570 createDirectory(dir);
2571 for (String intface : mapIntfacePTH.keySet()) {
2572 // Open a new file to write into
2573 FileWriter fw = new FileWriter(dir + "/" + intface + ".hpp");
2574 pw = new PrintWriter(new BufferedWriter(fw));
2575 // Write file headers
2576 println("#ifndef _" + intface.toUpperCase() + "_HPP__");
2577 println("#define _" + intface.toUpperCase() + "_HPP__");
2578 println("#include <iostream>");
2579 // Pass in set of methods and get include classes
2580 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2581 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
2582 List<String> methods = intDecl.getMethods();
2583 Set<String> includeClasses = getIncludeClasses(methods, intDecl, intface, true);
2584 printIncludeStatements(includeClasses); println("");
2585 println("using namespace std;\n");
2586 //writeStructCplus(structDecl);
2587 println("class " + intface); println("{");
2590 writeMethodCplusLocalInterface(methods, intDecl);
2594 System.out.println("IoTCompiler: Generated local interface " + intface + ".hpp...");
2600 * generateCPlusInterfaces() generate stub interfaces based on the methods list in C++
2602 * For C++ we use virtual classe as interface
2604 public void generateCPlusInterfaces() throws IOException {
2606 // Create a new directory
2607 String path = createDirectories(dir, subdir);
2608 for (String intface : mapIntfacePTH.keySet()) {
2610 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
2611 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
2613 // Open a new file to write into
2614 String newIntface = intMeth.getKey();
2615 FileWriter fw = new FileWriter(path + "/" + newIntface + ".hpp");
2616 pw = new PrintWriter(new BufferedWriter(fw));
2617 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2618 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
2619 // Write file headers
2620 println("#ifndef _" + newIntface.toUpperCase() + "_HPP__");
2621 println("#define _" + newIntface.toUpperCase() + "_HPP__");
2622 println("#include <iostream>");
2623 // Pass in set of methods and get import classes
2624 Set<String> includeClasses = getIncludeClasses(intMeth.getValue(), intDecl, intface, false);
2625 List<String> stdIncludeClasses = getStandardCplusIncludeClasses();
2626 List<String> allIncludeClasses = getAllLibClasses(stdIncludeClasses, includeClasses);
2627 printIncludeStatements(allIncludeClasses); println("");
2628 println("using namespace std;\n");
2629 println("class " + newIntface);
2633 writeMethodCplusInterface(intMeth.getValue(), intDecl);
2637 System.out.println("IoTCompiler: Generated interface " + newIntface + ".hpp...");
2644 * HELPER: writeMethodCplusStub() writes the methods of the stub
2646 private void writeMethodCplusStub(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
2648 boolean isDefined = false;
2649 for (String method : methods) {
2651 List<String> methParams = intDecl.getMethodParams(method);
2652 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2653 print(checkAndGetCplusType(intDecl.getMethodType(method)) + " " +
2654 intDecl.getMethodId(method) + "(");
2655 boolean isCallbackMethod = false;
2656 String callbackType = null;
2657 for (int i = 0; i < methParams.size(); i++) {
2659 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
2660 // Check if this has callback object
2661 if (callbackClasses.contains(paramType)) {
2662 isCallbackMethod = true;
2663 callbackType = paramType;
2664 // Even if there're 2 callback arguments, we expect them to be of the same interface
2666 String methPrmType = checkAndGetCplusType(methPrmTypes.get(i));
2667 String methParamComplete = checkAndGetCplusArray(methPrmType, methParams.get(i));
2668 print(methParamComplete);
2669 // Check if this is the last element (don't print a comma)
2670 if (i != methParams.size() - 1) {
2675 if (isCallbackMethod)
2676 writeCallbackMethodBodyCplusStub(intDecl, methParams, methPrmTypes, method, callbackType);
2677 writeStdMethodBodyCplusStub(intDecl, methParams, methPrmTypes, method, callbackType, isCallbackMethod);
2679 // Write the init callback helper method
2680 if (isCallbackMethod && !isDefined) {
2681 writeInitCallbackCplusStub(callbackType, intDecl);
2682 writeInitCallbackSendInfoCplusStub(intDecl);
2690 * HELPER: writeCallbackMethodBodyCplusStub() writes the callback method of the stub class
2692 private void writeCallbackMethodBodyCplusStub(InterfaceDecl intDecl, List<String> methParams,
2693 List<String> methPrmTypes, String method, String callbackType) {
2695 // Check if this is single object, array, or list of objects
2696 boolean isArrayOrList = false;
2697 String callbackParam = null;
2698 for (int i = 0; i < methParams.size(); i++) {
2700 String paramType = methPrmTypes.get(i);
2701 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
2702 String param = methParams.get(i);
2703 if (isArrayOrList(paramType, param)) { // Generate loop
2704 println("for (" + getGenericType(paramType) + "* cb : " + getSimpleIdentifier(param) + ") {");
2705 println(callbackType + "_CallbackSkeleton* skel" + i + " = new " + callbackType + "_CallbackSkeleton(cb, objIdCnt++);");
2706 isArrayOrList = true;
2707 callbackParam = getSimpleIdentifier(param);
2709 println(callbackType + "_CallbackSkeleton* skel" + i + " = new " + callbackType + "_CallbackSkeleton(" +
2710 getSimpleIdentifier(param) + ", objIdCnt++);");
2711 println("vecCallbackObj.push_back(skel" + i + ");");
2714 print("int ___paramCB" + i + " = ");
2716 println(callbackParam + ".size();");
2725 * HELPER: checkAndWriteEnumTypeCplusStub() writes the enum type (convert from enum to int)
2727 private void checkAndWriteEnumTypeCplusStub(List<String> methParams, List<String> methPrmTypes) {
2729 // Iterate and find enum declarations
2730 for (int i = 0; i < methParams.size(); i++) {
2731 String paramType = methPrmTypes.get(i);
2732 String param = methParams.get(i);
2733 if (isEnumClass(getGenericType(paramType))) {
2734 // Check if this is enum type
2735 if (isArrayOrList(paramType, param)) { // An array or vector
2736 println("int len" + i + " = " + getSimpleIdentifier(param) + ".size();");
2737 println("vector<int> paramEnum" + i + "(len" + i + ");");
2738 println("for (int i = 0; i < len" + i + "; i++) {");
2739 println("paramEnum" + i + "[i] = (int) " + getSimpleIdentifier(param) + "[i];");
2741 } else { // Just one element
2742 println("vector<int> paramEnum" + i + "(1);");
2743 println("paramEnum" + i + "[0] = (int) " + param + ";");
2751 * HELPER: checkAndWriteEnumRetTypeCplusStub() writes the enum return type (convert from enum to int)
2753 private void checkAndWriteEnumRetTypeCplusStub(String retType) {
2755 // Strips off array "[]" for return type
2756 String pureType = getSimpleArrayType(getGenericType(retType));
2757 // Take the inner type of generic
2758 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
2759 pureType = getGenericType(retType);
2760 if (isEnumClass(pureType)) {
2761 // Check if this is enum type
2762 println("vector<int> retEnumInt;");
2763 println("void* retObj = &retEnumInt;");
2764 println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
2765 if (isArrayOrList(retType, retType)) { // An array or vector
2766 println("int retLen = retEnumInt.size();");
2767 println("vector<" + pureType + "> retVal(retLen);");
2768 println("for (int i = 0; i < retLen; i++) {");
2769 println("retVal[i] = (" + pureType + ") retEnumInt[i];");
2771 } else { // Just one element
2772 println(pureType + " retVal = (" + pureType + ") retEnumInt[0];");
2774 println("return retVal;");
2780 * HELPER: checkAndWriteStructSetupCplusStub() writes the struct type setup
2782 private void checkAndWriteStructSetupCplusStub(List<String> methParams, List<String> methPrmTypes,
2783 InterfaceDecl intDecl, String method) {
2785 // Iterate and find struct declarations
2786 for (int i = 0; i < methParams.size(); i++) {
2787 String paramType = methPrmTypes.get(i);
2788 String param = methParams.get(i);
2789 String simpleType = getGenericType(paramType);
2790 if (isStructClass(simpleType)) {
2791 // Check if this is enum type
2792 println("int numParam" + i + " = 1;");
2793 int methodNumId = intDecl.getMethodNumId(method);
2794 String helperMethod = methodNumId + "struct" + i;
2795 println("int methodIdStruct" + i + " = " + intDecl.getHelperMethodNumId(helperMethod) + ";");
2796 println("string retTypeStruct" + i + " = \"void\";");
2797 println("string paramClsStruct" + i + "[] = { \"int\" };");
2798 print("int structLen" + i + " = ");
2799 if (isArrayOrList(paramType, param)) { // An array
2800 println(getSimpleArrayType(param) + ".size();");
2801 } else { // Just one element
2804 println("void* paramObjStruct" + i + "[] = { &structLen" + i + " };");
2805 println("void* retStructLen" + i + " = NULL;");
2806 println("rmiCall->remoteCall(objectId, methodIdStruct" + i +
2807 ", retTypeStruct" + i + ", paramClsStruct" + i + ", paramObjStruct" + i +
2808 ", numParam" + i + ", retStructLen" + i + ");\n");
2815 * HELPER: writeLengthStructParamClassCplusStub() writes lengths of params
2817 private void writeLengthStructParamClassCplusStub(List<String> methParams, List<String> methPrmTypes) {
2819 // Iterate and find struct declarations - count number of params
2820 for (int i = 0; i < methParams.size(); i++) {
2821 String paramType = methPrmTypes.get(i);
2822 String param = methParams.get(i);
2823 String simpleType = getGenericType(paramType);
2824 if (isStructClass(simpleType)) {
2825 int members = getNumOfMembers(simpleType);
2826 if (isArrayOrList(paramType, param)) { // An array or list
2827 String structLen = getSimpleIdentifier(param) + ".size()";
2828 print(members + "*" + structLen);
2830 print(Integer.toString(members));
2833 if (i != methParams.size() - 1) {
2841 * HELPER: writeStructMembersCplusStub() writes member parameters of struct
2843 private void writeStructMembersCplusStub(String simpleType, String paramType, String param) {
2845 // Get the struct declaration for this struct and generate initialization code
2846 StructDecl structDecl = getStructDecl(simpleType);
2847 List<String> memTypes = structDecl.getMemberTypes(simpleType);
2848 List<String> members = structDecl.getMembers(simpleType);
2849 if (isArrayOrList(paramType, param)) { // An array or list
2850 println("for(int i = 0; i < " + getSimpleIdentifier(param) + ".size(); i++) {");
2852 if (isArrayOrList(paramType, param)) { // An array or list
2853 for (int i = 0; i < members.size(); i++) {
2854 String prmTypeC = checkAndGetCplusArgClsType(memTypes.get(i), members.get(i));
2855 println("paramCls[pos] = \"" + prmTypeC + "\";");
2856 print("paramObj[pos++] = &" + getSimpleIdentifier(param) + "[i].");
2857 print(getSimpleIdentifier(members.get(i)));
2861 } else { // Just one struct element
2862 for (int i = 0; i < members.size(); i++) {
2863 String prmTypeC = checkAndGetCplusArgClsType(memTypes.get(i), members.get(i));
2864 println("paramCls[pos] = \"" + prmTypeC + "\";");
2865 print("paramObj[pos++] = &" + param + ".");
2866 print(getSimpleIdentifier(members.get(i)));
2874 * HELPER: writeStructParamClassCplusStub() writes member parameters of struct
2876 private void writeStructParamClassCplusStub(List<String> methParams, List<String> methPrmTypes, String callbackType) {
2878 print("int numParam = ");
2879 writeLengthStructParamClassCplusStub(methParams, methPrmTypes);
2881 println("void* paramObj[numParam];");
2882 println("string paramCls[numParam];");
2883 println("int pos = 0;");
2884 // Iterate again over the parameters
2885 for (int i = 0; i < methParams.size(); i++) {
2886 String paramType = methPrmTypes.get(i);
2887 String param = methParams.get(i);
2888 String simpleType = getGenericType(paramType);
2889 if (isStructClass(simpleType)) {
2890 writeStructMembersCplusStub(simpleType, paramType, param);
2891 } else if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
2892 println("paramCls[pos] = \"int\";");
2893 println("paramObj[pos++] = &___paramCB" + i + ";");
2895 String prmTypeC = checkAndGetCplusArgClsType(methPrmTypes.get(i), methParams.get(i));
2896 println("paramCls[pos] = \"" + prmTypeC + "\";");
2897 print("paramObj[pos++] = &");
2898 print(getEnumParam(methPrmTypes.get(i), getSimpleIdentifier(methParams.get(i)), i));
2907 * HELPER: writeStructRetMembersCplusStub() writes member parameters of struct for return statement
2909 private void writeStructRetMembersCplusStub(String simpleType, String retType) {
2911 // Get the struct declaration for this struct and generate initialization code
2912 StructDecl structDecl = getStructDecl(simpleType);
2913 List<String> memTypes = structDecl.getMemberTypes(simpleType);
2914 List<String> members = structDecl.getMembers(simpleType);
2915 if (isArrayOrList(retType, retType)) { // An array or list
2916 println("for(int i = 0; i < retLen; i++) {");
2918 if (isArrayOrList(retType, retType)) { // An array or list
2919 for (int i = 0; i < members.size(); i++) {
2920 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
2921 print("structRet[i]." + getSimpleIdentifier(members.get(i)));
2922 println(" = retParam" + i + "[i];");
2925 } else { // Just one struct element
2926 for (int i = 0; i < members.size(); i++) {
2927 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
2928 print("structRet." + getSimpleIdentifier(members.get(i)));
2929 println(" = retParam" + i + ";");
2932 println("return structRet;");
2937 * HELPER: writeStructReturnCplusStub() writes member parameters of struct for return statement
2939 private void writeStructReturnCplusStub(String simpleType, String retType) {
2941 // Minimum retLen is 1 if this is a single struct object
2942 println("int retLen = 0;");
2943 println("void* retLenObj = { &retLen };");
2944 // Handle the returned struct!!!
2945 println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retLenObj);");
2946 int numMem = getNumOfMembers(simpleType);
2947 println("int numRet = " + numMem + "*retLen;");
2948 println("string retCls[numRet];");
2949 println("void* retObj[numRet];");
2950 StructDecl structDecl = getStructDecl(simpleType);
2951 List<String> memTypes = structDecl.getMemberTypes(simpleType);
2952 List<String> members = structDecl.getMembers(simpleType);
2954 if (isArrayOrList(retType, retType)) { // An array or list
2955 for (int i = 0; i < members.size(); i++) {
2956 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
2957 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
2958 println(getSimpleType(getEnumType(prmType)) + " retParam" + i + "[retLen];");
2960 } else { // Just one struct element
2961 for (int i = 0; i < members.size(); i++) {
2962 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
2963 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
2964 println(getSimpleType(getEnumType(prmType)) + " retParam" + i + ";");
2967 println("int retPos = 0;");
2968 // Get the struct declaration for this struct and generate initialization code
2969 if (isArrayOrList(retType, retType)) { // An array or list
2970 println("for(int i = 0; i < retLen; i++) {");
2971 for (int i = 0; i < members.size(); i++) {
2972 String prmTypeC = checkAndGetCplusArgClsType(memTypes.get(i), members.get(i));
2973 println("retCls[retPos] = \"" + prmTypeC + "\";");
2974 println("retObj[retPos++] = &retParam" + i + "[i];");
2977 } else { // Just one struct element
2978 for (int i = 0; i < members.size(); i++) {
2979 String prmTypeC = checkAndGetCplusArgClsType(memTypes.get(i), members.get(i));
2980 println("retCls[retPos] = \"" + prmTypeC + "\";");
2981 println("retObj[retPos++] = &retParam" + i + ";");
2984 println("rmiCall->getStructObjects(retCls, numRet, retObj);");
2985 if (isArrayOrList(retType, retType)) { // An array or list
2986 println("vector<" + simpleType + "> structRet(retLen);");
2988 println(simpleType + " structRet;");
2989 writeStructRetMembersCplusStub(simpleType, retType);
2994 * HELPER: writeStdMethodBodyCplusStub() writes the standard method body in the stub class
2996 private void writeStdMethodBodyCplusStub(InterfaceDecl intDecl, List<String> methParams,
2997 List<String> methPrmTypes, String method, String callbackType, boolean isCallbackMethod) {
2999 checkAndWriteStructSetupCplusStub(methParams, methPrmTypes, intDecl, method);
3000 println("int methodId = " + intDecl.getMethodNumId(method) + ";");
3001 String retType = intDecl.getMethodType(method);
3002 println("string retType = \"" + checkAndGetCplusRetClsType(getStructType(getEnumType(retType))) + "\";");
3003 checkAndWriteEnumTypeCplusStub(methParams, methPrmTypes);
3004 // Generate array of parameter types
3005 if (isStructPresent(methParams, methPrmTypes)) {
3006 writeStructParamClassCplusStub(methParams, methPrmTypes, callbackType);
3008 println("int numParam = " + methParams.size() + ";");
3009 print("string paramCls[] = { ");
3010 for (int i = 0; i < methParams.size(); i++) {
3011 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
3012 if (checkCallbackType(paramType, callbackType)) {
3015 String paramTypeC = checkAndGetCplusArgClsType(methPrmTypes.get(i), methParams.get(i));
3016 print("\"" + paramTypeC + "\"");
3018 // Check if this is the last element (don't print a comma)
3019 if (i != methParams.size() - 1) {
3024 // Generate array of parameter objects
3025 print("void* paramObj[] = { ");
3026 for (int i = 0; i < methParams.size(); i++) {
3027 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
3028 if (checkCallbackType(paramType, callbackType)) // Check if this has callback object
3029 print("&___paramCB" + i);
3031 print("&" + getEnumParam(methPrmTypes.get(i), getSimpleIdentifier(methParams.get(i)), i));
3032 // Check if this is the last element (don't print a comma)
3033 if (i != methParams.size() - 1) {
3039 // Check if this is "void"
3040 if (retType.equals("void")) {
3041 println("void* retObj = NULL;");
3042 println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
3043 } else { // We do have a return value
3044 // Generate array of parameter types
3045 if (isStructClass(getGenericType(getSimpleArrayType(retType)))) {
3046 writeStructReturnCplusStub(getGenericType(getSimpleArrayType(retType)), retType);
3048 // Check if the return value NONPRIMITIVES
3049 if (isEnumClass(getSimpleArrayType(getGenericType(retType)))) {
3050 checkAndWriteEnumRetTypeCplusStub(retType);
3052 //if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
3053 if (isArrayOrList(retType,retType))
3054 println(checkAndGetCplusType(retType) + " retVal;");
3056 println(checkAndGetCplusType(retType) + " retVal = " + generateCplusInitializer(retType) + ";");
3058 println("void* retObj = &retVal;");
3059 println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
3060 println("return retVal;");
3068 * HELPER: writePropertiesCplusStub() writes the properties of the stub class
3070 private void writePropertiesCplusPermission(String intface) {
3072 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3073 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3074 String newIntface = intMeth.getKey();
3075 int newObjectId = getNewIntfaceObjectId(newIntface);
3076 println("const static int object" + newObjectId + "Id = " + newObjectId + ";\t//" + newIntface);
3077 println("static set<int> set" + newObjectId + "Allowed;");
3082 * HELPER: writePropertiesCplusStub() writes the properties of the stub class
3084 private void writePropertiesCplusStub(String intface, String newIntface, boolean callbackExist, Set<String> callbackClasses) {
3086 println("IoTRMICall *rmiCall;");
3087 println("string callbackAddress;");
3088 println("vector<int> ports;\n");
3089 // Get the object Id
3090 Integer objId = mapIntfaceObjId.get(intface);
3091 println("const static int objectId = " + objId + ";");
3092 mapNewIntfaceObjId.put(newIntface, objId);
3093 mapIntfaceObjId.put(intface, objId++);
3094 if (callbackExist) {
3095 // We assume that each class only has one callback interface for now
3096 Iterator it = callbackClasses.iterator();
3097 String callbackType = (String) it.next();
3098 println("// Callback properties");
3099 println("IoTRMIObject *rmiObj;");
3100 println("vector<" + callbackType + "*> vecCallbackObj;");
3101 println("static int objIdCnt;");
3102 // Generate permission stuff for callback stubs
3103 writePropertiesCplusPermission(callbackType);
3110 * HELPER: writeConstructorCplusStub() writes the constructor of the stub class
3112 private void writeConstructorCplusStub(String newStubClass, boolean callbackExist, Set<String> callbackClasses) {
3114 println(newStubClass +
3115 "(int _port, const char* _skeletonAddress, const char* _callbackAddress, int _rev, bool* _bResult, vector<int> _ports) {");
3116 println("callbackAddress = _callbackAddress;");
3117 println("ports = _ports;");
3118 println("rmiCall = new IoTRMICall(_port, _skeletonAddress, _rev, _bResult);");
3119 if (callbackExist) {
3120 Iterator it = callbackClasses.iterator();
3121 String callbackType = (String) it.next();
3122 println("thread th1 (&" + newStubClass + "::___initCallBack, this);");
3123 println("th1.detach();");
3124 println("___regCB();");
3131 * HELPER: writeDeconstructorCplusStub() writes the deconstructor of the stub class
3133 private void writeDeconstructorCplusStub(String newStubClass, boolean callbackExist, Set<String> callbackClasses) {
3135 println("~" + newStubClass + "() {");
3136 println("if (rmiCall != NULL) {");
3137 println("delete rmiCall;");
3138 println("rmiCall = NULL;");
3140 if (callbackExist) {
3141 // We assume that each class only has one callback interface for now
3142 println("if (rmiObj != NULL) {");
3143 println("delete rmiObj;");
3144 println("rmiObj = NULL;");
3146 Iterator it = callbackClasses.iterator();
3147 String callbackType = (String) it.next();
3148 println("for(" + callbackType + "* cb : vecCallbackObj) {");
3149 println("delete cb;");
3150 println("cb = NULL;");
3159 * HELPER: writeCplusMethodCallbackPermission() writes permission checks in stub for callbacks
3161 private void writeCplusMethodCallbackPermission(String intface) {
3163 println("int methodId = IoTRMIObject::getMethodId(method);");
3164 // Get all the different stubs
3165 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3166 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3167 String newIntface = intMeth.getKey();
3168 int newObjectId = getNewIntfaceObjectId(newIntface);
3169 println("if (set" + newObjectId + "Allowed.find(methodId) == set" + newObjectId + "Allowed.end()) {");
3170 println("cerr << \"Callback object for " + intface + " is not allowed to access method: \" << methodId;");
3178 * HELPER: writeInitCallbackCplusStub() writes the initialization of callback
3180 private void writeInitCallbackCplusStub(String intface, InterfaceDecl intDecl) {
3182 println("void ___initCallBack() {");
3183 println("bool bResult = false;");
3184 println("rmiObj = new IoTRMIObject(ports[0], &bResult);");
3185 println("while (true) {");
3186 println("char* method = rmiObj->getMethodBytes();");
3187 writeCplusMethodCallbackPermission(intface);
3188 println("int objId = IoTRMIObject::getObjectId(method);");
3189 println("if (objId < vecCallbackObj.size()) { // Check if still within range");
3190 println(intface + "_CallbackSkeleton* skel = dynamic_cast<" + intface +
3191 "_CallbackSkeleton*> (vecCallbackObj.at(objId));");
3192 println("skel->invokeMethod(rmiObj);");
3195 println("cerr << \"Illegal object Id: \" << to_string(objId);");
3196 // TODO: perhaps need to change this into "throw" to make it cleaner (allow stack unfolding)
3205 * HELPER: writeCplusInitCallbackPermission() writes the permission for callback
3207 private void writeCplusInitCallbackPermission(String intface, InterfaceDecl intDecl, boolean callbackExist) {
3209 if (callbackExist) {
3210 String method = "___initCallBack()";
3211 int methodNumId = intDecl.getHelperMethodNumId(method);
3212 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3213 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3214 String newIntface = intMeth.getKey();
3215 int newObjectId = getNewIntfaceObjectId(newIntface);
3216 println("set" + newObjectId + "Allowed.insert(" + methodNumId + ");");
3223 * HELPER: writeInitCallbackSendInfoCplusStub() writes the initialization (send info part) of callback
3225 private void writeInitCallbackSendInfoCplusStub(InterfaceDecl intDecl) {
3227 // Generate info sending part
3228 println("void ___regCB() {");
3229 println("int numParam = 3;");
3230 String method = "___initCallBack()";
3231 int methodNumId = intDecl.getHelperMethodNumId(method);
3232 println("int methodId = " + methodNumId + ";");
3233 println("string retType = \"void\";");
3234 println("string paramCls[] = { \"int\", \"String\", \"int\" };");
3235 println("int rev = 0;");
3236 println("void* paramObj[] = { &ports[0], &callbackAddress, &rev };");
3237 println("void* retObj = NULL;");
3238 println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
3244 * generateCPlusStubClasses() generate stubs based on the methods list in C++
3246 public void generateCPlusStubClasses() throws IOException {
3248 // Create a new directory
3249 String path = createDirectories(dir, subdir);
3250 for (String intface : mapIntfacePTH.keySet()) {
3252 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3253 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3254 // Open a new file to write into
3255 String newIntface = intMeth.getKey();
3256 String newStubClass = newIntface + "_Stub";
3257 FileWriter fw = new FileWriter(path + "/" + newStubClass + ".hpp");
3258 pw = new PrintWriter(new BufferedWriter(fw));
3259 // Write file headers
3260 println("#ifndef _" + newStubClass.toUpperCase() + "_HPP__");
3261 println("#define _" + newStubClass.toUpperCase() + "_HPP__");
3262 println("#include <iostream>");
3263 // Find out if there are callback objects
3264 Set<String> methods = intMeth.getValue();
3265 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
3266 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
3267 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
3268 boolean callbackExist = !callbackClasses.isEmpty();
3269 if (callbackExist) // Need thread library if this has callback
3270 println("#include <thread>");
3271 println("#include \"" + newIntface + ".hpp\""); println("");
3272 println("using namespace std;"); println("");
3273 println("class " + newStubClass + " : public " + newIntface); println("{");
3274 println("private:\n");
3275 writePropertiesCplusStub(intface, newIntface, callbackExist, callbackClasses);
3276 println("public:\n");
3277 // Add default constructor and destructor
3278 println(newStubClass + "() { }"); println("");
3279 writeConstructorCplusStub(newStubClass, callbackExist, callbackClasses);
3280 writeDeconstructorCplusStub(newStubClass, callbackExist, callbackClasses);
3282 writeMethodCplusStub(methods, intDecl, callbackClasses);
3283 print("}"); println(";");
3284 if (callbackExist) {
3285 Iterator it = callbackClasses.iterator();
3286 String callbackType = (String) it.next();
3287 // Generate permission stuff for callback stubs
3288 DeclarationHandler decHandlerCallback = mapIntDeclHand.get(callbackType);
3289 InterfaceDecl intDeclCallback = (InterfaceDecl) decHandlerCallback.getInterfaceDecl(callbackType);
3290 writePermissionInitializationCplus(callbackType, newStubClass, intDeclCallback);
3292 writeObjectIdCountInitializationCplus(newStubClass, callbackExist);
3295 System.out.println("IoTCompiler: Generated stub class " + newStubClass + ".hpp...");
3302 * HELPER: writePropertiesCplusCallbackStub() writes the properties of the stub class
3304 private void writePropertiesCplusCallbackStub(String intface, String newIntface, boolean callbackExist, Set<String> callbackClasses) {
3306 println("IoTRMICall *rmiCall;");
3307 // Get the object Id
3308 println("int objectId;");
3309 if (callbackExist) {
3310 // We assume that each class only has one callback interface for now
3311 Iterator it = callbackClasses.iterator();
3312 String callbackType = (String) it.next();
3313 println("// Callback properties");
3314 println("IoTRMIObject *rmiObj;");
3315 println("vector<" + callbackType + "*> vecCallbackObj;");
3316 println("static int objIdCnt;");
3317 // TODO: Need to initialize address and ports if we want to have callback-in-callback
3318 println("string address;");
3319 println("vector<int> ports;\n");
3320 writePropertiesCplusPermission(callbackType);
3327 * HELPER: writeConstructorCplusCallbackStub() writes the constructor of the stub class
3329 private void writeConstructorCplusCallbackStub(String newStubClass, boolean callbackExist, Set<String> callbackClasses) {
3331 println(newStubClass + "(IoTRMICall* _rmiCall, int _objectId) {");
3332 println("objectId = _objectId;");
3333 println("rmiCall = _rmiCall;");
3334 if (callbackExist) {
3335 Iterator it = callbackClasses.iterator();
3336 String callbackType = (String) it.next();
3337 println("thread th1 (&" + newStubClass + "::___initCallBack, this);");
3338 println("th1.detach();");
3339 println("___regCB();");
3346 * generateCPlusCallbackStubClasses() generate callback stubs based on the methods list in C++
3348 public void generateCPlusCallbackStubClasses() throws IOException {
3350 // Create a new directory
3351 String path = createDirectories(dir, subdir);
3352 for (String intface : mapIntfacePTH.keySet()) {
3354 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3355 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3356 // Open a new file to write into
3357 String newIntface = intMeth.getKey();
3358 String newStubClass = newIntface + "_CallbackStub";
3359 FileWriter fw = new FileWriter(path + "/" + newStubClass + ".hpp");
3360 pw = new PrintWriter(new BufferedWriter(fw));
3361 // Find out if there are callback objects
3362 Set<String> methods = intMeth.getValue();
3363 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
3364 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
3365 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
3366 boolean callbackExist = !callbackClasses.isEmpty();
3367 // Write file headers
3368 println("#ifndef _" + newStubClass.toUpperCase() + "_HPP__");
3369 println("#define _" + newStubClass.toUpperCase() + "_HPP__");
3370 println("#include <iostream>");
3372 println("#include <thread>");
3373 println("#include \"" + newIntface + ".hpp\""); println("");
3374 println("using namespace std;"); println("");
3375 println("class " + newStubClass + " : public " + newIntface); println("{");
3376 println("private:\n");
3377 writePropertiesCplusCallbackStub(intface, newIntface, callbackExist, callbackClasses);
3378 println("public:\n");
3379 // Add default constructor and destructor
3380 println(newStubClass + "() { }"); println("");
3381 writeConstructorCplusCallbackStub(newStubClass, callbackExist, callbackClasses);
3382 writeDeconstructorCplusStub(newStubClass, callbackExist, callbackClasses);
3384 writeMethodCplusStub(methods, intDecl, callbackClasses);
3386 if (callbackExist) {
3387 Iterator it = callbackClasses.iterator();
3388 String callbackType = (String) it.next();
3389 // Generate permission stuff for callback stubs
3390 DeclarationHandler decHandlerCallback = mapIntDeclHand.get(callbackType);
3391 InterfaceDecl intDeclCallback = (InterfaceDecl) decHandlerCallback.getInterfaceDecl(callbackType);
3392 writePermissionInitializationCplus(callbackType, newStubClass, intDeclCallback);
3394 writeObjectIdCountInitializationCplus(newStubClass, callbackExist);
3397 System.out.println("IoTCompiler: Generated callback stub class " + newIntface + ".hpp...");
3404 * HELPER: writePropertiesCplusSkeleton() writes the properties of the skeleton class
3406 private void writePropertiesCplusSkeleton(String intface, boolean callbackExist, Set<String> callbackClasses) {
3408 println(intface + " *mainObj;");
3410 if (callbackExist) {
3411 Iterator it = callbackClasses.iterator();
3412 String callbackType = (String) it.next();
3413 String exchangeType = checkAndGetParamClass(callbackType);
3414 println("// Callback properties");
3415 println("static int objIdCnt;");
3416 println("vector<" + exchangeType + "*> vecCallbackObj;");
3417 println("IoTRMICall *rmiCall;");
3419 println("IoTRMIObject *rmiObj;\n");
3420 // Keep track of object Ids of all stubs registered to this interface
3421 writePropertiesCplusPermission(intface);
3427 * HELPER: writeObjectIdCountInitializationCplus() writes the initialization of objIdCnt variable
3429 private void writeObjectIdCountInitializationCplus(String newSkelClass, boolean callbackExist) {
3432 println("int " + newSkelClass + "::objIdCnt = 0;");
3437 * HELPER: writePermissionInitializationCplus() writes the initialization of permission set
3439 private void writePermissionInitializationCplus(String intface, String newSkelClass, InterfaceDecl intDecl) {
3441 // Keep track of object Ids of all stubs registered to this interface
3442 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3443 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3444 String newIntface = intMeth.getKey();
3445 int newObjectId = getNewIntfaceObjectId(newIntface);
3446 print("set<int> " + newSkelClass + "::set" + newObjectId + "Allowed { ");
3447 Set<String> methodIds = intMeth.getValue();
3449 for (String methodId : methodIds) {
3450 int methodNumId = intDecl.getMethodNumId(methodId);
3451 print(Integer.toString(methodNumId));
3452 // Check if this is the last element (don't print a comma)
3453 if (i != methodIds.size() - 1) {
3464 * HELPER: writeStructPermissionCplusSkeleton() writes permission for struct helper
3466 private void writeStructPermissionCplusSkeleton(Collection<String> methods, InterfaceDecl intDecl, String intface) {
3468 // Use this set to handle two same methodIds
3469 for (String method : methods) {
3470 List<String> methParams = intDecl.getMethodParams(method);
3471 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
3472 // Check for params with structs
3473 for (int i = 0; i < methParams.size(); i++) {
3474 String paramType = methPrmTypes.get(i);
3475 String param = methParams.get(i);
3476 String simpleType = getGenericType(paramType);
3477 if (isStructClass(simpleType)) {
3478 int methodNumId = intDecl.getMethodNumId(method);
3479 String helperMethod = methodNumId + "struct" + i;
3480 int helperMethodNumId = intDecl.getHelperMethodNumId(helperMethod);
3481 // Iterate over interfaces to give permissions to
3482 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3483 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3484 String newIntface = intMeth.getKey();
3485 int newObjectId = getNewIntfaceObjectId(newIntface);
3486 println("set" + newObjectId + "Allowed.insert(" + helperMethodNumId + ");");
3495 * HELPER: writeConstructorCplusSkeleton() writes the constructor of the skeleton class
3497 private void writeConstructorCplusSkeleton(String newSkelClass, String intface, boolean callbackExist, InterfaceDecl intDecl, Collection<String> methods) {
3499 println(newSkelClass + "(" + intface + " *_mainObj, int _port) {");
3500 println("bool _bResult = false;");
3501 println("mainObj = _mainObj;");
3502 println("rmiObj = new IoTRMIObject(_port, &_bResult);");
3503 writeCplusInitCallbackPermission(intface, intDecl, callbackExist);
3504 writeStructPermissionCplusSkeleton(methods, intDecl, intface);
3505 println("___waitRequestInvokeMethod();");
3511 * HELPER: writeDeconstructorCplusSkeleton() writes the deconstructor of the skeleton class
3513 private void writeDeconstructorCplusSkeleton(String newSkelClass, boolean callbackExist, Set<String> callbackClasses) {
3515 println("~" + newSkelClass + "() {");
3516 println("if (rmiObj != NULL) {");
3517 println("delete rmiObj;");
3518 println("rmiObj = NULL;");
3520 if (callbackExist) {
3521 // We assume that each class only has one callback interface for now
3522 println("if (rmiCall != NULL) {");
3523 println("delete rmiCall;");
3524 println("rmiCall = NULL;");
3526 Iterator it = callbackClasses.iterator();
3527 String callbackType = (String) it.next();
3528 String exchangeType = checkAndGetParamClass(callbackType);
3529 println("for(" + exchangeType + "* cb : vecCallbackObj) {");
3530 println("delete cb;");
3531 println("cb = NULL;");
3540 * HELPER: writeStdMethodBodyCplusSkeleton() writes the standard method body in the skeleton class
3542 private void writeStdMethodBodyCplusSkeleton(List<String> methParams, String methodId, String methodType) {
3544 if (methodType.equals("void"))
3545 print("mainObj->" + methodId + "(");
3547 print("return mainObj->" + methodId + "(");
3548 for (int i = 0; i < methParams.size(); i++) {
3550 print(getSimpleIdentifier(methParams.get(i)));
3551 // Check if this is the last element (don't print a comma)
3552 if (i != methParams.size() - 1) {
3561 * HELPER: writeInitCallbackCplusSkeleton() writes the init callback method for skeleton class
3563 private void writeInitCallbackCplusSkeleton(boolean callbackSkeleton) {
3565 // This is a callback skeleton generation
3566 if (callbackSkeleton)
3567 println("void ___regCB(IoTRMIObject* rmiObj) {");
3569 println("void ___regCB() {");
3570 println("int numParam = 3;");
3571 println("int param1 = 0;");
3572 println("string param2 = \"\";");
3573 println("int param3 = 0;");
3574 println("string paramCls[] = { \"int\", \"String\", \"int\" };");
3575 println("void* paramObj[] = { ¶m1, ¶m2, ¶m3 };");
3576 println("rmiObj->getMethodParams(paramCls, numParam, paramObj);");
3577 println("bool bResult = false;");
3578 println("rmiCall = new IoTRMICall(param1, param2.c_str(), param3, &bResult);");
3584 * HELPER: writeMethodCplusSkeleton() writes the method of the skeleton class
3586 private void writeMethodCplusSkeleton(Collection<String> methods, InterfaceDecl intDecl,
3587 Set<String> callbackClasses, boolean callbackSkeleton) {
3589 boolean isDefined = false;
3590 for (String method : methods) {
3592 List<String> methParams = intDecl.getMethodParams(method);
3593 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
3594 String methodId = intDecl.getMethodId(method);
3595 String methodType = checkAndGetCplusType(intDecl.getMethodType(method));
3596 print(methodType + " " + methodId + "(");
3597 boolean isCallbackMethod = false;
3598 String callbackType = null;
3599 for (int i = 0; i < methParams.size(); i++) {
3601 String origParamType = methPrmTypes.get(i);
3602 if (callbackClasses.contains(origParamType)) { // Check if this has callback object
3603 isCallbackMethod = true;
3604 callbackType = origParamType;
3606 String paramType = checkAndGetParamClass(methPrmTypes.get(i));
3607 String methPrmType = checkAndGetCplusType(paramType);
3608 String methParamComplete = checkAndGetCplusArray(methPrmType, methParams.get(i));
3609 print(methParamComplete);
3610 // Check if this is the last element (don't print a comma)
3611 if (i != methParams.size() - 1) {
3616 // Now, write the body of skeleton!
3617 writeStdMethodBodyCplusSkeleton(methParams, methodId, intDecl.getMethodType(method));
3619 if (isCallbackMethod && !isDefined) {
3620 writeInitCallbackCplusSkeleton(callbackSkeleton);
3628 * HELPER: writeCallbackCplusNumStubs() writes the numStubs variable
3630 private void writeCallbackCplusNumStubs(List<String> methParams, List<String> methPrmTypes, String callbackType) {
3632 for (int i = 0; i < methParams.size(); i++) {
3633 String paramType = methPrmTypes.get(i);
3634 String param = methParams.get(i);
3635 //if (callbackType.equals(paramType)) {
3636 if (checkCallbackType(paramType, callbackType)) // Check if this has callback object
3637 println("int numStubs" + i + " = 0;");
3643 * HELPER: writeCallbackCplusStubGeneration() writes the callback stub generation part
3645 private void writeCallbackCplusStubGeneration(List<String> methParams, List<String> methPrmTypes, String callbackType) {
3647 // Iterate over callback objects
3648 for (int i = 0; i < methParams.size(); i++) {
3649 String paramType = methPrmTypes.get(i);
3650 String param = methParams.get(i);
3651 // Generate a loop if needed
3652 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
3653 String exchParamType = checkAndGetParamClass(getGenericType(paramType));
3654 if (isArrayOrList(paramType, param)) {
3655 println("vector<" + exchParamType + "*> stub" + i + ";");
3656 println("for (int objId = 0; objId < numStubs" + i + "; objId++) {");
3657 println(exchParamType + "* cb" + i + " = new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt);");
3658 println("stub" + i + ".push_back(cb" + i + ");");
3659 println("vecCallbackObj.push_back(cb" + i + ");");
3660 println("objIdCnt++;");
3663 println(exchParamType + "* stub" + i + " = new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt);");
3664 println("vecCallbackObj.push_back(stub" + i + ");");
3665 println("objIdCnt++;");
3673 * HELPER: checkAndWriteEnumTypeCplusSkeleton() writes the enum type (convert from enum to int)
3675 private void checkAndWriteEnumTypeCplusSkeleton(List<String> methParams, List<String> methPrmTypes) {
3677 // Iterate and find enum declarations
3678 for (int i = 0; i < methParams.size(); i++) {
3679 String paramType = methPrmTypes.get(i);
3680 String param = methParams.get(i);
3681 String simpleType = getGenericType(paramType);
3682 if (isEnumClass(simpleType)) {
3683 // Check if this is enum type
3684 if (isArrayOrList(paramType, param)) { // An array
3685 println("int len" + i + " = paramEnumInt" + i + ".size();");
3686 println("vector<" + simpleType + "> paramEnum" + i + "(len" + i + ");");
3687 println("for (int i=0; i < len" + i + "; i++) {");
3688 println("paramEnum" + i + "[i] = (" + simpleType + ") paramEnumInt" + i + "[i];");
3690 } else { // Just one element
3691 println(simpleType + " paramEnum" + i + ";");
3692 println("paramEnum" + i + " = (" + simpleType + ") paramEnumInt" + i + "[0];");
3700 * HELPER: checkAndWriteEnumRetTypeCplusSkeleton() writes the enum return type (convert from enum to int)
3702 private void checkAndWriteEnumRetTypeCplusSkeleton(String retType) {
3704 // Strips off array "[]" for return type
3705 String pureType = getSimpleArrayType(getGenericType(retType));
3706 // Take the inner type of generic
3707 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
3708 pureType = getGenericType(retType);
3709 if (isEnumClass(pureType)) {
3710 // Check if this is enum type
3712 if (isArrayOrList(retType, retType)) { // An array
3713 println("int retLen = retEnum.size();");
3714 println("vector<int> retEnumInt(retLen);");
3715 println("for (int i=0; i < retLen; i++) {");
3716 println("retEnumInt[i] = (int) retEnum[i];");
3718 } else { // Just one element
3719 println("vector<int> retEnumInt(1);");
3720 println("retEnumInt[0] = (int) retEnum;");
3727 * HELPER: writeMethodInputParameters() writes the parameter variables for C++ skeleton
3729 private void writeMethodInputParameters(List<String> methParams, List<String> methPrmTypes,
3730 Set<String> callbackClasses, String methodId) {
3732 print(methodId + "(");
3733 for (int i = 0; i < methParams.size(); i++) {
3734 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
3735 if (callbackClasses.contains(paramType))
3737 else if (isEnumClass(getGenericType(paramType))) // Check if this is enum type
3738 print("paramEnum" + i);
3739 else if (isStructClass(getGenericType(paramType))) // Struct type
3740 print("paramStruct" + i);
3742 print(getSimpleIdentifier(methParams.get(i)));
3743 if (i != methParams.size() - 1) {
3752 * HELPER: writeMethodHelperReturnCplusSkeleton() writes the return statement part in skeleton
3754 private void writeMethodHelperReturnCplusSkeleton(InterfaceDecl intDecl, List<String> methParams,
3755 List<String> methPrmTypes, String method, boolean isCallbackMethod, String callbackType,
3756 String methodId, Set<String> callbackClasses) {
3758 println("rmiObj->getMethodParams(paramCls, numParam, paramObj);");
3759 if (isCallbackMethod)
3760 writeCallbackCplusStubGeneration(methParams, methPrmTypes, callbackType);
3761 checkAndWriteEnumTypeCplusSkeleton(methParams, methPrmTypes);
3762 writeStructMembersInitCplusSkeleton(intDecl, methParams, methPrmTypes, method);
3763 // Check if this is "void"
3764 String retType = intDecl.getMethodType(method);
3765 // Check if this is "void"
3766 if (retType.equals("void")) {
3767 writeMethodInputParameters(methParams, methPrmTypes, callbackClasses, methodId);
3768 } else { // We do have a return value
3769 if (isEnumClass(getSimpleArrayType(getGenericType(retType)))) // Enum type
3770 print(checkAndGetCplusType(retType) + " retEnum = ");
3771 else if (isStructClass(getSimpleArrayType(getGenericType(retType)))) // Struct type
3772 print(checkAndGetCplusType(retType) + " retStruct = ");
3774 print(checkAndGetCplusType(retType) + " retVal = ");
3775 writeMethodInputParameters(methParams, methPrmTypes, callbackClasses, methodId);
3776 checkAndWriteEnumRetTypeCplusSkeleton(retType);
3777 if (isStructClass(getSimpleArrayType(getGenericType(retType)))) // Struct type
3778 writeStructReturnCplusSkeleton(getSimpleArrayType(getGenericType(retType)), retType);
3779 if (isEnumClass(getSimpleArrayType(getGenericType(retType)))) // Enum type
3780 println("void* retObj = &retEnumInt;");
3782 if (!isStructClass(getSimpleArrayType(getGenericType(retType)))) // Struct type
3783 println("void* retObj = &retVal;");
3784 String retTypeC = checkAndGetCplusType(retType);
3785 if (isStructClass(getSimpleArrayType(getGenericType(retType)))) // Struct type
3786 println("rmiObj->sendReturnObj(retObj, retCls, numRetObj);");
3788 println("rmiObj->sendReturnObj(retObj, \"" + checkAndGetCplusRetClsType(getEnumType(retType)) + "\");");
3794 * HELPER: writeStdMethodHelperBodyCplusSkeleton() writes the standard method body helper in the skeleton class
3796 private void writeStdMethodHelperBodyCplusSkeleton(InterfaceDecl intDecl, List<String> methParams,
3797 List<String> methPrmTypes, String method, String methodId, Set<String> callbackClasses) {
3799 // Generate array of parameter types
3800 boolean isCallbackMethod = false;
3801 String callbackType = null;
3802 print("string paramCls[] = { ");
3803 for (int i = 0; i < methParams.size(); i++) {
3804 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
3805 if (callbackClasses.contains(paramType)) {
3806 isCallbackMethod = true;
3807 callbackType = paramType;
3809 } else { // Generate normal classes if it's not a callback object
3810 String paramTypeC = checkAndGetCplusArgClsType(methPrmTypes.get(i), methParams.get(i));
3811 print("\"" + paramTypeC + "\"");
3813 if (i != methParams.size() - 1) {
3818 println("int numParam = " + methParams.size() + ";");
3819 if (isCallbackMethod)
3820 writeCallbackCplusNumStubs(methParams, methPrmTypes, callbackType);
3821 // Generate parameters
3822 for (int i = 0; i < methParams.size(); i++) {
3823 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
3824 if (!callbackClasses.contains(paramType)) {
3825 String methParamType = methPrmTypes.get(i);
3826 if (isEnumClass(getSimpleArrayType(getGenericType(methParamType)))) {
3827 // Check if this is enum type
3828 println("vector<int> paramEnumInt" + i + ";");
3830 String methPrmType = checkAndGetCplusType(methParamType);
3831 String methParamComplete = checkAndGetCplusArray(methPrmType, methParams.get(i));
3832 println(methParamComplete + ";");
3836 // Generate array of parameter objects
3837 print("void* paramObj[] = { ");
3838 for (int i = 0; i < methParams.size(); i++) {
3839 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
3840 if (callbackClasses.contains(paramType))
3841 print("&numStubs" + i);
3842 else if (isEnumClass(getGenericType(paramType))) // Check if this is enum type
3843 print("¶mEnumInt" + i);
3845 print("&" + getSimpleIdentifier(methParams.get(i)));
3846 if (i != methParams.size() - 1) {
3851 // Write the return value part
3852 writeMethodHelperReturnCplusSkeleton(intDecl, methParams, methPrmTypes, method, isCallbackMethod,
3853 callbackType, methodId, callbackClasses);
3858 * HELPER: writeStructMembersCplusSkeleton() writes member parameters of struct
3860 private void writeStructMembersCplusSkeleton(String simpleType, String paramType,
3861 String param, String method, InterfaceDecl intDecl, int iVar) {
3863 // Get the struct declaration for this struct and generate initialization code
3864 StructDecl structDecl = getStructDecl(simpleType);
3865 List<String> memTypes = structDecl.getMemberTypes(simpleType);
3866 List<String> members = structDecl.getMembers(simpleType);
3867 int methodNumId = intDecl.getMethodNumId(method);
3868 String counter = "struct" + methodNumId + "Size" + iVar;
3870 if (isArrayOrList(paramType, param)) { // An array or list
3871 for (int i = 0; i < members.size(); i++) {
3872 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
3873 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
3874 println(getSimpleType(getEnumType(prmType)) + " param" + iVar + i + "[" + counter + "];");
3876 } else { // Just one struct element
3877 for (int i = 0; i < members.size(); i++) {
3878 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
3879 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
3880 println(getSimpleType(getEnumType(prmType)) + " param" + iVar + i + ";");
3883 if (isArrayOrList(paramType, param)) { // An array or list
3884 println("for(int i = 0; i < " + counter + "; i++) {");
3886 if (isArrayOrList(paramType, param)) { // An array or list
3887 for (int i = 0; i < members.size(); i++) {
3888 String prmTypeC = checkAndGetCplusArgClsType(memTypes.get(i), members.get(i));
3889 println("paramCls[pos] = \"" + prmTypeC + "\";");
3890 println("paramObj[pos++] = ¶m" + iVar + i + "[i];");
3893 } else { // Just one struct element
3894 for (int i = 0; i < members.size(); i++) {
3895 String prmTypeC = checkAndGetCplusArgClsType(memTypes.get(i), members.get(i));
3896 println("paramCls[pos] = \"" + prmTypeC + "\";");
3897 println("paramObj[pos++] = ¶m" + iVar + i + ";");
3904 * HELPER: writeStructMembersInitCplusSkeleton() writes member parameters initialization of struct
3906 private void writeStructMembersInitCplusSkeleton(InterfaceDecl intDecl, List<String> methParams,
3907 List<String> methPrmTypes, String method) {
3909 for (int i = 0; i < methParams.size(); i++) {
3910 String paramType = methPrmTypes.get(i);
3911 String param = methParams.get(i);
3912 String simpleType = getGenericType(paramType);
3913 if (isStructClass(simpleType)) {
3914 int methodNumId = intDecl.getMethodNumId(method);
3915 String counter = "struct" + methodNumId + "Size" + i;
3917 if (isArrayOrList(paramType, param)) { // An array or list
3918 println("vector<" + simpleType + "> paramStruct" + i + "(" + counter + ");");
3920 println(simpleType + " paramStruct" + i + ";");
3921 // Initialize members
3922 StructDecl structDecl = getStructDecl(simpleType);
3923 List<String> members = structDecl.getMembers(simpleType);
3924 List<String> memTypes = structDecl.getMemberTypes(simpleType);
3925 if (isArrayOrList(paramType, param)) { // An array or list
3926 println("for(int i = 0; i < " + counter + "; i++) {");
3927 for (int j = 0; j < members.size(); j++) {
3928 print("paramStruct" + i + "[i]." + getSimpleIdentifier(members.get(j)));
3929 println(" = param" + i + j + "[i];");
3932 } else { // Just one struct element
3933 for (int j = 0; j < members.size(); j++) {
3934 print("paramStruct" + i + "." + getSimpleIdentifier(members.get(j)));
3935 println(" = param" + i + j + ";");
3944 * HELPER: writeStructReturnCplusSkeleton() writes parameters of struct for return statement
3946 private void writeStructReturnCplusSkeleton(String simpleType, String retType) {
3948 // Minimum retLen is 1 if this is a single struct object
3949 if (isArrayOrList(retType, retType))
3950 println("int retLen = retStruct.size();");
3951 else // Just single struct object
3952 println("int retLen = 1;");
3953 println("void* retLenObj = &retLen;");
3954 println("rmiObj->sendReturnObj(retLenObj, \"int\");");
3955 int numMem = getNumOfMembers(simpleType);
3956 println("int numRetObj = " + numMem + "*retLen;");
3957 println("string retCls[numRetObj];");
3958 println("void* retObj[numRetObj];");
3959 println("int retPos = 0;");
3960 // Get the struct declaration for this struct and generate initialization code
3961 StructDecl structDecl = getStructDecl(simpleType);
3962 List<String> memTypes = structDecl.getMemberTypes(simpleType);
3963 List<String> members = structDecl.getMembers(simpleType);
3964 if (isArrayOrList(retType, retType)) { // An array or list
3965 println("for(int i = 0; i < retLen; i++) {");
3966 for (int i = 0; i < members.size(); i++) {
3967 String prmTypeC = checkAndGetCplusArgClsType(memTypes.get(i), members.get(i));
3968 println("retCls[retPos] = \"" + prmTypeC + "\";");
3969 print("retObj[retPos++] = &retStruct[i].");
3970 print(getEnumParam(memTypes.get(i), getSimpleIdentifier(members.get(i)), i));
3974 } else { // Just one struct element
3975 for (int i = 0; i < members.size(); i++) {
3976 String prmTypeC = checkAndGetCplusArgClsType(memTypes.get(i), members.get(i));
3977 println("retCls[retPos] = \"" + prmTypeC + "\";");
3978 print("retObj[retPos++] = &retStruct.");
3979 print(getEnumParam(memTypes.get(i), getSimpleIdentifier(members.get(i)), i));
3988 * HELPER: writeMethodHelperStructCplusSkeleton() writes the struct in skeleton
3990 private void writeMethodHelperStructCplusSkeleton(InterfaceDecl intDecl, List<String> methParams,
3991 List<String> methPrmTypes, String method, String methodId, Set<String> callbackClasses) {
3993 // Generate array of parameter objects
3994 boolean isCallbackMethod = false;
3995 String callbackType = null;
3996 print("int numParam = ");
3997 writeLengthStructParamClassSkeleton(methParams, methPrmTypes, method, intDecl);
3999 println("string paramCls[numParam];");
4000 println("void* paramObj[numParam];");
4001 println("int pos = 0;");
4002 // Iterate again over the parameters
4003 for (int i = 0; i < methParams.size(); i++) {
4004 String paramType = methPrmTypes.get(i);
4005 String param = methParams.get(i);
4006 String simpleType = getGenericType(paramType);
4007 if (isStructClass(simpleType)) {
4008 writeStructMembersCplusSkeleton(simpleType, paramType, param, method, intDecl, i);
4010 String prmType = returnGenericCallbackType(methPrmTypes.get(i));
4011 if (callbackClasses.contains(prmType)) {
4012 isCallbackMethod = true;
4013 callbackType = prmType;
4014 println("int numStubs" + i + " = 0;");
4015 println("paramCls[pos] = \"int\";");
4016 println("paramObj[pos++] = &numStubs" + i + ";");
4017 } else { // Generate normal classes if it's not a callback object
4018 String paramTypeC = checkAndGetCplusType(methPrmTypes.get(i));
4019 if (isEnumClass(getGenericType(paramTypeC))) { // Check if this is enum type
4020 println("vector<int> paramEnumInt" + i + ";");
4022 String methParamComplete = checkAndGetCplusArray(paramTypeC, methParams.get(i));
4023 println(methParamComplete + ";");
4025 String prmTypeC = checkAndGetCplusArgClsType(methPrmTypes.get(i), methParams.get(i));
4026 println("paramCls[pos] = \"" + prmTypeC + "\";");
4027 if (isEnumClass(getGenericType(paramType))) // Check if this is enum type
4028 println("paramObj[pos++] = ¶mEnumInt" + i + ";");
4030 println("paramObj[pos++] = &" + getSimpleIdentifier(methParams.get(i)) + ";");
4034 // Write the return value part
4035 writeMethodHelperReturnCplusSkeleton(intDecl, methParams, methPrmTypes, method, isCallbackMethod,
4036 callbackType, methodId, callbackClasses);
4041 * HELPER: writeMethodHelperCplusSkeleton() writes the method helper of the skeleton class
4043 private void writeMethodHelperCplusSkeleton(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
4045 // Use this set to handle two same methodIds
4046 Set<String> uniqueMethodIds = new HashSet<String>();
4047 for (String method : methods) {
4049 List<String> methParams = intDecl.getMethodParams(method);
4050 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4051 if (isStructPresent(methParams, methPrmTypes)) { // Treat struct differently
4052 String methodId = intDecl.getMethodId(method);
4054 String helperMethod = methodId;
4055 if (uniqueMethodIds.contains(methodId))
4056 helperMethod = helperMethod + intDecl.getMethodNumId(method);
4058 uniqueMethodIds.add(methodId);
4059 String retType = intDecl.getMethodType(method);
4060 print(helperMethod + "(");
4061 boolean begin = true;
4062 for (int i = 0; i < methParams.size(); i++) { // Print size variables
4063 String paramType = methPrmTypes.get(i);
4064 String param = methParams.get(i);
4065 String simpleType = getGenericType(paramType);
4066 if (isStructClass(simpleType)) {
4067 if (!begin) // Generate comma for not the beginning variable
4071 int methodNumId = intDecl.getMethodNumId(method);
4072 print("int struct" + methodNumId + "Size" + i);
4076 writeMethodHelperStructCplusSkeleton(intDecl, methParams, methPrmTypes, method, methodId, callbackClasses);
4079 String methodId = intDecl.getMethodId(method);
4081 String helperMethod = methodId;
4082 if (uniqueMethodIds.contains(methodId))
4083 helperMethod = helperMethod + intDecl.getMethodNumId(method);
4085 uniqueMethodIds.add(methodId);
4086 // Check if this is "void"
4087 String retType = intDecl.getMethodType(method);
4088 println(helperMethod + "() {");
4089 // Now, write the helper body of skeleton!
4090 writeStdMethodHelperBodyCplusSkeleton(intDecl, methParams, methPrmTypes, method, methodId, callbackClasses);
4094 // Write method helper for structs
4095 writeMethodHelperStructSetupCplusSkeleton(methods, intDecl);
4100 * HELPER: writeMethodHelperStructSetupCplusSkeleton() writes the method helper of struct in skeleton class
4102 private void writeMethodHelperStructSetupCplusSkeleton(Collection<String> methods,
4103 InterfaceDecl intDecl) {
4105 // Use this set to handle two same methodIds
4106 for (String method : methods) {
4108 List<String> methParams = intDecl.getMethodParams(method);
4109 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4110 // Check for params with structs
4111 for (int i = 0; i < methParams.size(); i++) {
4112 String paramType = methPrmTypes.get(i);
4113 String param = methParams.get(i);
4114 String simpleType = getGenericType(paramType);
4115 if (isStructClass(simpleType)) {
4116 int methodNumId = intDecl.getMethodNumId(method);
4118 String helperMethod = methodNumId + "struct" + i;
4119 println(helperMethod + "() {");
4120 // Now, write the helper body of skeleton!
4121 println("string paramCls[] = { \"int\" };");
4122 println("int numParam = 1;");
4123 println("int param0 = 0;");
4124 println("void* paramObj[] = { ¶m0 };");
4125 println("rmiObj->getMethodParams(paramCls, numParam, paramObj);");
4126 println("return param0;");
4135 * HELPER: writeMethodHelperStructSetupCplusCallbackSkeleton() writes the method helper of struct in skeleton class
4137 private void writeMethodHelperStructSetupCplusCallbackSkeleton(Collection<String> methods,
4138 InterfaceDecl intDecl) {
4140 // Use this set to handle two same methodIds
4141 for (String method : methods) {
4143 List<String> methParams = intDecl.getMethodParams(method);
4144 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4145 // Check for params with structs
4146 for (int i = 0; i < methParams.size(); i++) {
4147 String paramType = methPrmTypes.get(i);
4148 String param = methParams.get(i);
4149 String simpleType = getGenericType(paramType);
4150 if (isStructClass(simpleType)) {
4151 int methodNumId = intDecl.getMethodNumId(method);
4153 String helperMethod = methodNumId + "struct" + i;
4154 println(helperMethod + "(IoTRMIObject* rmiObj) {");
4155 // Now, write the helper body of skeleton!
4156 println("string paramCls[] = { \"int\" };");
4157 println("int numParam = 1;");
4158 println("int param0 = 0;");
4159 println("void* paramObj[] = { ¶m0 };");
4160 println("rmiObj->getMethodParams(paramCls, numParam, paramObj);");
4161 println("return param0;");
4170 * HELPER: writeCplusMethodPermission() writes permission checks in skeleton
4172 private void writeCplusMethodPermission(String intface) {
4174 // Get all the different stubs
4175 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
4176 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
4177 String newIntface = intMeth.getKey();
4178 int newObjectId = getNewIntfaceObjectId(newIntface);
4179 println("if (_objectId == object" + newObjectId + "Id) {");
4180 println("if (set" + newObjectId + "Allowed.find(methodId) == set" + newObjectId + "Allowed.end()) {");
4181 println("cerr << \"Object with object Id: \" << _objectId << \" is not allowed to access method: \" << methodId << endl;");
4186 println("cerr << \"Object Id: \" << _objectId << \" not recognized!\" << endl;");
4194 * HELPER: writeCplusWaitRequestInvokeMethod() writes the main loop of the skeleton class
4196 private void writeCplusWaitRequestInvokeMethod(Collection<String> methods, InterfaceDecl intDecl, boolean callbackExist, String intface) {
4198 // Use this set to handle two same methodIds
4199 Set<String> uniqueMethodIds = new HashSet<String>();
4200 println("void ___waitRequestInvokeMethod() {");
4201 // Write variables here if we have callbacks or enums or structs
4202 writeCountVarStructSkeleton(methods, intDecl);
4203 println("while (true) {");
4204 println("rmiObj->getMethodBytes();");
4205 println("int _objectId = rmiObj->getObjectId();");
4206 println("int methodId = rmiObj->getMethodId();");
4207 // Generate permission check
4208 writeCplusMethodPermission(intface);
4209 println("switch (methodId) {");
4210 // Print methods and method Ids
4211 for (String method : methods) {
4212 String methodId = intDecl.getMethodId(method);
4213 int methodNumId = intDecl.getMethodNumId(method);
4214 print("case " + methodNumId + ": ___");
4215 String helperMethod = methodId;
4216 if (uniqueMethodIds.contains(methodId))
4217 helperMethod = helperMethod + methodNumId;
4219 uniqueMethodIds.add(methodId);
4220 print(helperMethod + "(");
4221 writeInputCountVarStructSkeleton(method, intDecl);
4222 println("); break;");
4224 String method = "___initCallBack()";
4225 // Print case -9999 (callback handler) if callback exists
4226 if (callbackExist) {
4227 int methodId = intDecl.getHelperMethodNumId(method);
4228 println("case " + methodId + ": ___regCB(); break;");
4230 writeMethodCallStructSkeleton(methods, intDecl);
4231 println("default: ");
4232 println("cerr << \"Method Id \" << methodId << \" not recognized!\" << endl;");
4233 println("throw exception();");
4241 * generateCplusSkeletonClass() generate skeletons based on the methods list in C++
4243 public void generateCplusSkeletonClass() throws IOException {
4245 // Create a new directory
4246 String path = createDirectories(dir, subdir);
4247 for (String intface : mapIntfacePTH.keySet()) {
4248 // Open a new file to write into
4249 String newSkelClass = intface + "_Skeleton";
4250 FileWriter fw = new FileWriter(path + "/" + newSkelClass + ".hpp");
4251 pw = new PrintWriter(new BufferedWriter(fw));
4252 // Write file headers
4253 println("#ifndef _" + newSkelClass.toUpperCase() + "_HPP__");
4254 println("#define _" + newSkelClass.toUpperCase() + "_HPP__");
4255 println("#include <iostream>");
4256 println("#include \"" + intface + ".hpp\"\n");
4257 // Pass in set of methods and get import classes
4258 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4259 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
4260 List<String> methods = intDecl.getMethods();
4261 Set<String> includeClasses = getIncludeClasses(methods, intDecl, intface, true);
4262 List<String> stdIncludeClasses = getStandardCplusIncludeClasses();
4263 List<String> allIncludeClasses = getAllLibClasses(stdIncludeClasses, includeClasses);
4264 printIncludeStatements(allIncludeClasses); println("");
4265 println("using namespace std;\n");
4266 // Find out if there are callback objects
4267 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
4268 boolean callbackExist = !callbackClasses.isEmpty();
4269 // Write class header
4270 println("class " + newSkelClass + " : public " + intface); println("{");
4271 println("private:\n");
4273 writePropertiesCplusSkeleton(intface, callbackExist, callbackClasses);
4274 println("public:\n");
4275 // Write constructor
4276 writeConstructorCplusSkeleton(newSkelClass, intface, callbackExist, intDecl, methods);
4277 // Write deconstructor
4278 writeDeconstructorCplusSkeleton(newSkelClass, callbackExist, callbackClasses);
4280 writeMethodCplusSkeleton(methods, intDecl, callbackClasses, false);
4281 // Write method helper
4282 writeMethodHelperCplusSkeleton(methods, intDecl, callbackClasses);
4283 // Write waitRequestInvokeMethod() - main loop
4284 writeCplusWaitRequestInvokeMethod(methods, intDecl, callbackExist, intface);
4286 writePermissionInitializationCplus(intface, newSkelClass, intDecl);
4287 writeObjectIdCountInitializationCplus(newSkelClass, callbackExist);
4290 System.out.println("IoTCompiler: Generated skeleton class " + newSkelClass + ".hpp...");
4296 * HELPER: writePropertiesCplusCallbackSkeleton() writes the properties of the callback skeleton class
4298 private void writePropertiesCplusCallbackSkeleton(String intface, boolean callbackExist, Set<String> callbackClasses) {
4300 println(intface + " *mainObj;");
4301 // Keep track of object Ids of all stubs registered to this interface
4302 println("int objectId;");
4304 if (callbackExist) {
4305 Iterator it = callbackClasses.iterator();
4306 String callbackType = (String) it.next();
4307 String exchangeType = checkAndGetParamClass(callbackType);
4308 println("// Callback properties");
4309 println("IoTRMICall* rmiCall;");
4310 println("vector<" + exchangeType + "*> vecCallbackObj;");
4311 println("static int objIdCnt;");
4318 * HELPER: writeConstructorCplusCallbackSkeleton() writes the constructor of the skeleton class
4320 private void writeConstructorCplusCallbackSkeleton(String newSkelClass, String intface, boolean callbackExist, InterfaceDecl intDecl, Collection<String> methods) {
4322 println(newSkelClass + "(" + intface + " *_mainObj, int _objectId) {");
4323 println("mainObj = _mainObj;");
4324 println("objectId = _objectId;");
4330 * HELPER: writeDeconstructorCplusStub() writes the deconstructor of the stub class
4332 private void writeDeconstructorCplusCallbackSkeleton(String newStubClass, boolean callbackExist,
4333 Set<String> callbackClasses) {
4335 println("~" + newStubClass + "() {");
4336 if (callbackExist) {
4337 // We assume that each class only has one callback interface for now
4338 println("if (rmiCall != NULL) {");
4339 println("delete rmiCall;");
4340 println("rmiCall = NULL;");
4342 Iterator it = callbackClasses.iterator();
4343 String callbackType = (String) it.next();
4344 String exchangeType = checkAndGetParamClass(callbackType);
4345 println("for(" + exchangeType + "* cb : vecCallbackObj) {");
4346 println("delete cb;");
4347 println("cb = NULL;");
4356 * HELPER: writeMethodHelperCplusCallbackSkeleton() writes the method helper of callback skeleton class
4358 private void writeMethodHelperCplusCallbackSkeleton(Collection<String> methods, InterfaceDecl intDecl,
4359 Set<String> callbackClasses) {
4361 // Use this set to handle two same methodIds
4362 Set<String> uniqueMethodIds = new HashSet<String>();
4363 for (String method : methods) {
4365 List<String> methParams = intDecl.getMethodParams(method);
4366 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4367 if (isStructPresent(methParams, methPrmTypes)) { // Treat struct differently
4368 String methodId = intDecl.getMethodId(method);
4370 String helperMethod = methodId;
4371 if (uniqueMethodIds.contains(methodId))
4372 helperMethod = helperMethod + intDecl.getMethodNumId(method);
4374 uniqueMethodIds.add(methodId);
4375 String retType = intDecl.getMethodType(method);
4376 print(helperMethod + "(");
4377 boolean begin = true;
4378 for (int i = 0; i < methParams.size(); i++) { // Print size variables
4379 String paramType = methPrmTypes.get(i);
4380 String param = methParams.get(i);
4381 String simpleType = getGenericType(paramType);
4382 if (isStructClass(simpleType)) {
4383 if (!begin) // Generate comma for not the beginning variable
4387 int methodNumId = intDecl.getMethodNumId(method);
4388 print("int struct" + methodNumId + "Size" + i);
4391 println(", IoTRMIObject* rmiObj) {");
4392 writeMethodHelperStructCplusSkeleton(intDecl, methParams, methPrmTypes, method, methodId, callbackClasses);
4395 String methodId = intDecl.getMethodId(method);
4397 String helperMethod = methodId;
4398 if (uniqueMethodIds.contains(methodId))
4399 helperMethod = helperMethod + intDecl.getMethodNumId(method);
4401 uniqueMethodIds.add(methodId);
4402 // Check if this is "void"
4403 String retType = intDecl.getMethodType(method);
4404 println(helperMethod + "(IoTRMIObject* rmiObj) {");
4405 // Now, write the helper body of skeleton!
4406 writeStdMethodHelperBodyCplusSkeleton(intDecl, methParams, methPrmTypes, method, methodId, callbackClasses);
4410 // Write method helper for structs
4411 writeMethodHelperStructSetupCplusCallbackSkeleton(methods, intDecl);
4416 * HELPER: writeCplusCallbackWaitRequestInvokeMethod() writes the request invoke method of the skeleton callback class
4418 private void writeCplusCallbackWaitRequestInvokeMethod(Collection<String> methods, InterfaceDecl intDecl,
4419 boolean callbackExist) {
4421 // Use this set to handle two same methodIds
4422 Set<String> uniqueMethodIds = new HashSet<String>();
4423 println("void invokeMethod(IoTRMIObject* rmiObj) {");
4424 // Write variables here if we have callbacks or enums or structs
4425 writeCountVarStructSkeleton(methods, intDecl);
4426 // Write variables here if we have callbacks or enums or structs
4427 println("int methodId = rmiObj->getMethodId();");
4428 // TODO: code the permission check here!
4429 println("switch (methodId) {");
4430 // Print methods and method Ids
4431 for (String method : methods) {
4432 String methodId = intDecl.getMethodId(method);
4433 int methodNumId = intDecl.getMethodNumId(method);
4434 print("case " + methodNumId + ": ___");
4435 String helperMethod = methodId;
4436 if (uniqueMethodIds.contains(methodId))
4437 helperMethod = helperMethod + methodNumId;
4439 uniqueMethodIds.add(methodId);
4440 print(helperMethod + "(");
4441 if (writeInputCountVarStructSkeleton(method, intDecl))
4442 println(", rmiObj); break;");
4444 println("rmiObj); break;");
4446 String method = "___initCallBack()";
4447 // Print case -9999 (callback handler) if callback exists
4448 if (callbackExist) {
4449 int methodId = intDecl.getHelperMethodNumId(method);
4450 println("case " + methodId + ": ___regCB(rmiObj); break;");
4452 writeMethodCallStructCallbackSkeleton(methods, intDecl);
4453 println("default: ");
4454 println("cerr << \"Method Id \" << methodId << \" not recognized!\" << endl;");
4455 println("throw exception();");
4462 * generateCplusCallbackSkeletonClass() generate callback skeletons based on the methods list in C++
4464 public void generateCplusCallbackSkeletonClass() throws IOException {
4466 // Create a new directory
4467 String path = createDirectories(dir, subdir);
4468 for (String intface : mapIntfacePTH.keySet()) {
4469 // Open a new file to write into
4470 String newSkelClass = intface + "_CallbackSkeleton";
4471 FileWriter fw = new FileWriter(path + "/" + newSkelClass + ".hpp");
4472 pw = new PrintWriter(new BufferedWriter(fw));
4473 // Write file headers
4474 println("#ifndef _" + newSkelClass.toUpperCase() + "_HPP__");
4475 println("#define _" + newSkelClass.toUpperCase() + "_HPP__");
4476 println("#include <iostream>");
4477 println("#include \"" + intface + ".hpp\"\n");
4478 // Pass in set of methods and get import classes
4479 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4480 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
4481 List<String> methods = intDecl.getMethods();
4482 Set<String> includeClasses = getIncludeClasses(methods, intDecl, intface, true);
4483 List<String> stdIncludeClasses = getStandardCplusIncludeClasses();
4484 List<String> allIncludeClasses = getAllLibClasses(stdIncludeClasses, includeClasses);
4485 printIncludeStatements(allIncludeClasses); println("");
4486 // Find out if there are callback objects
4487 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
4488 boolean callbackExist = !callbackClasses.isEmpty();
4489 println("using namespace std;\n");
4490 // Write class header
4491 println("class " + newSkelClass + " : public " + intface); println("{");
4492 println("private:\n");
4494 writePropertiesCplusCallbackSkeleton(intface, callbackExist, callbackClasses);
4495 println("public:\n");
4496 // Write constructor
4497 writeConstructorCplusCallbackSkeleton(newSkelClass, intface, callbackExist, intDecl, methods);
4498 // Write deconstructor
4499 writeDeconstructorCplusCallbackSkeleton(newSkelClass, callbackExist, callbackClasses);
4501 writeMethodCplusSkeleton(methods, intDecl, callbackClasses, true);
4502 // Write method helper
4503 writeMethodHelperCplusCallbackSkeleton(methods, intDecl, callbackClasses);
4504 // Write waitRequestInvokeMethod() - main loop
4505 writeCplusCallbackWaitRequestInvokeMethod(methods, intDecl, callbackExist);
4507 writeObjectIdCountInitializationCplus(newSkelClass, callbackExist);
4510 System.out.println("IoTCompiler: Generated callback skeleton class " + newSkelClass + ".hpp...");
4516 * generateInitializer() generate initializer based on type
4518 public String generateCplusInitializer(String type) {
4520 // Generate dummy returns for now
4521 if (type.equals("short")||
4522 type.equals("int") ||
4523 type.equals("long") ||
4524 type.equals("float")||
4525 type.equals("double")) {
4528 } else if ( type.equals("String") ||
4529 type.equals("string")) {
4532 } else if ( type.equals("char") ||
4533 type.equals("byte")) {
4536 } else if ( type.equals("boolean")) {
4546 * setDirectory() sets a new directory for stub files
4548 public void setDirectory(String _subdir) {
4555 * printUsage() prints the usage of this compiler
4557 public static void printUsage() {
4559 System.out.println();
4560 System.out.println("Sentinel interface and stub compiler version 1.0");
4561 System.out.println("Copyright (c) 2015-2016 University of California, Irvine - Programming Language Group.");
4562 System.out.println("All rights reserved.");
4563 System.out.println("Usage:");
4564 System.out.println("\tjava IoTCompiler -help / --help / -h\n");
4565 System.out.println("\t\tDisplay this help texts\n\n");
4566 System.out.println("\tjava IoTCompiler [<main-policy-file> <req-policy-file>]");
4567 System.out.println("\tjava IoTCompiler [<main-policy-file> <req-policy-file>] [options]\n");
4568 System.out.println("\t\tTake one or more pairs of main-req policy files, and generate Java and/or C++ files\n");
4569 System.out.println("Options:");
4570 System.out.println("\t-java\t<directory>\tGenerate Java stub files");
4571 System.out.println("\t-cplus\t<directory>\tGenerate C++ stub files");
4572 System.out.println();
4577 * parseFile() prepares Lexer and Parser objects, then parses the file
4579 public static ParseNode parseFile(String file) {
4581 ParseNode pn = null;
4583 ComplexSymbolFactory csf = new ComplexSymbolFactory();
4584 ScannerBuffer lexer =
4585 new ScannerBuffer(new Lexer(new BufferedReader(new FileReader(file)),csf));
4586 Parser parse = new Parser(lexer,csf);
4587 pn = (ParseNode) parse.parse().value;
4588 } catch (Exception e) {
4589 e.printStackTrace();
4590 throw new Error("IoTCompiler: ERROR parsing policy file or wrong command line option: " + file + "\n");
4598 * Basic helper functions
4601 boolean newline=true;
4604 private void print(String str) {
4607 if (str.equals("}"))
4609 for(int i=0; i<tab; i++)
4619 * This function converts Java to C++ type for compilation
4621 private String convertType(String type) {
4623 if (mapPrimitives.containsKey(type))
4624 return mapPrimitives.get(type);
4631 * A collection of methods with print-to-file functionality
4633 private void println(String str) {
4636 if (str.contains("}") && !str.contains("{"))
4638 for(int i=0; i<tab; i++)
4647 private void updatetabbing(String str) {
4649 tablevel+=count(str,'{')-count(str,'}');
4653 private int count(String str, char key) {
4654 char[] array = str.toCharArray();
4656 for(int i=0; i<array.length; i++) {
4657 if (array[i] == key)
4664 private void createDirectory(String dirName) {
4666 File file = new File(dirName);
4667 if (!file.exists()) {
4669 System.out.println("IoTCompiler: Directory " + dirName + " has been created!");
4671 System.out.println("IoTCompiler: Failed to create directory " + dirName + "!");
4674 System.out.println("IoTCompiler: Directory " + dirName + " exists...");
4679 // Create a directory and possibly a sub directory
4680 private String createDirectories(String dir, String subdir) {
4683 createDirectory(path);
4684 if (subdir != null) {
4685 path = path + "/" + subdir;
4686 createDirectory(path);
4692 // Inserting array members into a Map object
4693 // that maps arrKey to arrVal objects
4694 private void arraysToMap(Map map, Object[] arrKey, Object[] arrVal) {
4696 for(int i = 0; i < arrKey.length; i++) {
4698 map.put(arrKey[i], arrVal[i]);
4703 // Check and find object Id for new interface in mapNewIntfaceObjId (callbacks)
4704 // Throw an error if the new interface is not found!
4705 // Basically the compiler needs to parse the policy (and requires) files for callback class first
4706 private int getNewIntfaceObjectId(String newIntface) {
4708 if (!mapNewIntfaceObjId.containsKey(newIntface)) {
4709 throw new Error("IoTCompiler: Need to parse policy and requires files for callback class first! " +
4710 "Please place the two files for callback class in front...\n");
4712 int retObjId = mapNewIntfaceObjId.get(newIntface);
4718 // Return parameter category, i.e. PRIMITIVES, NONPRIMITIVES, USERDEFINED, ENUM, or STRUCT
4719 private ParamCategory getParamCategory(String paramType) {
4721 if (mapPrimitives.containsKey(paramType)) {
4722 return ParamCategory.PRIMITIVES;
4723 // We can either use mapNonPrimitivesJava or mapNonPrimitivesCplus here
4724 } else if (mapNonPrimitivesJava.containsKey(getSimpleType(paramType))) {
4725 return ParamCategory.NONPRIMITIVES;
4726 } else if (isEnumClass(paramType)) {
4727 return ParamCategory.ENUM;
4728 } else if (isStructClass(paramType)) {
4729 return ParamCategory.STRUCT;
4731 return ParamCategory.USERDEFINED;
4735 // Return full class name for non-primitives to generate Java import statements
4736 // e.g. java.util.Set for Set
4737 private String getNonPrimitiveJavaClass(String paramNonPrimitives) {
4739 return mapNonPrimitivesJava.get(paramNonPrimitives);
4743 // Return full class name for non-primitives to generate Cplus include statements
4744 // e.g. #include <set> for Set
4745 private String getNonPrimitiveCplusClass(String paramNonPrimitives) {
4747 return mapNonPrimitivesCplus.get(paramNonPrimitives);
4751 // Get simple types, e.g. HashSet for HashSet<...>
4752 // Basically strip off the "<...>"
4753 private String getSimpleType(String paramType) {
4755 // Check if this is generics
4756 if(paramType.contains("<")) {
4757 String[] type = paramType.split("<");
4764 // Generate a set of standard classes for import statements
4765 private List<String> getStandardJavaIntfaceImportClasses() {
4767 List<String> importClasses = new ArrayList<String>();
4768 // Add the standard list first
4769 importClasses.add("java.util.List");
4770 importClasses.add("java.util.ArrayList");
4772 return importClasses;
4776 // Generate a set of standard classes for import statements
4777 private List<String> getStandardJavaImportClasses() {
4779 List<String> importClasses = new ArrayList<String>();
4780 // Add the standard list first
4781 importClasses.add("java.io.IOException");
4782 importClasses.add("java.util.List");
4783 importClasses.add("java.util.ArrayList");
4784 importClasses.add("java.util.Arrays");
4785 importClasses.add("iotrmi.Java.IoTRMICall");
4786 importClasses.add("iotrmi.Java.IoTRMIObject");
4788 return importClasses;
4792 // Generate a set of standard classes for import statements
4793 private List<String> getStandardCplusIncludeClasses() {
4795 List<String> importClasses = new ArrayList<String>();
4796 // Add the standard list first
4797 importClasses.add("<vector>");
4798 importClasses.add("<set>");
4799 importClasses.add("\"IoTRMICall.hpp\"");
4800 importClasses.add("\"IoTRMIObject.hpp\"");
4802 return importClasses;
4806 // Combine all classes for import statements
4807 private List<String> getAllLibClasses(Collection<String> stdLibClasses, Collection<String> libClasses) {
4809 List<String> allLibClasses = new ArrayList<String>(stdLibClasses);
4810 // Iterate over the list of import classes
4811 for (String str : libClasses) {
4812 if (!allLibClasses.contains(str)) {
4813 allLibClasses.add(str);
4816 return allLibClasses;
4821 // Generate a set of classes for import statements
4822 private Set<String> getImportClasses(Collection<String> methods, InterfaceDecl intDecl) {
4824 Set<String> importClasses = new HashSet<String>();
4825 for (String method : methods) {
4826 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4827 for (String paramType : methPrmTypes) {
4829 String simpleType = getSimpleType(paramType);
4830 if (getParamCategory(simpleType) == ParamCategory.NONPRIMITIVES) {
4831 importClasses.add(getNonPrimitiveJavaClass(simpleType));
4835 return importClasses;
4839 // Handle and return the correct enum declaration
4840 // In Java, if we declare enum in Camera interface, then it becomes "Camera.<enum>"
4841 private String getEnumParamDecl(String type, InterfaceDecl intDecl) {
4843 // Strips off array "[]" for return type
4844 String pureType = getSimpleArrayType(type);
4845 // Take the inner type of generic
4846 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
4847 pureType = getTypeOfGeneric(type)[0];
4848 if (isEnumClass(pureType)) {
4849 String enumType = intDecl.getInterface() + "." + type;
4856 // Handle and return the correct type
4857 private String getEnumParam(String type, String param, int i) {
4859 // Strips off array "[]" for return type
4860 String pureType = getSimpleArrayType(type);
4861 // Take the inner type of generic
4862 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
4863 pureType = getTypeOfGeneric(type)[0];
4864 if (isEnumClass(pureType)) {
4865 String enumParam = "paramEnum" + i;
4872 // Handle and return the correct enum declaration translate into int[]
4873 private String getEnumType(String type) {
4875 // Strips off array "[]" for return type
4876 String pureType = getSimpleArrayType(type);
4877 // Take the inner type of generic
4878 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
4879 pureType = getGenericType(type);
4880 if (isEnumClass(pureType)) {
4881 String enumType = "int[]";
4887 // Handle and return the correct enum declaration translate into int* for C
4888 private String getEnumCplusClsType(String type) {
4890 // Strips off array "[]" for return type
4891 String pureType = getSimpleArrayType(type);
4892 // Take the inner type of generic
4893 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
4894 pureType = getGenericType(type);
4895 if (isEnumClass(pureType)) {
4896 String enumType = "int*";
4903 // Handle and return the correct struct declaration
4904 private String getStructType(String type) {
4906 // Strips off array "[]" for return type
4907 String pureType = getSimpleArrayType(type);
4908 // Take the inner type of generic
4909 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
4910 pureType = getGenericType(type);
4911 if (isStructClass(pureType)) {
4912 String structType = "int";
4919 // Check if this an enum declaration
4920 private boolean isEnumClass(String type) {
4922 // Just iterate over the set of interfaces
4923 for (String intface : mapIntfacePTH.keySet()) {
4924 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4925 EnumDecl enumDecl = (EnumDecl) decHandler.getEnumDecl(intface);
4926 Set<String> setEnumDecl = enumDecl.getEnumDeclarations();
4927 if (setEnumDecl.contains(type))
4934 // Check if this an struct declaration
4935 private boolean isStructClass(String type) {
4937 // Just iterate over the set of interfaces
4938 for (String intface : mapIntfacePTH.keySet()) {
4939 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4940 StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
4941 List<String> listStructDecl = structDecl.getStructTypes();
4942 if (listStructDecl.contains(type))
4949 // Return a struct declaration
4950 private StructDecl getStructDecl(String type) {
4952 // Just iterate over the set of interfaces
4953 for (String intface : mapIntfacePTH.keySet()) {
4954 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4955 StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
4956 List<String> listStructDecl = structDecl.getStructTypes();
4957 if (listStructDecl.contains(type))
4964 // Return number of members (-1 if not found)
4965 private int getNumOfMembers(String type) {
4967 // Just iterate over the set of interfaces
4968 for (String intface : mapIntfacePTH.keySet()) {
4969 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4970 StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
4971 List<String> listStructDecl = structDecl.getStructTypes();
4972 if (listStructDecl.contains(type))
4973 return structDecl.getNumOfMembers(type);
4979 // Generate a set of classes for include statements
4980 private Set<String> getIncludeClasses(Collection<String> methods, InterfaceDecl intDecl, String intface, boolean needExchange) {
4982 Set<String> includeClasses = new HashSet<String>();
4983 for (String method : methods) {
4985 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4986 List<String> methParams = intDecl.getMethodParams(method);
4987 for (int i = 0; i < methPrmTypes.size(); i++) {
4989 String simpleType = getSimpleType(methPrmTypes.get(i));
4990 String param = methParams.get(i);
4991 if (getParamCategory(simpleType) == ParamCategory.NONPRIMITIVES) {
4992 includeClasses.add("<" + getNonPrimitiveCplusClass(simpleType) + ">");
4993 } else if (getParamCategory(simpleType) == ParamCategory.USERDEFINED) {
4994 // For original interface, we need it exchanged... not for stub interfaces
4996 includeClasses.add("\"" + exchangeParamType(simpleType) + ".hpp\"");
4997 includeClasses.add("\"" + exchangeParamType(simpleType) + "_CallbackStub.hpp\"");
4999 includeClasses.add("\"" + simpleType + ".hpp\"");
5000 includeClasses.add("\"" + simpleType + "_CallbackSkeleton.hpp\"");
5002 } else if (getParamCategory(getSimpleArrayType(simpleType)) == ParamCategory.ENUM) {
5003 includeClasses.add("\"" + simpleType + ".hpp\"");
5004 } else if (getParamCategory(getSimpleArrayType(simpleType)) == ParamCategory.STRUCT) {
5005 includeClasses.add("\"" + simpleType + ".hpp\"");
5006 } else if (param.contains("[]")) {
5007 // Check if this is array for C++; translate into vector
5008 includeClasses.add("<vector>");
5012 return includeClasses;
5016 // Generate a set of callback classes
5017 private Set<String> getCallbackClasses(Collection<String> methods, InterfaceDecl intDecl) {
5019 Set<String> callbackClasses = new HashSet<String>();
5020 for (String method : methods) {
5022 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
5023 List<String> methParams = intDecl.getMethodParams(method);
5024 for (int i = 0; i < methPrmTypes.size(); i++) {
5026 String type = methPrmTypes.get(i);
5027 if (getParamCategory(type) == ParamCategory.USERDEFINED) {
5028 callbackClasses.add(type);
5029 } else if (getParamCategory(type) == ParamCategory.NONPRIMITIVES) {
5030 // Can be a List<...> of callback objects ...
5031 String genericType = getTypeOfGeneric(type)[0];
5032 if (getParamCategory(type) == ParamCategory.USERDEFINED) {
5033 callbackClasses.add(type);
5038 return callbackClasses;
5042 // Print import statements into file
5043 private void printImportStatements(Collection<String> importClasses) {
5045 for(String cls : importClasses) {
5046 println("import " + cls + ";");
5051 // Print include statements into file
5052 private void printIncludeStatements(Collection<String> includeClasses) {
5054 for(String cls : includeClasses) {
5055 println("#include " + cls);
5060 // Get the C++ version of a non-primitive type
5061 // e.g. set for Set and map for Map
5062 // Input nonPrimitiveType has to be generics in format
5063 private String[] getTypeOfGeneric(String nonPrimitiveType) {
5065 // Handle <, >, and , for 2-type generic/template
5066 String[] substr = nonPrimitiveType.split("<")[1].split(">")[0].split(",");
5071 // Gets generic type inside "<" and ">"
5072 private String getGenericType(String type) {
5074 // Handle <, >, and , for 2-type generic/template
5075 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES) {
5076 String[] substr = type.split("<")[1].split(">")[0].split(",");
5083 // This helper function strips off array declaration, e.g. int[] becomes int
5084 private String getSimpleArrayType(String type) {
5086 // Handle [ for array declaration
5087 String substr = type;
5088 if (type.contains("[]")) {
5089 substr = type.split("\\[\\]")[0];
5095 // This helper function strips off array declaration, e.g. D[] becomes D
5096 private String getSimpleIdentifier(String ident) {
5098 // Handle [ for array declaration
5099 String substr = ident;
5100 if (ident.contains("[]")) {
5101 substr = ident.split("\\[\\]")[0];
5107 // Checks and gets type in C++
5108 private String checkAndGetCplusType(String paramType) {
5110 if (getParamCategory(paramType) == ParamCategory.PRIMITIVES) {
5111 return convertType(paramType);
5112 } else if (getParamCategory(paramType) == ParamCategory.NONPRIMITIVES) {
5114 // Check for generic/template format
5115 if (paramType.contains("<") && paramType.contains(">")) {
5117 String genericClass = getSimpleType(paramType);
5118 String genericType = getGenericType(paramType);
5119 String cplusTemplate = null;
5120 cplusTemplate = getNonPrimitiveCplusClass(genericClass);
5121 if(getParamCategory(getGenericType(paramType)) == ParamCategory.USERDEFINED) {
5122 cplusTemplate = cplusTemplate + "<" + genericType + "*>";
5124 cplusTemplate = cplusTemplate + "<" + convertType(genericType) + ">";
5126 return cplusTemplate;
5128 return getNonPrimitiveCplusClass(paramType);
5129 } else if(paramType.contains("[]")) { // Array type (used for return type only)
5130 String cArray = "vector<" + convertType(getSimpleArrayType(paramType)) + ">";
5132 } else if(getParamCategory(paramType) == ParamCategory.USERDEFINED) {
5133 return paramType + "*";
5135 // Just return it as is if it's not non-primitives
5140 // Detect array declaration, e.g. int A[],
5141 // then generate "int A[]" in C++ as "vector<int> A"
5142 private String checkAndGetCplusArray(String paramType, String param) {
5144 String paramComplete = null;
5145 // Check for array declaration
5146 if (param.contains("[]")) {
5147 paramComplete = "vector<" + paramType + "> " + param.replace("[]","");
5149 // Just return it as is if it's not an array
5150 paramComplete = paramType + " " + param;
5152 return paramComplete;
5156 // Detect array declaration, e.g. int A[],
5157 // then generate "int A[]" in C++ as "vector<int> A"
5158 // This method just returns the type
5159 private String checkAndGetCplusArrayType(String paramType) {
5161 String paramTypeRet = null;
5162 // Check for array declaration
5163 if (paramType.contains("[]")) {
5164 String type = paramType.split("\\[\\]")[0];
5165 paramTypeRet = checkAndGetCplusType(type) + "[]";
5166 } else if (paramType.contains("vector")) {
5167 // Just return it as is if it's not an array
5168 String type = paramType.split("<")[1].split(">")[0];
5169 paramTypeRet = checkAndGetCplusType(type) + "[]";
5171 paramTypeRet = paramType;
5173 return paramTypeRet;
5177 // Detect array declaration, e.g. int A[],
5178 // then generate "int A[]" in C++ as "vector<int> A"
5179 // This method just returns the type
5180 private String checkAndGetCplusArrayType(String paramType, String param) {
5182 String paramTypeRet = null;
5183 // Check for array declaration
5184 if (param.contains("[]")) {
5185 paramTypeRet = checkAndGetCplusType(paramType) + "[]";
5186 } else if (paramType.contains("vector")) {
5187 // Just return it as is if it's not an array
5188 String type = paramType.split("<")[1].split(">")[0];
5189 paramTypeRet = checkAndGetCplusType(type) + "[]";
5191 paramTypeRet = paramType;
5193 return paramTypeRet;
5197 // Return the class type for class resolution (for return value)
5198 // - Check and return C++ array class, e.g. int A[] into int*
5199 // - Check and return C++ vector class, e.g. List<Integer> A into vector<int>
5200 private String checkAndGetCplusRetClsType(String paramType) {
5202 String paramTypeRet = null;
5203 // Check for array declaration
5204 if (paramType.contains("[]")) {
5205 String type = paramType.split("\\[\\]")[0];
5206 paramTypeRet = getSimpleArrayType(type) + "*";
5207 } else if (paramType.contains("<") && paramType.contains(">")) {
5208 // Just return it as is if it's not an array
5209 String type = paramType.split("<")[1].split(">")[0];
5210 paramTypeRet = "vector<" + getGenericType(type) + ">";
5212 paramTypeRet = paramType;
5214 return paramTypeRet;
5218 // Return the class type for class resolution (for method arguments)
5219 // - Check and return C++ array class, e.g. int A[] into int*
5220 // - Check and return C++ vector class, e.g. List<Integer> A into vector<int>
5221 private String checkAndGetCplusArgClsType(String paramType, String param) {
5223 String paramTypeRet = getEnumCplusClsType(paramType);
5224 if (!paramTypeRet.equals(paramType))
5225 // Just return if it is an enum type
5226 // Type will still be the same if it's not an enum type
5227 return paramTypeRet;
5229 // Check for array declaration
5230 if (param.contains("[]")) {
5231 paramTypeRet = getSimpleArrayType(paramType) + "*";
5232 } else if (paramType.contains("<") && paramType.contains(">")) {
5233 // Just return it as is if it's not an array
5234 String type = paramType.split("<")[1].split(">")[0];
5235 paramTypeRet = "vector<" + getGenericType(type) + ">";
5237 paramTypeRet = paramType;
5239 return paramTypeRet;
5243 // Detect array declaration, e.g. int A[],
5244 // then generate type "int[]"
5245 private String checkAndGetArray(String paramType, String param) {
5247 String paramTypeRet = null;
5248 // Check for array declaration
5249 if (param.contains("[]")) {
5250 paramTypeRet = paramType + "[]";
5252 // Just return it as is if it's not an array
5253 paramTypeRet = paramType;
5255 return paramTypeRet;
5259 // Is array or list?
5260 private boolean isArrayOrList(String paramType, String param) {
5262 // Check for array declaration
5265 else if (isList(paramType))
5273 // For return type we use retType as input parameter
5274 private boolean isArray(String param) {
5276 // Check for array declaration
5277 if (param.contains("[]"))
5285 private boolean isList(String paramType) {
5287 // Check for array declaration
5288 if (paramType.contains("List"))
5295 // Get the right type for a callback object
5296 private String checkAndGetParamClass(String paramType) {
5298 // Check if this is generics
5299 if(getParamCategory(paramType) == ParamCategory.USERDEFINED) {
5300 return exchangeParamType(paramType);
5301 } else if (isList(paramType) &&
5302 (getParamCategory(getGenericType(paramType)) == ParamCategory.USERDEFINED)) {
5303 return "List<" + exchangeParamType(getGenericType(paramType)) + ">";
5309 // Returns the other interface for type-checking purposes for USERDEFINED
5310 // classes based on the information provided in multiple policy files
5311 // e.g. return CameraWithXXX instead of Camera
5312 private String exchangeParamType(String intface) {
5314 // Param type that's passed is the interface name we need to look for
5315 // in the map of interfaces, based on available policy files.
5316 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
5317 if (decHandler != null) {
5318 // We've found the required interface policy files
5319 RequiresDecl reqDecl = (RequiresDecl) decHandler.getRequiresDecl(intface);
5320 Set<String> setExchInt = reqDecl.getInterfaces();
5321 if (setExchInt.size() == 1) {
5322 Iterator iter = setExchInt.iterator();
5323 return (String) iter.next();
5325 throw new Error("IoTCompiler: Ambiguous stub interfaces: " + setExchInt.toString() +
5326 ". Only one new interface can be declared if the object " + intface +
5327 " needs to be passed in as an input parameter!\n");
5330 // NULL value - this means policy files missing
5331 throw new Error("IoTCompiler: Parameter type lookup failed for " + intface +
5332 "... Please provide the necessary policy files for user-defined types." +
5333 " If this is an array please type the brackets after the variable name," +
5334 " e.g. \"String str[]\", not \"String[] str\"." +
5335 " If this is a Collections (Java) / STL (C++) type, this compiler only" +
5336 " supports List/ArrayList (Java) or list (C++).\n");
5341 public static void main(String[] args) throws Exception {
5343 // If there is no argument or just "--help" or "-h", then invoke printUsage()
5344 if ((args[0].equals("-help") ||
5345 args[0].equals("--help")||
5346 args[0].equals("-h")) ||
5347 (args.length == 0)) {
5349 IoTCompiler.printUsage();
5351 } else if (args.length > 1) {
5353 IoTCompiler comp = new IoTCompiler();
5356 // Parse main policy file
5357 ParseNode pnPol = IoTCompiler.parseFile(args[i]);
5358 // Parse "requires" policy file
5359 ParseNode pnReq = IoTCompiler.parseFile(args[i+1]);
5360 // Get interface name
5361 String intface = ParseTreeHandler.getOrigIntface(pnPol);
5362 comp.setDataStructures(intface, pnPol, pnReq);
5363 comp.getMethodsForIntface(intface);
5365 // 1) Check if this is the last option before "-java" or "-cplus"
5366 // 2) Check if this is really the last option (no "-java" or "-cplus")
5367 } while(!args[i].equals("-java") &&
5368 !args[i].equals("-cplus") &&
5371 // Generate everything if we don't see "-java" or "-cplus"
5372 if (i == args.length) {
5373 comp.generateEnumJava();
5374 comp.generateStructJava();
5375 comp.generateJavaLocalInterfaces();
5376 comp.generateJavaInterfaces();
5377 comp.generateJavaStubClasses();
5378 comp.generateJavaCallbackStubClasses();
5379 comp.generateJavaSkeletonClass();
5380 comp.generateJavaCallbackSkeletonClass();
5381 comp.generateEnumCplus();
5382 comp.generateStructCplus();
5383 comp.generateCplusLocalInterfaces();
5384 comp.generateCPlusInterfaces();
5385 comp.generateCPlusStubClasses();
5386 comp.generateCPlusCallbackStubClasses();
5387 comp.generateCplusSkeletonClass();
5388 comp.generateCplusCallbackSkeletonClass();
5390 // Check other options
5391 while(i < args.length) {
5393 if (!args[i].equals("-java") &&
5394 !args[i].equals("-cplus")) {
5395 throw new Error("IoTCompiler: ERROR - unrecognized command line option: " + args[i] + "\n");
5397 if (i + 1 < args.length) {
5398 comp.setDirectory(args[i+1]);
5400 throw new Error("IoTCompiler: ERROR - please provide <directory> after option: " + args[i] + "\n");
5402 if (args[i].equals("-java")) {
5403 comp.generateEnumJava();
5404 comp.generateStructJava();
5405 comp.generateJavaLocalInterfaces();
5406 comp.generateJavaInterfaces();
5407 comp.generateJavaStubClasses();
5408 comp.generateJavaCallbackStubClasses();
5409 comp.generateJavaSkeletonClass();
5410 comp.generateJavaCallbackSkeletonClass();
5412 comp.generateEnumCplus();
5413 comp.generateStructCplus();
5414 comp.generateCplusLocalInterfaces();
5415 comp.generateCPlusInterfaces();
5416 comp.generateCPlusStubClasses();
5417 comp.generateCPlusCallbackStubClasses();
5418 comp.generateCplusSkeletonClass();
5419 comp.generateCplusCallbackSkeletonClass();
5426 // Need to at least have exactly 2 parameters, i.e. main policy file and requires file
5427 IoTCompiler.printUsage();
5428 throw new Error("IoTCompiler: At least two arguments (main and requires policy files) have to be provided!\n");