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 address;");
418 println("private int[] ports;\n");
420 Integer objId = mapIntfaceObjId.get(intface);
421 println("private final static int objectId = " + objId + ";");
422 mapNewIntfaceObjId.put(newIntface, objId);
423 mapIntfaceObjId.put(intface, objId++);
425 // We assume that each class only has one callback interface for now
426 Iterator it = callbackClasses.iterator();
427 String callbackType = (String) it.next();
428 println("// Callback properties");
429 println("private IoTRMIObject rmiObj;");
430 println("List<" + callbackType + "> listCallbackObj;");
431 println("private static int objIdCnt = 0;");
432 // Generate permission stuff for callback stubs
433 DeclarationHandler decHandler = mapIntDeclHand.get(callbackType);
434 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(callbackType);
435 writePropertiesJavaPermission(callbackType, intDecl);
442 * HELPER: writeConstructorJavaPermission() writes the permission in constructor
444 private void writeConstructorJavaPermission(String intface) {
446 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
447 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
448 String newIntface = intMeth.getKey();
449 int newObjectId = 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 _address, int _rev, int[] _ports) throws Exception {");
461 println("address = _address;");
462 println("ports = _ports;");
463 println("rmiCall = new IoTRMICall(_port, _address, _rev);");
465 Iterator it = callbackClasses.iterator();
466 String callbackType = (String) it.next();
467 writeConstructorJavaPermission(intface);
468 println("listCallbackObj = new ArrayList<" + callbackType + ">();");
469 println("___initCallBack();");
476 * HELPER: writeJavaMethodCallbackPermission() writes permission checks in stub for callbacks
478 private void writeJavaMethodCallbackPermission(String intface) {
480 println("int methodId = IoTRMIObject.getMethodId(method);");
481 // Get all the different stubs
482 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
483 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
484 String newIntface = intMeth.getKey();
485 int newObjectId = 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], address, 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) {
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);
761 String prmType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
762 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
763 print("paramObj[pos++] = ");
764 print(getEnumParam(methPrmTypes.get(i), getSimpleIdentifier(methParams.get(i)), i));
773 * HELPER: writeStructRetMembersJavaStub() writes parameters of struct for return statement
775 private void writeStructRetMembersJavaStub(String simpleType, String retType) {
777 // Get the struct declaration for this struct and generate initialization code
778 StructDecl structDecl = getStructDecl(simpleType);
779 List<String> memTypes = structDecl.getMemberTypes(simpleType);
780 List<String> members = structDecl.getMembers(simpleType);
781 if (isArrayOrList(retType, retType)) { // An array or list
782 println("for(int i = 0; i < retLen; i++) {");
784 if (isArray(retType)) { // An array
785 for (int i = 0; i < members.size(); i++) {
786 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
787 print("structRet[i]." + getSimpleIdentifier(members.get(i)));
788 println(" = (" + getSimpleType(getEnumType(prmType)) + ") retObj[retObjPos++];");
791 } else if (isList(retType)) { // A list
792 println(simpleType + " structRetMem = new " + simpleType + "();");
793 for (int i = 0; i < members.size(); i++) {
794 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
795 print("structRetMem." + getSimpleIdentifier(members.get(i)));
796 println(" = (" + getSimpleType(getEnumType(prmType)) + ") retObj[retObjPos++];");
798 println("structRet.add(structRetMem);");
800 } else { // Just one struct element
801 for (int i = 0; i < members.size(); i++) {
802 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
803 print("structRet." + getSimpleIdentifier(members.get(i)));
804 println(" = (" + getSimpleType(getEnumType(prmType)) + ") retObj[retObjPos++];");
807 println("return structRet;");
812 * HELPER: writeStructReturnJavaStub() writes parameters if struct is present for return statement
814 private void writeStructReturnJavaStub(String simpleType, String retType) {
816 // Handle the returned struct!!!
817 println("Object retLenObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
818 // Minimum retLen is 1 if this is a single struct object
819 println("int retLen = (int) retLenObj;");
820 int numMem = getNumOfMembers(simpleType);
821 println("Class<?>[] retCls = new Class<?>[" + numMem + "*retLen];");
822 println("Class<?>[] retClsVal = new Class<?>[" + numMem + "*retLen];");
823 println("int retPos = 0;");
824 // Get the struct declaration for this struct and generate initialization code
825 StructDecl structDecl = getStructDecl(simpleType);
826 List<String> memTypes = structDecl.getMemberTypes(simpleType);
827 List<String> members = structDecl.getMembers(simpleType);
828 if (isArrayOrList(retType, retType)) { // An array or list
829 println("for(int i = 0; i < retLen; i++) {");
830 for (int i = 0; i < members.size(); i++) {
831 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
832 println("retCls[retPos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
833 println("retClsVal[retPos++] = null;");
836 } else { // Just one struct element
837 for (int i = 0; i < members.size(); i++) {
838 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
839 println("retCls[retPos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
840 println("retClsVal[retPos++] = null;");
843 println("Object[] retObj = rmiCall.getStructObjects(retCls, retClsVal);");
844 if (isArray(retType)) { // An array
845 println(simpleType + "[] structRet = new " + simpleType + "[retLen];");
846 println("for(int i = 0; i < retLen; i++) {");
847 println("structRet[i] = new " + simpleType + "();");
849 } else if (isList(retType)) { // A list
850 println("List<" + simpleType + "> structRet = new ArrayList<" + simpleType + ">();");
852 println(simpleType + " structRet = new " + simpleType + "();");
853 println("int retObjPos = 0;");
854 writeStructRetMembersJavaStub(simpleType, retType);
859 * HELPER: writeStdMethodBodyJavaStub() writes the standard method body in the stub class
861 private void writeStdMethodBodyJavaStub(InterfaceDecl intDecl, List<String> methParams,
862 List<String> methPrmTypes, String method) {
864 checkAndWriteStructSetupJavaStub(methParams, methPrmTypes, intDecl, method);
865 println("int methodId = " + intDecl.getMethodNumId(method) + ";");
866 String retType = intDecl.getMethodType(method);
867 println("Class<?> retType = " + getSimpleType(getStructType(getEnumType(retType))) + ".class;");
868 checkAndWriteEnumTypeJavaStub(methParams, methPrmTypes);
869 // Generate array of parameter types
870 if (isStructPresent(methParams, methPrmTypes)) {
871 writeStructParamClassJavaStub(methParams, methPrmTypes);
873 print("Class<?>[] paramCls = new Class<?>[] { ");
874 for (int i = 0; i < methParams.size(); i++) {
875 String paramType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
876 print(getSimpleType(getEnumType(paramType)) + ".class");
877 // Check if this is the last element (don't print a comma)
878 if (i != methParams.size() - 1) {
883 // Generate array of parameter objects
884 print("Object[] paramObj = new Object[] { ");
885 for (int i = 0; i < methParams.size(); i++) {
886 print(getEnumParam(methPrmTypes.get(i), getSimpleIdentifier(methParams.get(i)), i));
887 // Check if this is the last element (don't print a comma)
888 if (i != methParams.size() - 1) {
894 // Check if this is "void"
895 if (retType.equals("void")) {
896 println("rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
897 } else { // We do have a return value
898 // Generate array of parameter types
899 if (isStructClass(getGenericType(getSimpleArrayType(retType)))) {
900 writeStructReturnJavaStub(getGenericType(getSimpleArrayType(retType)), retType);
902 // This is an enum type
903 if (getParamCategory(getGenericType(getSimpleArrayType(retType))) == ParamCategory.ENUM) {
904 println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
905 checkAndWriteEnumRetTypeJavaStub(retType);
906 } else if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES) {
907 // Check if the return value NONPRIMITIVES
908 String retGenValType = getGenericType(retType);
909 println("Class<?> retGenValType = " + retGenValType + ".class;");
910 println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, retGenValType, paramCls, paramObj);");
911 println("return (" + retType + ")retObj;");
913 println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
914 println("return (" + retType + ")retObj;");
922 * HELPER: returnGenericCallbackType() returns the callback type
924 private String returnGenericCallbackType(String paramType) {
926 if (getParamCategory(paramType) == ParamCategory.NONPRIMITIVES)
927 return getTypeOfGeneric(paramType)[0];
934 * HELPER: checkCallbackType() checks the callback type
936 private boolean checkCallbackType(String paramType, String callbackType) {
938 String prmType = returnGenericCallbackType(paramType);
939 return callbackType.equals(prmType);
944 * HELPER: writeCallbackMethodBodyJavaStub() writes the callback method of the stub class
946 private void writeCallbackMethodBodyJavaStub(InterfaceDecl intDecl, List<String> methParams,
947 List<String> methPrmTypes, String method, String callbackType) {
950 // Check if this is single object, array, or list of objects
951 for (int i = 0; i < methParams.size(); i++) {
952 String paramType = methPrmTypes.get(i);
953 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
954 String param = methParams.get(i);
955 if (isArrayOrList(paramType, param)) { // Generate loop
956 println("for (" + paramType + " cb : " + getSimpleIdentifier(param) + ") {");
957 println(callbackType + "_CallbackSkeleton skel = new " + callbackType + "_CallbackSkeleton(cb, objIdCnt++);");
959 println(callbackType + "_CallbackSkeleton skel = new " + callbackType + "_CallbackSkeleton(" +
960 getSimpleIdentifier(param) + ", objIdCnt++);");
961 println("listCallbackObj.add(skel);");
962 if (isArrayOrList(paramType, param))
967 println(" catch (Exception ex) {");
968 println("ex.printStackTrace();");
969 println("throw new Error(\"Exception when generating skeleton objects!\");");
971 println("int methodId = " + intDecl.getMethodNumId(method) + ";");
972 String retType = intDecl.getMethodType(method);
973 println("Class<?> retType = " + getSimpleType(getEnumType(retType)) + ".class;");
974 // Generate array of parameter types
975 print("Class<?>[] paramCls = new Class<?>[] { ");
976 for (int i = 0; i < methParams.size(); i++) {
977 String paramType = methPrmTypes.get(i);
978 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
980 } else { // Generate normal classes if it's not a callback object
981 String prmType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
982 print(getSimpleType(prmType) + ".class");
984 if (i != methParams.size() - 1) // Check if this is the last element
988 // Generate array of parameter objects
989 print("Object[] paramObj = new Object[] { ");
990 for (int i = 0; i < methParams.size(); i++) {
991 String paramType = methPrmTypes.get(i);
992 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
993 //if (isArray(methPrmTypes.get(i), methParams.get(i)))
994 if (isArray(methParams.get(i)))
995 print(getSimpleIdentifier(methParams.get(i)) + ".length");
996 else if (isList(methPrmTypes.get(i)))
997 print(getSimpleIdentifier(methParams.get(i)) + ".size()");
999 print("new Integer(1)");
1001 print(getSimpleIdentifier(methParams.get(i)));
1002 if (i != methParams.size() - 1)
1006 // Check if this is "void"
1007 if (retType.equals("void")) {
1008 println("rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
1009 } else { // We do have a return value
1010 // Check if the return value NONPRIMITIVES
1011 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES) {
1012 String[] retGenValType = getTypeOfGeneric(retType);
1013 println("Class<?> retGenValType = " + retGenValType[0] + ".class;");
1014 println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, retGenValType, paramCls, paramObj);");
1015 println("return (" + retType + ")retObj;");
1017 println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
1018 println("return (" + retType + ")retObj;");
1025 * HELPER: writeMethodJavaStub() writes the methods of the stub class
1027 private void writeMethodJavaStub(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
1029 for (String method : methods) {
1031 List<String> methParams = intDecl.getMethodParams(method);
1032 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1033 print("public " + intDecl.getMethodType(method) + " " +
1034 intDecl.getMethodId(method) + "(");
1035 boolean isCallbackMethod = false;
1036 String callbackType = null;
1037 for (int i = 0; i < methParams.size(); i++) {
1039 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
1040 // Check if this has callback object
1041 if (callbackClasses.contains(paramType)) {
1042 isCallbackMethod = true;
1043 callbackType = paramType;
1044 // Even if there're 2 callback arguments, we expect them to be of the same interface
1046 print(methPrmTypes.get(i) + " " + methParams.get(i));
1047 // Check if this is the last element (don't print a comma)
1048 if (i != methParams.size() - 1) {
1053 // Now, write the body of stub!
1054 if (isCallbackMethod)
1055 writeCallbackMethodBodyJavaStub(intDecl, methParams, methPrmTypes, method, callbackType);
1057 writeStdMethodBodyJavaStub(intDecl, methParams, methPrmTypes, method);
1059 // Write the init callback helper method
1060 if (isCallbackMethod)
1061 writeInitCallbackJavaStub(callbackType, intDecl);
1067 * generateJavaStubClasses() generate stubs based on the methods list in Java
1069 public void generateJavaStubClasses() throws IOException {
1071 // Create a new directory
1072 String path = createDirectories(dir, subdir);
1073 for (String intface : mapIntfacePTH.keySet()) {
1075 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
1076 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
1078 // Open a new file to write into
1079 String newIntface = intMeth.getKey();
1080 String newStubClass = newIntface + "_Stub";
1081 FileWriter fw = new FileWriter(path + "/" + newStubClass + ".java");
1082 pw = new PrintWriter(new BufferedWriter(fw));
1083 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
1084 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
1085 // Pass in set of methods and get import classes
1086 Set<String> methods = intMeth.getValue();
1087 Set<String> importClasses = getImportClasses(methods, intDecl);
1088 List<String> stdImportClasses = getStandardJavaImportClasses();
1089 List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
1090 printImportStatements(allImportClasses); println("");
1091 // Find out if there are callback objects
1092 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
1093 boolean callbackExist = !callbackClasses.isEmpty();
1094 // Write class header
1095 println("public class " + newStubClass + " implements " + newIntface + " {\n");
1097 writePropertiesJavaStub(intface, newIntface, callbackExist, callbackClasses);
1098 // Write constructor
1099 writeConstructorJavaStub(intface, newStubClass, callbackExist, callbackClasses);
1101 writeMethodJavaStub(intMeth.getValue(), intDecl, callbackClasses);
1104 System.out.println("IoTCompiler: Generated stub class " + newStubClass + ".java...");
1111 * HELPER: writePropertiesJavaCallbackStub() writes the properties of the callback stub class
1113 private void writePropertiesJavaCallbackStub(String intface, String newIntface, boolean callbackExist, Set<String> callbackClasses) {
1115 println("private IoTRMICall rmiCall;");
1116 println("private String address;");
1117 println("private int[] ports;\n");
1118 // Get the object Id
1119 println("private static int objectId = 0;");
1120 if (callbackExist) {
1121 // We assume that each class only has one callback interface for now
1122 Iterator it = callbackClasses.iterator();
1123 String callbackType = (String) it.next();
1124 println("// Callback properties");
1125 println("private IoTRMIObject rmiObj;");
1126 println("List<" + callbackType + "> listCallbackObj;");
1127 println("private static int objIdCnt = 0;");
1128 // Generate permission stuff for callback stubs
1129 DeclarationHandler decHandler = mapIntDeclHand.get(callbackType);
1130 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(callbackType);
1131 writePropertiesJavaPermission(callbackType, intDecl);
1138 * HELPER: writeConstructorJavaCallbackStub() writes the constructor of the callback stub class
1140 private void writeConstructorJavaCallbackStub(String intface, String newStubClass, boolean callbackExist, Set<String> callbackClasses) {
1142 // TODO: If we want callback in callback, then we need to add address and port initializations
1143 println("public " + newStubClass + "(IoTRMICall _rmiCall, int _objectId) throws Exception {");
1144 println("objectId = _objectId;");
1145 println("rmiCall = _rmiCall;");
1146 if (callbackExist) {
1147 Iterator it = callbackClasses.iterator();
1148 String callbackType = (String) it.next();
1149 writeConstructorJavaPermission(intface);
1150 println("listCallbackObj = new ArrayList<" + callbackType + ">();");
1151 println("___initCallBack();");
1152 println("// TODO: Add address and port initialization here if we want callback in callback!");
1159 * generateJavaCallbackStubClasses() generate callback stubs based on the methods list in Java
1161 * Callback stubs gets the IoTRMICall objects from outside of the class as contructor input
1162 * because all these stubs are populated by the class that takes in this object as a callback
1163 * object. In such a class, we only use one socket, hence one IoTRMICall, for all callback objects.
1165 public void generateJavaCallbackStubClasses() throws IOException {
1167 // Create a new directory
1168 String path = createDirectories(dir, subdir);
1169 for (String intface : mapIntfacePTH.keySet()) {
1171 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
1172 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
1174 // Open a new file to write into
1175 String newIntface = intMeth.getKey();
1176 String newStubClass = newIntface + "_CallbackStub";
1177 FileWriter fw = new FileWriter(path + "/" + newStubClass + ".java");
1178 pw = new PrintWriter(new BufferedWriter(fw));
1179 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
1180 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
1181 // Pass in set of methods and get import classes
1182 Set<String> methods = intMeth.getValue();
1183 Set<String> importClasses = getImportClasses(methods, intDecl);
1184 List<String> stdImportClasses = getStandardJavaImportClasses();
1185 List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
1186 printImportStatements(allImportClasses); println("");
1187 // Find out if there are callback objects
1188 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
1189 boolean callbackExist = !callbackClasses.isEmpty();
1190 // Write class header
1191 println("public class " + newStubClass + " implements " + newIntface + " {\n");
1193 writePropertiesJavaCallbackStub(intface, newIntface, callbackExist, callbackClasses);
1194 // Write constructor
1195 writeConstructorJavaCallbackStub(intface, newStubClass, callbackExist, callbackClasses);
1197 // TODO: perhaps need to generate callback for callback
1198 writeMethodJavaStub(intMeth.getValue(), intDecl, callbackClasses);
1201 System.out.println("IoTCompiler: Generated callback stub class " + newStubClass + ".java...");
1208 * HELPER: writePropertiesJavaSkeleton() writes the properties of the skeleton class
1210 private void writePropertiesJavaSkeleton(String intface, boolean callbackExist, InterfaceDecl intDecl) {
1212 println("private " + intface + " mainObj;");
1213 //println("private int ports;");
1214 println("private IoTRMIObject rmiObj;\n");
1216 if (callbackExist) {
1217 println("private static int objIdCnt = 0;");
1218 println("private IoTRMICall rmiCall;");
1220 writePropertiesJavaPermission(intface, intDecl);
1226 * HELPER: writeStructPermissionJavaSkeleton() writes permission for struct helper
1228 private void writeStructPermissionJavaSkeleton(Collection<String> methods, InterfaceDecl intDecl, String intface) {
1230 // Use this set to handle two same methodIds
1231 for (String method : methods) {
1232 List<String> methParams = intDecl.getMethodParams(method);
1233 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1234 // Check for params with structs
1235 for (int i = 0; i < methParams.size(); i++) {
1236 String paramType = methPrmTypes.get(i);
1237 String param = methParams.get(i);
1238 String simpleType = getGenericType(paramType);
1239 if (isStructClass(simpleType)) {
1240 int methodNumId = intDecl.getMethodNumId(method);
1241 String helperMethod = methodNumId + "struct" + i;
1242 int methodHelperNumId = intDecl.getHelperMethodNumId(helperMethod);
1243 // Iterate over interfaces to give permissions to
1244 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
1245 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
1246 String newIntface = intMeth.getKey();
1247 int newObjectId = getNewIntfaceObjectId(newIntface);
1248 println("set" + newObjectId + "Allowed.add(" + methodHelperNumId + ");");
1257 * HELPER: writeConstructorJavaSkeleton() writes the constructor of the skeleton class
1259 private void writeConstructorJavaSkeleton(String newSkelClass, String intface, InterfaceDecl intDecl, Collection<String> methods, boolean callbackExist) {
1261 println("public " + newSkelClass + "(" + intface + " _mainObj, int _port) throws Exception {");
1262 println("mainObj = _mainObj;");
1263 println("rmiObj = new IoTRMIObject(_port);");
1264 // Generate permission control initialization
1265 writeConstructorJavaPermission(intface);
1266 writeJavaInitCallbackPermission(intface, intDecl, callbackExist);
1267 writeStructPermissionJavaSkeleton(methods, intDecl, intface);
1268 println("___waitRequestInvokeMethod();");
1274 * HELPER: writeStdMethodBodyJavaSkeleton() writes the standard method body in the skeleton class
1276 private void writeStdMethodBodyJavaSkeleton(List<String> methParams, String methodId, String methodType) {
1278 if (methodType.equals("void"))
1279 print("mainObj." + methodId + "(");
1281 print("return mainObj." + methodId + "(");
1282 for (int i = 0; i < methParams.size(); i++) {
1284 print(getSimpleIdentifier(methParams.get(i)));
1285 // Check if this is the last element (don't print a comma)
1286 if (i != methParams.size() - 1) {
1295 * HELPER: writeInitCallbackJavaSkeleton() writes the init callback method for skeleton class
1297 private void writeInitCallbackJavaSkeleton(boolean callbackSkeleton) {
1299 // This is a callback skeleton generation
1300 if (callbackSkeleton)
1301 println("public void ___regCB(IoTRMIObject rmiObj) throws IOException {");
1303 println("public void ___regCB() throws IOException {");
1304 println("Object[] paramObj = rmiObj.getMethodParams(new Class<?>[] { int.class, String.class, int.class },");
1305 println("\tnew Class<?>[] { null, null, null });");
1306 println("rmiCall = new IoTRMICall((int) paramObj[0], (String) paramObj[1], (int) paramObj[2]);");
1312 * HELPER: writeMethodJavaSkeleton() writes the method of the skeleton class
1314 private void writeMethodJavaSkeleton(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses,
1315 boolean callbackSkeleton) {
1317 for (String method : methods) {
1319 List<String> methParams = intDecl.getMethodParams(method);
1320 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1321 String methodId = intDecl.getMethodId(method);
1322 print("public " + intDecl.getMethodType(method) + " " + methodId + "(");
1323 boolean isCallbackMethod = false;
1324 String callbackType = null;
1325 for (int i = 0; i < methParams.size(); i++) {
1327 String origParamType = methPrmTypes.get(i);
1328 String paramType = checkAndGetParamClass(origParamType);
1329 if (callbackClasses.contains(origParamType)) { // Check if this has callback object
1330 isCallbackMethod = true;
1331 callbackType = origParamType;
1333 print(paramType + " " + methParams.get(i));
1334 // Check if this is the last element (don't print a comma)
1335 if (i != methParams.size() - 1) {
1340 // Now, write the body of skeleton!
1341 writeStdMethodBodyJavaSkeleton(methParams, methodId, intDecl.getMethodType(method));
1343 if (isCallbackMethod)
1344 writeInitCallbackJavaSkeleton(callbackSkeleton);
1350 * HELPER: writeCallbackJavaStubGeneration() writes the callback stub generation part
1352 private Map<Integer,String> writeCallbackJavaStubGeneration(List<String> methParams, List<String> methPrmTypes,
1353 String callbackType) {
1355 Map<Integer,String> mapStubParam = new HashMap<Integer,String>();
1356 // Iterate over callback objects
1357 for (int i = 0; i < methParams.size(); i++) {
1358 String paramType = methPrmTypes.get(i);
1359 String param = methParams.get(i);
1360 //if (callbackType.equals(paramType)) {
1361 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
1363 String exchParamType = checkAndGetParamClass(paramType);
1364 // Print array if this is array or list if this is a list of callback objects
1365 if (isArray(param)) {
1366 println("int numStubs" + i + " = (int) paramObj[" + i + "];");
1367 println(exchParamType + "[] stub" + i + " = new " + exchParamType + "[numStubs" + i + "];");
1368 } else if (isList(paramType)) {
1369 println("int numStubs" + i + " = (int) paramObj[" + i + "];");
1370 println("List<" + exchParamType + "> stub" + i + " = new ArrayList<" + exchParamType + ">();");
1372 println(exchParamType + " stub" + i + " = new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt);");
1373 println("objIdCnt++;");
1376 // Generate a loop if needed
1377 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
1378 String exchParamType = checkAndGetParamClass(paramType);
1379 if (isArray(param)) {
1380 println("for (int objId = 0; objId < numStubs" + i + "; objId++) {");
1381 println("stub" + i + "[objId] = new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt);");
1382 println("objIdCnt++;");
1384 } else if (isList(paramType)) {
1385 println("for (int objId = 0; objId < numStubs" + i + "; objId++) {");
1386 println("stub" + i + ".add(new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt));");
1387 println("objIdCnt++;");
1390 mapStubParam.put(i, "stub" + i); // List of all stub parameters
1393 return mapStubParam;
1398 * HELPER: checkAndWriteEnumTypeJavaSkeleton() writes the enum type (convert from enum to int)
1400 private void checkAndWriteEnumTypeJavaSkeleton(List<String> methParams, List<String> methPrmTypes) {
1402 // Iterate and find enum declarations
1403 for (int i = 0; i < methParams.size(); i++) {
1404 String paramType = methPrmTypes.get(i);
1405 String param = methParams.get(i);
1406 String simpleType = getGenericType(paramType);
1407 if (isEnumClass(simpleType)) {
1408 // Check if this is enum type
1409 println("int paramInt" + i + "[] = (int[]) paramObj[" + i + "];");
1410 println(simpleType + "[] enumVals = " + simpleType + ".values();");
1411 if (isArray(param)) { // An array
1412 println("int len" + i + " = paramInt" + i + ".length;");
1413 println(simpleType + "[] paramEnum" + i + " = new " + simpleType + "[len" + i + "];");
1414 println("for (int i = 0; i < len" + i + "; i++) {");
1415 println("paramEnum" + i + "[i] = enumVals[paramInt" + i + "[i]];");
1417 } else if (isList(paramType)) { // A list
1418 println("int len" + i + " = paramInt" + i + ".length;");
1419 println("List<" + simpleType + "> paramEnum" + i + " = new ArrayList<" + simpleType + ">();");
1420 println("for (int i = 0; i < len" + i + "; i++) {");
1421 println("paramEnum" + i + ".add(enumVals[paramInt" + i + "[i]]);");
1423 } else { // Just one element
1424 println(simpleType + " paramEnum" + i + " = enumVals[paramInt" + i + "[0]];");
1432 * HELPER: checkAndWriteEnumRetTypeJavaSkeleton() writes the enum return type (convert from enum to int)
1434 private void checkAndWriteEnumRetTypeJavaSkeleton(String retType, String methodId) {
1436 // Strips off array "[]" for return type
1437 String pureType = getSimpleArrayType(getGenericType(retType));
1438 // Take the inner type of generic
1439 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
1440 pureType = getGenericType(retType);
1441 if (isEnumClass(pureType)) {
1442 // Check if this is enum type
1444 if (isArray(retType)) { // An array
1445 print(pureType + "[] retEnum = " + methodId + "(");
1446 } else if (isList(retType)) { // A list
1447 print("List<" + pureType + "> retEnum = " + methodId + "(");
1448 } else { // Just one element
1449 print(pureType + " retEnum = " + methodId + "(");
1456 * HELPER: checkAndWriteEnumRetConvJavaSkeleton() writes the enum return type (convert from enum to int)
1458 private void checkAndWriteEnumRetConvJavaSkeleton(String retType) {
1460 // Strips off array "[]" for return type
1461 String pureType = getSimpleArrayType(getGenericType(retType));
1462 // Take the inner type of generic
1463 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
1464 pureType = getGenericType(retType);
1465 if (isEnumClass(pureType)) {
1466 // Check if this is enum type
1467 if (isArray(retType)) { // An array
1468 println("int retLen = retEnum.length;");
1469 println("int[] retEnumVal = new int[retLen];");
1470 println("for (int i = 0; i < retLen; i++) {");
1471 println("retEnumVal[i] = retEnum[i].ordinal();");
1473 } else if (isList(retType)) { // A list
1474 println("int retLen = retEnum.size();");
1475 println("int[] retEnumVal = new int[retLen];");
1476 println("for (int i = 0; i < retLen; i++) {");
1477 println("retEnumVal[i] = retEnum.get(i).ordinal();");
1479 } else { // Just one element
1480 println("int[] retEnumVal = new int[1];");
1481 println("retEnumVal[0] = retEnum.ordinal();");
1483 println("Object retObj = retEnumVal;");
1489 * HELPER: writeLengthStructParamClassSkeleton() writes lengths of params
1491 private void writeLengthStructParamClassSkeleton(List<String> methParams, List<String> methPrmTypes,
1492 String method, InterfaceDecl intDecl) {
1494 // Iterate and find struct declarations - count number of params
1495 for (int i = 0; i < methParams.size(); i++) {
1496 String paramType = methPrmTypes.get(i);
1497 String param = methParams.get(i);
1498 String simpleType = getGenericType(paramType);
1499 if (isStructClass(simpleType)) {
1500 int members = getNumOfMembers(simpleType);
1501 print(Integer.toString(members) + "*");
1502 int methodNumId = intDecl.getMethodNumId(method);
1503 print("struct" + methodNumId + "Size" + i);
1506 if (i != methParams.size() - 1) {
1514 * HELPER: writeStructMembersJavaSkeleton() writes member parameters of struct
1516 private void writeStructMembersJavaSkeleton(String simpleType, String paramType,
1517 String param, String method, InterfaceDecl intDecl, int iVar) {
1519 // Get the struct declaration for this struct and generate initialization code
1520 StructDecl structDecl = getStructDecl(simpleType);
1521 List<String> memTypes = structDecl.getMemberTypes(simpleType);
1522 List<String> members = structDecl.getMembers(simpleType);
1523 println("int pos = 0;");
1524 if (isArrayOrList(paramType, param)) { // An array or list
1525 int methodNumId = intDecl.getMethodNumId(method);
1526 String counter = "struct" + methodNumId + "Size" + iVar;
1527 println("for(int i = 0; i < " + counter + "; i++) {");
1529 if (isArrayOrList(paramType, param)) { // An array or list
1530 for (int i = 0; i < members.size(); i++) {
1531 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
1532 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
1533 println("paramClsGen[pos++] = null;");
1536 } else { // Just one struct element
1537 for (int i = 0; i < members.size(); i++) {
1538 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
1539 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
1540 println("paramClsGen[pos++] = null;");
1547 * HELPER: writeStructMembersInitJavaSkeleton() writes member parameters initialization of struct
1549 private void writeStructMembersInitJavaSkeleton(InterfaceDecl intDecl, List<String> methParams,
1550 List<String> methPrmTypes, String method) {
1552 for (int i = 0; i < methParams.size(); i++) {
1553 String paramType = methPrmTypes.get(i);
1554 String param = methParams.get(i);
1555 String simpleType = getGenericType(paramType);
1556 if (isStructClass(simpleType)) {
1557 int methodNumId = intDecl.getMethodNumId(method);
1558 String counter = "struct" + methodNumId + "Size" + i;
1560 if (isArray(param)) { // An array
1561 println(simpleType + "[] paramStruct" + i + " = new " + simpleType + "[" + counter + "];");
1562 println("for(int i = 0; i < " + counter + "; i++) {");
1563 println("paramStruct" + i + "[i] = new " + simpleType + "();");
1565 } else if (isList(paramType)) { // A list
1566 println("List<" + simpleType + "> paramStruct" + i + " = new ArrayList<" + simpleType + ">();");
1568 println(simpleType + " paramStruct" + i + " = new " + simpleType + "();");
1569 println("int objPos = 0;");
1570 // Initialize members
1571 StructDecl structDecl = getStructDecl(simpleType);
1572 List<String> members = structDecl.getMembers(simpleType);
1573 List<String> memTypes = structDecl.getMemberTypes(simpleType);
1574 if (isArrayOrList(paramType, param)) { // An array or list
1575 println("for(int i = 0; i < " + counter + "; i++) {");
1577 if (isArray(param)) { // An array
1578 for (int j = 0; j < members.size(); j++) {
1579 String prmType = checkAndGetArray(memTypes.get(j), members.get(j));
1580 print("paramStruct" + i + "[i]." + getSimpleIdentifier(members.get(j)));
1581 println(" = (" + getSimpleType(getEnumType(prmType)) + ") paramObj[objPos++];");
1584 } else if (isList(paramType)) { // A list
1585 println(simpleType + " paramStructMem = new " + simpleType + "();");
1586 for (int j = 0; j < members.size(); j++) {
1587 String prmType = checkAndGetArray(memTypes.get(j), members.get(j));
1588 print("paramStructMem." + getSimpleIdentifier(members.get(j)));
1589 println(" = (" + getSimpleType(getEnumType(prmType)) + ") paramObj[objPos++];");
1591 println("paramStruct" + i + ".add(paramStructMem);");
1593 } else { // Just one struct element
1594 for (int j = 0; j < members.size(); j++) {
1595 String prmType = checkAndGetArray(memTypes.get(j), members.get(j));
1596 print("paramStruct" + i + "." + getSimpleIdentifier(members.get(j)));
1597 println(" = (" + getSimpleType(getEnumType(prmType)) + ") paramObj[objPos++];");
1601 // Take offsets of parameters
1602 println("int offset" + i +" = objPos;");
1609 * HELPER: writeStructReturnJavaSkeleton() writes struct for return statement
1611 private void writeStructReturnJavaSkeleton(String simpleType, String retType) {
1613 // Minimum retLen is 1 if this is a single struct object
1614 if (isArray(retType))
1615 println("int retLen = retStruct.length;");
1616 else if (isList(retType))
1617 println("int retLen = retStruct.size();");
1618 else // Just single struct object
1619 println("int retLen = 1;");
1620 println("Object retLenObj = retLen;");
1621 println("rmiObj.sendReturnObj(retLenObj);");
1622 int numMem = getNumOfMembers(simpleType);
1623 println("Class<?>[] retCls = new Class<?>[" + numMem + "*retLen];");
1624 println("Object[] retObj = new Object[" + numMem + "*retLen];");
1625 println("int retPos = 0;");
1626 // Get the struct declaration for this struct and generate initialization code
1627 StructDecl structDecl = getStructDecl(simpleType);
1628 List<String> memTypes = structDecl.getMemberTypes(simpleType);
1629 List<String> members = structDecl.getMembers(simpleType);
1630 if (isArray(retType)) { // An array or list
1631 println("for(int i = 0; i < retLen; i++) {");
1632 for (int i = 0; i < members.size(); i++) {
1633 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
1634 println("retCls[retPos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
1635 print("retObj[retPos++] = retStruct[i].");
1636 print(getEnumParam(memTypes.get(i), getSimpleIdentifier(members.get(i)), i));
1640 } else if (isList(retType)) { // An array or list
1641 println("for(int i = 0; i < retLen; i++) {");
1642 for (int i = 0; i < members.size(); i++) {
1643 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
1644 println("retCls[retPos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
1645 print("retObj[retPos++] = retStruct.get(i).");
1646 print(getEnumParam(memTypes.get(i), getSimpleIdentifier(members.get(i)), i));
1650 } else { // Just one struct element
1651 for (int i = 0; i < members.size(); i++) {
1652 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
1653 println("retCls[retPos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
1654 print("retObj[retPos++] = retStruct.");
1655 print(getEnumParam(memTypes.get(i), getSimpleIdentifier(members.get(i)), i));
1664 * HELPER: writeMethodHelperReturnJavaSkeleton() writes return statement part in skeleton
1666 private void writeMethodHelperReturnJavaSkeleton(InterfaceDecl intDecl, List<String> methParams,
1667 List<String> methPrmTypes, String method, boolean isCallbackMethod, String callbackType,
1668 boolean isStructMethod) {
1670 checkAndWriteEnumTypeJavaSkeleton(methParams, methPrmTypes);
1671 Map<Integer,String> mapStubParam = null;
1672 if (isCallbackMethod)
1673 mapStubParam = writeCallbackJavaStubGeneration(methParams, methPrmTypes, callbackType);
1674 // Check if this is "void"
1675 String retType = intDecl.getMethodType(method);
1676 if (retType.equals("void")) {
1677 print(intDecl.getMethodId(method) + "(");
1678 } else if (isEnumClass(getSimpleArrayType(getGenericType(retType)))) { // Enum type
1679 checkAndWriteEnumRetTypeJavaSkeleton(retType, intDecl.getMethodId(method));
1680 } else if (isStructClass(getSimpleArrayType(getGenericType(retType)))) { // Struct type
1681 print(retType + " retStruct = " + intDecl.getMethodId(method) + "(");
1682 } else { // We do have a return value
1683 print("Object retObj = " + intDecl.getMethodId(method) + "(");
1685 for (int i = 0; i < methParams.size(); i++) {
1687 if (isCallbackMethod) {
1688 print(mapStubParam.get(i)); // Get the callback parameter
1689 } else if (isEnumClass(getGenericType(methPrmTypes.get(i)))) { // Enum class
1690 print(getEnumParam(methPrmTypes.get(i), methParams.get(i), i));
1691 } else if (isStructClass(getGenericType(methPrmTypes.get(i)))) {
1692 print("paramStruct" + i);
1694 String prmType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
1696 print("(" + prmType + ") paramObj[offset" + i + "]");
1698 print("(" + prmType + ") paramObj[" + i + "]");
1700 if (i != methParams.size() - 1)
1704 if (!retType.equals("void")) {
1705 if (isEnumClass(getSimpleArrayType(getGenericType(retType)))) { // Enum type
1706 checkAndWriteEnumRetConvJavaSkeleton(retType);
1707 println("rmiObj.sendReturnObj(retObj);");
1708 } else if (isStructClass(getSimpleArrayType(getGenericType(retType)))) { // Struct type
1709 writeStructReturnJavaSkeleton(getSimpleArrayType(getGenericType(retType)), retType);
1710 println("rmiObj.sendReturnObj(retCls, retObj);");
1712 println("rmiObj.sendReturnObj(retObj);");
1714 if (isCallbackMethod) { // Catch exception if this is callback
1716 println(" catch(Exception ex) {");
1717 println("ex.printStackTrace();");
1718 println("throw new Error(\"Exception from callback object instantiation!\");");
1725 * HELPER: writeMethodHelperStructJavaSkeleton() writes the struct in skeleton
1727 private void writeMethodHelperStructJavaSkeleton(InterfaceDecl intDecl, List<String> methParams,
1728 List<String> methPrmTypes, String method, Set<String> callbackClasses) {
1730 // Generate array of parameter objects
1731 boolean isCallbackMethod = false;
1732 String callbackType = null;
1733 print("int paramLen = ");
1734 writeLengthStructParamClassSkeleton(methParams, methPrmTypes, method, intDecl);
1736 println("Class<?>[] paramCls = new Class<?>[paramLen];");
1737 println("Class<?>[] paramClsGen = new Class<?>[paramLen];");
1738 // Iterate again over the parameters
1739 for (int i = 0; i < methParams.size(); i++) {
1740 String paramType = methPrmTypes.get(i);
1741 String param = methParams.get(i);
1742 String simpleType = getGenericType(paramType);
1743 if (isStructClass(simpleType)) {
1744 writeStructMembersJavaSkeleton(simpleType, paramType, param, method, intDecl, i);
1746 String prmType = returnGenericCallbackType(methPrmTypes.get(i));
1747 if (callbackClasses.contains(prmType)) {
1748 isCallbackMethod = true;
1749 callbackType = prmType;
1750 println("paramCls[pos] = int.class;");
1751 println("paramClsGen[pos++] = null;");
1752 } else { // Generate normal classes if it's not a callback object
1753 String paramTypeOth = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
1754 println("paramCls[pos] = " + getSimpleType(getEnumType(paramTypeOth)) + ".class;");
1755 print("paramClsGen[pos++] = ");
1756 String prmTypeOth = methPrmTypes.get(i);
1757 if (getParamCategory(prmTypeOth) == ParamCategory.NONPRIMITIVES)
1758 println(getTypeOfGeneric(prmType)[0] + ".class;");
1764 println("Object[] paramObj = rmiObj.getMethodParams(paramCls, paramClsGen);");
1765 writeStructMembersInitJavaSkeleton(intDecl, methParams, methPrmTypes, method);
1766 // Write the return value part
1767 writeMethodHelperReturnJavaSkeleton(intDecl, methParams, methPrmTypes, method, isCallbackMethod, callbackType, true);
1772 * HELPER: writeStdMethodHelperBodyJavaSkeleton() writes the standard method body helper in the skeleton class
1774 private void writeStdMethodHelperBodyJavaSkeleton(InterfaceDecl intDecl, List<String> methParams,
1775 List<String> methPrmTypes, String method, Set<String> callbackClasses) {
1777 // Generate array of parameter objects
1778 boolean isCallbackMethod = false;
1779 String callbackType = null;
1780 print("Object[] paramObj = rmiObj.getMethodParams(new Class<?>[] { ");
1781 for (int i = 0; i < methParams.size(); i++) {
1783 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
1784 if (callbackClasses.contains(paramType)) {
1785 isCallbackMethod = true;
1786 callbackType = paramType;
1788 } else { // Generate normal classes if it's not a callback object
1789 String prmType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
1790 print(getSimpleType(getEnumType(prmType)) + ".class");
1792 if (i != methParams.size() - 1)
1796 // Generate generic class if it's a generic type.. null otherwise
1797 print("new Class<?>[] { ");
1798 for (int i = 0; i < methParams.size(); i++) {
1799 String prmType = methPrmTypes.get(i);
1800 if ((getParamCategory(prmType) == ParamCategory.NONPRIMITIVES) &&
1801 !isEnumClass(getGenericType(prmType)))
1802 print(getGenericType(prmType) + ".class");
1805 if (i != methParams.size() - 1)
1809 // Write the return value part
1810 writeMethodHelperReturnJavaSkeleton(intDecl, methParams, methPrmTypes, method, isCallbackMethod, callbackType, false);
1815 * HELPER: writeMethodHelperJavaSkeleton() writes the method helper of the skeleton class
1817 private void writeMethodHelperJavaSkeleton(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
1819 // Use this set to handle two same methodIds
1820 Set<String> uniqueMethodIds = new HashSet<String>();
1821 for (String method : methods) {
1823 List<String> methParams = intDecl.getMethodParams(method);
1824 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1825 if (isStructPresent(methParams, methPrmTypes)) { // Treat struct differently
1826 String methodId = intDecl.getMethodId(method);
1827 print("public void ___");
1828 String helperMethod = methodId;
1829 if (uniqueMethodIds.contains(methodId))
1830 helperMethod = helperMethod + intDecl.getMethodNumId(method);
1832 uniqueMethodIds.add(methodId);
1833 String retType = intDecl.getMethodType(method);
1834 print(helperMethod + "(");
1835 boolean begin = true;
1836 for (int i = 0; i < methParams.size(); i++) { // Print size variables
1837 String paramType = methPrmTypes.get(i);
1838 String param = methParams.get(i);
1839 String simpleType = getGenericType(paramType);
1840 if (isStructClass(simpleType)) {
1841 if (!begin) { // Generate comma for not the beginning variable
1842 print(", "); begin = false;
1844 int methodNumId = intDecl.getMethodNumId(method);
1845 print("int struct" + methodNumId + "Size" + i);
1848 // Check if this is "void"
1849 if (retType.equals("void"))
1852 println(") throws IOException {");
1853 writeMethodHelperStructJavaSkeleton(intDecl, methParams, methPrmTypes, method, callbackClasses);
1856 String methodId = intDecl.getMethodId(method);
1857 print("public void ___");
1858 String helperMethod = methodId;
1859 if (uniqueMethodIds.contains(methodId))
1860 helperMethod = helperMethod + intDecl.getMethodNumId(method);
1862 uniqueMethodIds.add(methodId);
1863 // Check if this is "void"
1864 String retType = intDecl.getMethodType(method);
1865 if (retType.equals("void"))
1866 println(helperMethod + "() {");
1868 println(helperMethod + "() throws IOException {");
1869 // Now, write the helper body of skeleton!
1870 writeStdMethodHelperBodyJavaSkeleton(intDecl, methParams, methPrmTypes, method, callbackClasses);
1874 // Write method helper for structs
1875 writeMethodHelperStructSetupJavaSkeleton(methods, intDecl);
1880 * HELPER: writeMethodHelperStructSetupJavaSkeleton() writes the method helper of struct setup in skeleton class
1882 private void writeMethodHelperStructSetupJavaSkeleton(Collection<String> methods,
1883 InterfaceDecl intDecl) {
1885 // Use this set to handle two same methodIds
1886 for (String method : methods) {
1888 List<String> methParams = intDecl.getMethodParams(method);
1889 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1890 // Check for params with structs
1891 for (int i = 0; i < methParams.size(); i++) {
1892 String paramType = methPrmTypes.get(i);
1893 String param = methParams.get(i);
1894 String simpleType = getGenericType(paramType);
1895 if (isStructClass(simpleType)) {
1896 int methodNumId = intDecl.getMethodNumId(method);
1897 print("public int ___");
1898 String helperMethod = methodNumId + "struct" + i;
1899 println(helperMethod + "() {");
1900 // Now, write the helper body of skeleton!
1901 println("Object[] paramObj = rmiObj.getMethodParams(new Class<?>[] { int.class }, new Class<?>[] { null });");
1902 println("return (int) paramObj[0];");
1911 * HELPER: writeMethodHelperStructSetupJavaCallbackSkeleton() writes the method helper of struct setup in callback skeleton class
1913 private void writeMethodHelperStructSetupJavaCallbackSkeleton(Collection<String> methods,
1914 InterfaceDecl intDecl) {
1916 // Use this set to handle two same methodIds
1917 for (String method : methods) {
1919 List<String> methParams = intDecl.getMethodParams(method);
1920 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1921 // Check for params with structs
1922 for (int i = 0; i < methParams.size(); i++) {
1923 String paramType = methPrmTypes.get(i);
1924 String param = methParams.get(i);
1925 String simpleType = getGenericType(paramType);
1926 if (isStructClass(simpleType)) {
1927 int methodNumId = intDecl.getMethodNumId(method);
1928 print("public int ___");
1929 String helperMethod = methodNumId + "struct" + i;
1930 println(helperMethod + "(IoTRMIObject rmiObj) {");
1931 // Now, write the helper body of skeleton!
1932 println("Object[] paramObj = rmiObj.getMethodParams(new Class<?>[] { int.class }, new Class<?>[] { null });");
1933 println("return (int) paramObj[0];");
1942 * HELPER: writeCountVarStructSkeleton() writes counter variable of struct for skeleton
1944 private void writeCountVarStructSkeleton(Collection<String> methods, InterfaceDecl intDecl) {
1946 // Use this set to handle two same methodIds
1947 for (String method : methods) {
1949 List<String> methParams = intDecl.getMethodParams(method);
1950 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1951 // Check for params with structs
1952 for (int i = 0; i < methParams.size(); i++) {
1953 String paramType = methPrmTypes.get(i);
1954 String param = methParams.get(i);
1955 String simpleType = getGenericType(paramType);
1956 if (isStructClass(simpleType)) {
1957 int methodNumId = intDecl.getMethodNumId(method);
1958 println("int struct" + methodNumId + "Size" + i + " = 0;");
1966 * HELPER: writeInputCountVarStructSkeleton() writes input counter variable of struct for skeleton
1968 private boolean writeInputCountVarStructSkeleton(String method, InterfaceDecl intDecl) {
1970 List<String> methParams = intDecl.getMethodParams(method);
1971 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1972 boolean structExist = false;
1973 // Check for params with structs
1974 for (int i = 0; i < methParams.size(); i++) {
1975 String paramType = methPrmTypes.get(i);
1976 String param = methParams.get(i);
1977 String simpleType = getGenericType(paramType);
1978 boolean begin = true;
1979 if (isStructClass(simpleType)) {
1982 print(", "); begin = false;
1984 int methodNumId = intDecl.getMethodNumId(method);
1985 print("struct" + methodNumId + "Size" + i);
1993 * HELPER: writeMethodCallStructSkeleton() writes method call for wait invoke in skeleton
1995 private void writeMethodCallStructSkeleton(Collection<String> methods, InterfaceDecl intDecl) {
1997 // Use this set to handle two same methodIds
1998 for (String method : methods) {
2000 List<String> methParams = intDecl.getMethodParams(method);
2001 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2002 // Check for params with structs
2003 for (int i = 0; i < methParams.size(); i++) {
2004 String paramType = methPrmTypes.get(i);
2005 String param = methParams.get(i);
2006 String simpleType = getGenericType(paramType);
2007 if (isStructClass(simpleType)) {
2008 int methodNumId = intDecl.getMethodNumId(method);
2010 String helperMethod = methodNumId + "struct" + i;
2011 String tempVar = "struct" + methodNumId + "Size" + i;
2012 print(intDecl.getHelperMethodNumId(helperMethod) + ": ");
2013 print(tempVar + " = ___");
2014 println(helperMethod + "(); break;");
2022 * HELPER: writeMethodCallStructCallbackSkeleton() writes method call for wait invoke in skeleton
2024 private void writeMethodCallStructCallbackSkeleton(Collection<String> methods, InterfaceDecl intDecl) {
2026 // Use this set to handle two same methodIds
2027 for (String method : methods) {
2029 List<String> methParams = intDecl.getMethodParams(method);
2030 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2031 // Check for params with structs
2032 for (int i = 0; i < methParams.size(); i++) {
2033 String paramType = methPrmTypes.get(i);
2034 String param = methParams.get(i);
2035 String simpleType = getGenericType(paramType);
2036 if (isStructClass(simpleType)) {
2037 int methodNumId = intDecl.getMethodNumId(method);
2039 String helperMethod = methodNumId + "struct" + i;
2040 String tempVar = "struct" + methodNumId + "Size" + i;
2041 print(intDecl.getHelperMethodNumId(helperMethod) + ": ");
2042 print(tempVar + " = ___");
2043 println(helperMethod + "(rmiObj); break;");
2051 * HELPER: writeJavaMethodPermission() writes permission checks in skeleton
2053 private void writeJavaMethodPermission(String intface) {
2055 // Get all the different stubs
2056 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
2057 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
2058 String newIntface = intMeth.getKey();
2059 int newObjectId = getNewIntfaceObjectId(newIntface);
2060 println("if (_objectId == object" + newObjectId + "Id) {");
2061 println("if (!set" + newObjectId + "Allowed.contains(methodId)) {");
2062 println("throw new Error(\"Object with object Id: \" + _objectId + \" is not allowed to access method: \" + methodId);");
2066 println("throw new Error(\"Object Id: \" + _objectId + \" not recognized!\");");
2073 * HELPER: writeJavaWaitRequestInvokeMethod() writes the main loop of the skeleton class
2075 private void writeJavaWaitRequestInvokeMethod(Collection<String> methods, InterfaceDecl intDecl, boolean callbackExist, String intface) {
2077 // Use this set to handle two same methodIds
2078 Set<String> uniqueMethodIds = new HashSet<String>();
2079 println("private void ___waitRequestInvokeMethod() throws IOException {");
2080 // Write variables here if we have callbacks or enums or structs
2081 writeCountVarStructSkeleton(methods, intDecl);
2082 println("while (true) {");
2083 println("rmiObj.getMethodBytes();");
2084 println("int _objectId = rmiObj.getObjectId();");
2085 println("int methodId = rmiObj.getMethodId();");
2086 // Generate permission check
2087 writeJavaMethodPermission(intface);
2088 println("switch (methodId) {");
2089 // Print methods and method Ids
2090 for (String method : methods) {
2091 String methodId = intDecl.getMethodId(method);
2092 int methodNumId = intDecl.getMethodNumId(method);
2093 print("case " + methodNumId + ": ___");
2094 String helperMethod = methodId;
2095 if (uniqueMethodIds.contains(methodId))
2096 helperMethod = helperMethod + methodNumId;
2098 uniqueMethodIds.add(methodId);
2099 print(helperMethod + "(");
2100 writeInputCountVarStructSkeleton(method, intDecl);
2101 println("); break;");
2103 String method = "___initCallBack()";
2104 // Print case -9999 (callback handler) if callback exists
2105 if (callbackExist) {
2106 int methodId = intDecl.getHelperMethodNumId(method);
2107 println("case " + methodId + ": ___regCB(); break;");
2109 writeMethodCallStructSkeleton(methods, intDecl);
2110 println("default: ");
2111 println("throw new Error(\"Method Id \" + methodId + \" not recognized!\");");
2119 * generateJavaSkeletonClass() generate skeletons based on the methods list in Java
2121 public void generateJavaSkeletonClass() throws IOException {
2123 // Create a new directory
2124 String path = createDirectories(dir, subdir);
2125 for (String intface : mapIntfacePTH.keySet()) {
2126 // Open a new file to write into
2127 String newSkelClass = intface + "_Skeleton";
2128 FileWriter fw = new FileWriter(path + "/" + newSkelClass + ".java");
2129 pw = new PrintWriter(new BufferedWriter(fw));
2130 // Pass in set of methods and get import classes
2131 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2132 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
2133 List<String> methods = intDecl.getMethods();
2134 Set<String> importClasses = getImportClasses(methods, intDecl);
2135 List<String> stdImportClasses = getStandardJavaImportClasses();
2136 List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
2137 printImportStatements(allImportClasses);
2138 // Find out if there are callback objects
2139 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
2140 boolean callbackExist = !callbackClasses.isEmpty();
2141 // Write class header
2143 println("public class " + newSkelClass + " implements " + intface + " {\n");
2145 writePropertiesJavaSkeleton(intface, callbackExist, intDecl);
2146 // Write constructor
2147 writeConstructorJavaSkeleton(newSkelClass, intface, intDecl, methods, callbackExist);
2149 writeMethodJavaSkeleton(methods, intDecl, callbackClasses, false);
2150 // Write method helper
2151 writeMethodHelperJavaSkeleton(methods, intDecl, callbackClasses);
2152 // Write waitRequestInvokeMethod() - main loop
2153 writeJavaWaitRequestInvokeMethod(methods, intDecl, callbackExist, intface);
2156 System.out.println("IoTCompiler: Generated skeleton class " + newSkelClass + ".java...");
2162 * HELPER: writePropertiesJavaCallbackSkeleton() writes the properties of the callback skeleton class
2164 private void writePropertiesJavaCallbackSkeleton(String intface, boolean callbackExist) {
2166 println("private " + intface + " mainObj;");
2167 // For callback skeletons, this is its own object Id
2168 println("private static int objectId = 0;");
2170 if (callbackExist) {
2171 println("private static int objIdCnt = 0;");
2172 println("private IoTRMICall rmiCall;");
2179 * HELPER: writeConstructorJavaCallbackSkeleton() writes the constructor of the skeleton class
2181 private void writeConstructorJavaCallbackSkeleton(String newSkelClass, String intface, InterfaceDecl intDecl, Collection<String> methods) {
2183 println("public " + newSkelClass + "(" + intface + " _mainObj, int _objectId) throws Exception {");
2184 println("mainObj = _mainObj;");
2185 println("objectId = _objectId;");
2191 * HELPER: writeMethodHelperJavaCallbackSkeleton() writes the method helper of the callback skeleton class
2193 private void writeMethodHelperJavaCallbackSkeleton(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
2195 // Use this set to handle two same methodIds
2196 Set<String> uniqueMethodIds = new HashSet<String>();
2197 for (String method : methods) {
2199 List<String> methParams = intDecl.getMethodParams(method);
2200 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2201 if (isStructPresent(methParams, methPrmTypes)) { // Treat struct differently
2202 String methodId = intDecl.getMethodId(method);
2203 print("public void ___");
2204 String helperMethod = methodId;
2205 if (uniqueMethodIds.contains(methodId))
2206 helperMethod = helperMethod + intDecl.getMethodNumId(method);
2208 uniqueMethodIds.add(methodId);
2209 String retType = intDecl.getMethodType(method);
2210 print(helperMethod + "(");
2211 boolean begin = true;
2212 for (int i = 0; i < methParams.size(); i++) { // Print size variables
2213 String paramType = methPrmTypes.get(i);
2214 String param = methParams.get(i);
2215 String simpleType = getGenericType(paramType);
2216 if (isStructClass(simpleType)) {
2217 if (!begin) { // Generate comma for not the beginning variable
2218 print(", "); begin = false;
2220 int methodNumId = intDecl.getMethodNumId(method);
2221 print("int struct" + methodNumId + "Size" + i);
2224 // Check if this is "void"
2225 if (retType.equals("void"))
2226 println(", IoTRMIObject rmiObj) {");
2228 println(", IoTRMIObject rmiObj) throws IOException {");
2229 writeMethodHelperStructJavaSkeleton(intDecl, methParams, methPrmTypes, method, callbackClasses);
2232 String methodId = intDecl.getMethodId(method);
2233 print("public void ___");
2234 String helperMethod = methodId;
2235 if (uniqueMethodIds.contains(methodId))
2236 helperMethod = helperMethod + intDecl.getMethodNumId(method);
2238 uniqueMethodIds.add(methodId);
2239 // Check if this is "void"
2240 String retType = intDecl.getMethodType(method);
2241 if (retType.equals("void"))
2242 println(helperMethod + "(IoTRMIObject rmiObj) {");
2244 println(helperMethod + "(IoTRMIObject rmiObj) throws IOException {");
2245 // Now, write the helper body of skeleton!
2246 writeStdMethodHelperBodyJavaSkeleton(intDecl, methParams, methPrmTypes, method, callbackClasses);
2250 // Write method helper for structs
2251 writeMethodHelperStructSetupJavaCallbackSkeleton(methods, intDecl);
2256 * HELPER: writeJavaCallbackWaitRequestInvokeMethod() writes the request invoke method of the callback skeleton class
2258 private void writeJavaCallbackWaitRequestInvokeMethod(Collection<String> methods, InterfaceDecl intDecl, boolean callbackExist) {
2260 // Use this set to handle two same methodIds
2261 Set<String> uniqueMethodIds = new HashSet<String>();
2262 println("public void invokeMethod(IoTRMIObject rmiObj) throws IOException {");
2263 // Write variables here if we have callbacks or enums or structs
2264 writeCountVarStructSkeleton(methods, intDecl);
2265 // Write variables here if we have callbacks or enums or structs
2266 println("int methodId = rmiObj.getMethodId();");
2267 // TODO: code the permission check here!
2268 println("switch (methodId) {");
2269 // Print methods and method Ids
2270 for (String method : methods) {
2271 String methodId = intDecl.getMethodId(method);
2272 int methodNumId = intDecl.getMethodNumId(method);
2273 print("case " + methodNumId + ": ___");
2274 String helperMethod = methodId;
2275 if (uniqueMethodIds.contains(methodId))
2276 helperMethod = helperMethod + methodNumId;
2278 uniqueMethodIds.add(methodId);
2279 print(helperMethod + "(");
2280 if (writeInputCountVarStructSkeleton(method, intDecl))
2281 println(", rmiObj); break;");
2283 println("rmiObj); break;");
2285 String method = "___initCallBack()";
2286 // Print case -9999 (callback handler) if callback exists
2287 if (callbackExist) {
2288 int methodId = intDecl.getHelperMethodNumId(method);
2289 println("case " + methodId + ": ___regCB(rmiObj); break;");
2291 writeMethodCallStructCallbackSkeleton(methods, intDecl);
2292 println("default: ");
2293 println("throw new Error(\"Method Id \" + methodId + \" not recognized!\");");
2300 * generateJavaCallbackSkeletonClass() generate callback skeletons based on the methods list in Java
2302 public void generateJavaCallbackSkeletonClass() throws IOException {
2304 // Create a new directory
2305 String path = createDirectories(dir, subdir);
2306 for (String intface : mapIntfacePTH.keySet()) {
2307 // Open a new file to write into
2308 String newSkelClass = intface + "_CallbackSkeleton";
2309 FileWriter fw = new FileWriter(path + "/" + newSkelClass + ".java");
2310 pw = new PrintWriter(new BufferedWriter(fw));
2311 // Pass in set of methods and get import classes
2312 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2313 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
2314 List<String> methods = intDecl.getMethods();
2315 Set<String> importClasses = getImportClasses(methods, intDecl);
2316 List<String> stdImportClasses = getStandardJavaImportClasses();
2317 List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
2318 printImportStatements(allImportClasses);
2319 // Find out if there are callback objects
2320 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
2321 boolean callbackExist = !callbackClasses.isEmpty();
2322 // Write class header
2324 println("public class " + newSkelClass + " implements " + intface + " {\n");
2326 writePropertiesJavaCallbackSkeleton(intface, callbackExist);
2327 // Write constructor
2328 writeConstructorJavaCallbackSkeleton(newSkelClass, intface, intDecl, methods);
2330 writeMethodJavaSkeleton(methods, intDecl, callbackClasses, true);
2331 // Write method helper
2332 writeMethodHelperJavaCallbackSkeleton(methods, intDecl, callbackClasses);
2333 // Write waitRequestInvokeMethod() - main loop
2334 writeJavaCallbackWaitRequestInvokeMethod(methods, intDecl, callbackExist);
2337 System.out.println("IoTCompiler: Generated callback skeleton class " + newSkelClass + ".java...");
2343 * HELPER: writeMethodCplusLocalInterface() writes the method of the local interface
2345 private void writeMethodCplusLocalInterface(Collection<String> methods, InterfaceDecl intDecl) {
2347 for (String method : methods) {
2349 List<String> methParams = intDecl.getMethodParams(method);
2350 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2351 print("virtual " + checkAndGetCplusType(intDecl.getMethodType(method)) + " " +
2352 intDecl.getMethodId(method) + "(");
2353 for (int i = 0; i < methParams.size(); i++) {
2354 // Check for params with driver class types and exchange it
2355 // with its remote interface
2356 String paramType = checkAndGetParamClass(methPrmTypes.get(i));
2357 paramType = checkAndGetCplusType(paramType);
2358 // Check for arrays - translate into vector in C++
2359 String paramComplete = checkAndGetCplusArray(paramType, methParams.get(i));
2360 print(paramComplete);
2361 // Check if this is the last element (don't print a comma)
2362 if (i != methParams.size() - 1) {
2372 * HELPER: writeMethodCplusInterface() writes the method of the interface
2374 private void writeMethodCplusInterface(Collection<String> methods, InterfaceDecl intDecl) {
2376 for (String method : methods) {
2378 List<String> methParams = intDecl.getMethodParams(method);
2379 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2380 print("virtual " + checkAndGetCplusType(intDecl.getMethodType(method)) + " " +
2381 intDecl.getMethodId(method) + "(");
2382 for (int i = 0; i < methParams.size(); i++) {
2383 // Check for params with driver class types and exchange it
2384 // with its remote interface
2385 String paramType = methPrmTypes.get(i);
2386 paramType = checkAndGetCplusType(paramType);
2387 // Check for arrays - translate into vector in C++
2388 String paramComplete = checkAndGetCplusArray(paramType, methParams.get(i));
2389 print(paramComplete);
2390 // Check if this is the last element (don't print a comma)
2391 if (i != methParams.size() - 1) {
2401 * HELPER: generateEnumCplus() writes the enumeration declaration
2403 public void generateEnumCplus() throws IOException {
2405 // Create a new directory
2406 createDirectory(dir);
2407 for (String intface : mapIntfacePTH.keySet()) {
2408 // Get the right StructDecl
2409 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2410 EnumDecl enumDecl = (EnumDecl) decHandler.getEnumDecl(intface);
2411 Set<String> enumTypes = enumDecl.getEnumDeclarations();
2412 // Iterate over enum declarations
2413 for (String enType : enumTypes) {
2414 // Open a new file to write into
2415 FileWriter fw = new FileWriter(dir + "/" + enType + ".hpp");
2416 pw = new PrintWriter(new BufferedWriter(fw));
2417 // Write file headers
2418 println("#ifndef _" + enType.toUpperCase() + "_HPP__");
2419 println("#define _" + enType.toUpperCase() + "_HPP__");
2420 println("enum " + enType + " {");
2421 List<String> enumMembers = enumDecl.getMembers(enType);
2422 for (int i = 0; i < enumMembers.size(); i++) {
2424 String member = enumMembers.get(i);
2426 // Check if this is the last element (don't print a comma)
2427 if (i != enumMembers.size() - 1)
2435 System.out.println("IoTCompiler: Generated enum " + enType + ".hpp...");
2442 * HELPER: generateStructCplus() writes the struct declaration
2444 public void generateStructCplus() throws IOException {
2446 // Create a new directory
2447 createDirectory(dir);
2448 for (String intface : mapIntfacePTH.keySet()) {
2449 // Get the right StructDecl
2450 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2451 StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
2452 List<String> structTypes = structDecl.getStructTypes();
2453 // Iterate over enum declarations
2454 for (String stType : structTypes) {
2455 // Open a new file to write into
2456 FileWriter fw = new FileWriter(dir + "/" + stType + ".hpp");
2457 pw = new PrintWriter(new BufferedWriter(fw));
2458 // Write file headers
2459 println("#ifndef _" + stType.toUpperCase() + "_HPP__");
2460 println("#define _" + stType.toUpperCase() + "_HPP__");
2461 println("using namespace std;");
2462 println("struct " + stType + " {");
2463 List<String> structMemberTypes = structDecl.getMemberTypes(stType);
2464 List<String> structMembers = structDecl.getMembers(stType);
2465 for (int i = 0; i < structMembers.size(); i++) {
2467 String memberType = structMemberTypes.get(i);
2468 String member = structMembers.get(i);
2469 String structTypeC = checkAndGetCplusType(memberType);
2470 String structComplete = checkAndGetCplusArray(structTypeC, member);
2471 println(structComplete + ";");
2476 System.out.println("IoTCompiler: Generated struct " + stType + ".hpp...");
2483 * generateCplusLocalInterfaces() writes the local interfaces and provides type-checking.
2485 * It needs to rewrite and exchange USERDEFINED types in input parameters of stub
2486 * and original interfaces, e.g. exchange Camera and CameraWithVideoAndRecording.
2487 * The local interface has to be the input parameter for the stub and the stub
2488 * interface has to be the input parameter for the local class.
2490 public void generateCplusLocalInterfaces() throws IOException {
2492 // Create a new directory
2493 createDirectory(dir);
2494 for (String intface : mapIntfacePTH.keySet()) {
2495 // Open a new file to write into
2496 FileWriter fw = new FileWriter(dir + "/" + intface + ".hpp");
2497 pw = new PrintWriter(new BufferedWriter(fw));
2498 // Write file headers
2499 println("#ifndef _" + intface.toUpperCase() + "_HPP__");
2500 println("#define _" + intface.toUpperCase() + "_HPP__");
2501 println("#include <iostream>");
2502 // Pass in set of methods and get include classes
2503 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2504 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
2505 List<String> methods = intDecl.getMethods();
2506 Set<String> includeClasses = getIncludeClasses(methods, intDecl, intface, true);
2507 printIncludeStatements(includeClasses); println("");
2508 println("using namespace std;\n");
2509 //writeStructCplus(structDecl);
2510 println("class " + intface); println("{");
2513 writeMethodCplusLocalInterface(methods, intDecl);
2517 System.out.println("IoTCompiler: Generated local interface " + intface + ".hpp...");
2523 * generateCPlusInterfaces() generate stub interfaces based on the methods list in C++
2525 * For C++ we use virtual classe as interface
2527 public void generateCPlusInterfaces() throws IOException {
2529 // Create a new directory
2530 String path = createDirectories(dir, subdir);
2531 for (String intface : mapIntfacePTH.keySet()) {
2533 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
2534 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
2536 // Open a new file to write into
2537 String newIntface = intMeth.getKey();
2538 FileWriter fw = new FileWriter(path + "/" + newIntface + ".hpp");
2539 pw = new PrintWriter(new BufferedWriter(fw));
2540 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2541 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
2542 // Write file headers
2543 println("#ifndef _" + newIntface.toUpperCase() + "_HPP__");
2544 println("#define _" + newIntface.toUpperCase() + "_HPP__");
2545 println("#include <iostream>");
2546 // Pass in set of methods and get import classes
2547 Set<String> includeClasses = getIncludeClasses(intMeth.getValue(), intDecl, intface, false);
2548 List<String> stdIncludeClasses = getStandardCplusIncludeClasses();
2549 List<String> allIncludeClasses = getAllLibClasses(stdIncludeClasses, includeClasses);
2550 printIncludeStatements(allIncludeClasses); println("");
2551 println("using namespace std;\n");
2552 println("class " + newIntface);
2556 writeMethodCplusInterface(intMeth.getValue(), intDecl);
2560 System.out.println("IoTCompiler: Generated interface " + newIntface + ".hpp...");
2567 * HELPER: writeMethodCplusStub() writes the methods of the stub
2569 private void writeMethodCplusStub(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
2571 for (String method : methods) {
2573 List<String> methParams = intDecl.getMethodParams(method);
2574 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2575 print(checkAndGetCplusType(intDecl.getMethodType(method)) + " " +
2576 intDecl.getMethodId(method) + "(");
2577 boolean isCallbackMethod = false;
2578 String callbackType = null;
2579 for (int i = 0; i < methParams.size(); i++) {
2581 String paramType = methPrmTypes.get(i);
2582 // Check if this has callback object
2583 if (callbackClasses.contains(paramType)) {
2584 isCallbackMethod = true;
2585 callbackType = paramType;
2586 // Even if there're 2 callback arguments, we expect them to be of the same interface
2588 String methPrmType = checkAndGetCplusType(methPrmTypes.get(i));
2589 String methParamComplete = checkAndGetCplusArray(methPrmType, methParams.get(i));
2590 print(methParamComplete);
2591 // Check if this is the last element (don't print a comma)
2592 if (i != methParams.size() - 1) {
2597 if (isCallbackMethod)
2598 writeCallbackMethodBodyCplusStub(intDecl, methParams, methPrmTypes, method, callbackType);
2600 writeStdMethodBodyCplusStub(intDecl, methParams, methPrmTypes, method);
2602 // Write the init callback helper method
2603 if (isCallbackMethod) {
2604 writeInitCallbackCplusStub(callbackType, intDecl);
2605 writeInitCallbackSendInfoCplusStub(intDecl);
2612 * HELPER: writeCallbackMethodBodyCplusStub() writes the callback method of the stub class
2614 private void writeCallbackMethodBodyCplusStub(InterfaceDecl intDecl, List<String> methParams,
2615 List<String> methPrmTypes, String method, String callbackType) {
2617 // Check if this is single object, array, or list of objects
2618 boolean isArrayOrList = false;
2619 String callbackParam = null;
2620 for (int i = 0; i < methParams.size(); i++) {
2622 String paramType = methPrmTypes.get(i);
2623 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
2624 String param = methParams.get(i);
2625 if (isArrayOrList(paramType, param)) { // Generate loop
2626 println("for (" + paramType + "* cb : " + getSimpleIdentifier(param) + ") {");
2627 println(callbackType + "_CallbackSkeleton* skel = new " + callbackType + "_CallbackSkeleton(cb, objIdCnt++);");
2628 isArrayOrList = true;
2629 callbackParam = getSimpleIdentifier(param);
2631 println(callbackType + "_CallbackSkeleton* skel = new " + callbackType + "_CallbackSkeleton(" +
2632 getSimpleIdentifier(param) + ", objIdCnt++);");
2633 println("vecCallbackObj.push_back(skel);");
2634 if (isArrayOrList(paramType, param))
2638 println("int numParam = " + methParams.size() + ";");
2639 println("int methodId = " + intDecl.getMethodNumId(method) + ";");
2640 String retType = intDecl.getMethodType(method);
2641 //String retTypeC = checkAndGetCplusType(retType);
2642 //println("string retType = \"" + checkAndGetCplusArrayType(getStructType(getEnumType(retTypeC))) + "\";");
2643 println("string retType = \"" + checkAndGetCplusRetClsType(getStructType(getEnumType(retType))) + "\";");
2644 // Generate array of parameter types
2645 print("string paramCls[] = { ");
2646 for (int i = 0; i < methParams.size(); i++) {
2647 String paramType = methPrmTypes.get(i);
2648 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
2650 } else { // Generate normal classes if it's not a callback object
2651 String paramTypeC = checkAndGetCplusArgClsType(methPrmTypes.get(i), methParams.get(i));
2652 print("\"" + paramTypeC + "\"");
2654 if (i != methParams.size() - 1) // Check if this is the last element
2658 print("int ___paramCB = ");
2660 println(callbackParam + ".size();");
2663 // Generate array of parameter objects
2664 print("void* paramObj[] = { ");
2665 for (int i = 0; i < methParams.size(); i++) {
2666 String paramType = methPrmTypes.get(i);
2667 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
2668 print("&___paramCB");
2670 print(getSimpleIdentifier(methParams.get(i)));
2671 if (i != methParams.size() - 1)
2675 // Check if this is "void"
2676 if (retType.equals("void")) {
2677 println("void* retObj = NULL;");
2678 println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
2679 } else { // We do have a return value
2680 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
2681 println(checkAndGetCplusType(retType) + " retVal;");
2683 println(checkAndGetCplusType(retType) + " retVal = " + generateCplusInitializer(retType) + ";");
2684 println("void* retObj = &retVal;");
2685 println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
2686 println("return retVal;");
2692 * HELPER: checkAndWriteEnumTypeCplusStub() writes the enum type (convert from enum to int)
2694 private void checkAndWriteEnumTypeCplusStub(List<String> methParams, List<String> methPrmTypes) {
2696 // Iterate and find enum declarations
2697 for (int i = 0; i < methParams.size(); i++) {
2698 String paramType = methPrmTypes.get(i);
2699 String param = methParams.get(i);
2700 if (isEnumClass(getGenericType(paramType))) {
2701 // Check if this is enum type
2702 if (isArrayOrList(paramType, param)) { // An array or vector
2703 println("int len" + i + " = " + getSimpleIdentifier(param) + ".size();");
2704 println("vector<int> paramEnum" + i + "(len" + i + ");");
2705 println("for (int i = 0; i < len" + i + "; i++) {");
2706 println("paramEnum" + i + "[i] = (int) " + getSimpleIdentifier(param) + "[i];");
2708 } else { // Just one element
2709 println("vector<int> paramEnum" + i + "(1);");
2710 println("paramEnum" + i + "[0] = (int) " + param + ";");
2718 * HELPER: checkAndWriteEnumRetTypeCplusStub() writes the enum return type (convert from enum to int)
2720 private void checkAndWriteEnumRetTypeCplusStub(String retType) {
2722 // Strips off array "[]" for return type
2723 String pureType = getSimpleArrayType(getGenericType(retType));
2724 // Take the inner type of generic
2725 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
2726 pureType = getGenericType(retType);
2727 if (isEnumClass(pureType)) {
2728 // Check if this is enum type
2729 println("vector<int> retEnumInt;");
2730 println("void* retObj = &retEnumInt;");
2731 println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
2732 if (isArrayOrList(retType, retType)) { // An array or vector
2733 println("int retLen = retEnumInt.size();");
2734 println("vector<" + pureType + "> retVal(retLen);");
2735 println("for (int i = 0; i < retLen; i++) {");
2736 println("retVal[i] = (" + pureType + ") retEnumInt[i];");
2738 } else { // Just one element
2739 println(pureType + " retVal = (" + pureType + ") retEnumInt[0];");
2741 println("return retVal;");
2747 * HELPER: checkAndWriteStructSetupCplusStub() writes the struct type setup
2749 private void checkAndWriteStructSetupCplusStub(List<String> methParams, List<String> methPrmTypes,
2750 InterfaceDecl intDecl, String method) {
2752 // Iterate and find struct declarations
2753 for (int i = 0; i < methParams.size(); i++) {
2754 String paramType = methPrmTypes.get(i);
2755 String param = methParams.get(i);
2756 String simpleType = getGenericType(paramType);
2757 if (isStructClass(simpleType)) {
2758 // Check if this is enum type
2759 println("int numParam" + i + " = 1;");
2760 int methodNumId = intDecl.getMethodNumId(method);
2761 String helperMethod = methodNumId + "struct" + i;
2762 println("int methodIdStruct" + i + " = " + intDecl.getHelperMethodNumId(helperMethod) + ";");
2763 println("string retTypeStruct" + i + " = \"void\";");
2764 println("string paramClsStruct" + i + "[] = { \"int\" };");
2765 print("int structLen" + i + " = ");
2766 if (isArrayOrList(paramType, param)) { // An array
2767 println(getSimpleArrayType(param) + ".size();");
2768 } else { // Just one element
2771 println("void* paramObjStruct" + i + "[] = { &structLen" + i + " };");
2772 println("void* retStructLen" + i + " = NULL;");
2773 println("rmiCall->remoteCall(objectId, methodIdStruct" + i +
2774 ", retTypeStruct" + i + ", paramClsStruct" + i + ", paramObjStruct" + i +
2775 ", numParam" + i + ", retStructLen" + i + ");\n");
2782 * HELPER: writeLengthStructParamClassCplusStub() writes lengths of params
2784 private void writeLengthStructParamClassCplusStub(List<String> methParams, List<String> methPrmTypes) {
2786 // Iterate and find struct declarations - count number of params
2787 for (int i = 0; i < methParams.size(); i++) {
2788 String paramType = methPrmTypes.get(i);
2789 String param = methParams.get(i);
2790 String simpleType = getGenericType(paramType);
2791 if (isStructClass(simpleType)) {
2792 int members = getNumOfMembers(simpleType);
2793 if (isArrayOrList(paramType, param)) { // An array or list
2794 String structLen = getSimpleIdentifier(param) + ".size()";
2795 print(members + "*" + structLen);
2797 print(Integer.toString(members));
2800 if (i != methParams.size() - 1) {
2808 * HELPER: writeStructMembersCplusStub() writes member parameters of struct
2810 private void writeStructMembersCplusStub(String simpleType, String paramType, String param) {
2812 // Get the struct declaration for this struct and generate initialization code
2813 StructDecl structDecl = getStructDecl(simpleType);
2814 List<String> memTypes = structDecl.getMemberTypes(simpleType);
2815 List<String> members = structDecl.getMembers(simpleType);
2816 if (isArrayOrList(paramType, param)) { // An array or list
2817 println("for(int i = 0; i < " + getSimpleIdentifier(param) + ".size(); i++) {");
2819 if (isArrayOrList(paramType, param)) { // An array or list
2820 for (int i = 0; i < members.size(); i++) {
2821 String prmTypeC = checkAndGetCplusArgClsType(memTypes.get(i), members.get(i));
2822 println("paramCls[pos] = \"" + prmTypeC + "\";");
2823 print("paramObj[pos++] = &" + getSimpleIdentifier(param) + "[i].");
2824 print(getSimpleIdentifier(members.get(i)));
2828 } else { // Just one struct element
2829 for (int i = 0; i < members.size(); i++) {
2830 String prmTypeC = checkAndGetCplusArgClsType(memTypes.get(i), members.get(i));
2831 println("paramCls[pos] = \"" + prmTypeC + "\";");
2832 print("paramObj[pos++] = &" + param + ".");
2833 print(getSimpleIdentifier(members.get(i)));
2841 * HELPER: writeStructParamClassCplusStub() writes member parameters of struct
2843 private void writeStructParamClassCplusStub(List<String> methParams, List<String> methPrmTypes) {
2845 print("int numParam = ");
2846 writeLengthStructParamClassCplusStub(methParams, methPrmTypes);
2848 println("void* paramObj[numParam];");
2849 println("string paramCls[numParam];");
2850 println("int pos = 0;");
2851 // Iterate again over the parameters
2852 for (int i = 0; i < methParams.size(); i++) {
2853 String paramType = methPrmTypes.get(i);
2854 String param = methParams.get(i);
2855 String simpleType = getGenericType(paramType);
2856 if (isStructClass(simpleType)) {
2857 writeStructMembersCplusStub(simpleType, paramType, param);
2859 String prmTypeC = checkAndGetCplusArgClsType(methPrmTypes.get(i), methParams.get(i));
2860 println("paramCls[pos] = \"" + prmTypeC + "\";");
2861 print("paramObj[pos++] = &");
2862 print(getEnumParam(methPrmTypes.get(i), getSimpleIdentifier(methParams.get(i)), i));
2871 * HELPER: writeStructRetMembersCplusStub() writes member parameters of struct for return statement
2873 private void writeStructRetMembersCplusStub(String simpleType, String retType) {
2875 // Get the struct declaration for this struct and generate initialization code
2876 StructDecl structDecl = getStructDecl(simpleType);
2877 List<String> memTypes = structDecl.getMemberTypes(simpleType);
2878 List<String> members = structDecl.getMembers(simpleType);
2879 if (isArrayOrList(retType, retType)) { // An array or list
2880 println("for(int i = 0; i < retLen; i++) {");
2882 if (isArrayOrList(retType, retType)) { // An array or list
2883 for (int i = 0; i < members.size(); i++) {
2884 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
2885 print("structRet[i]." + getSimpleIdentifier(members.get(i)));
2886 println(" = retParam" + i + "[i];");
2889 } else { // Just one struct element
2890 for (int i = 0; i < members.size(); i++) {
2891 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
2892 print("structRet." + getSimpleIdentifier(members.get(i)));
2893 println(" = retParam" + i + ";");
2896 println("return structRet;");
2901 * HELPER: writeStructReturnCplusStub() writes member parameters of struct for return statement
2903 private void writeStructReturnCplusStub(String simpleType, String retType) {
2905 // Minimum retLen is 1 if this is a single struct object
2906 println("int retLen = 0;");
2907 println("void* retLenObj = { &retLen };");
2908 // Handle the returned struct!!!
2909 println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retLenObj);");
2910 int numMem = getNumOfMembers(simpleType);
2911 println("int numRet = " + numMem + "*retLen;");
2912 println("string retCls[numRet];");
2913 println("void* retObj[numRet];");
2914 StructDecl structDecl = getStructDecl(simpleType);
2915 List<String> memTypes = structDecl.getMemberTypes(simpleType);
2916 List<String> members = structDecl.getMembers(simpleType);
2918 if (isArrayOrList(retType, retType)) { // An array or list
2919 for (int i = 0; i < members.size(); i++) {
2920 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
2921 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
2922 println(getSimpleType(getEnumType(prmType)) + " retParam" + i + "[retLen];");
2924 } else { // Just one struct element
2925 for (int i = 0; i < members.size(); i++) {
2926 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
2927 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
2928 println(getSimpleType(getEnumType(prmType)) + " retParam" + i + ";");
2931 println("int retPos = 0;");
2932 // Get the struct declaration for this struct and generate initialization code
2933 if (isArrayOrList(retType, retType)) { // An array or list
2934 println("for(int i = 0; i < retLen; i++) {");
2935 for (int i = 0; i < members.size(); i++) {
2936 String prmTypeC = checkAndGetCplusArgClsType(memTypes.get(i), members.get(i));
2937 println("retCls[retPos] = \"" + prmTypeC + "\";");
2938 println("retObj[retPos++] = &retParam" + i + "[i];");
2941 } else { // Just one struct element
2942 for (int i = 0; i < members.size(); i++) {
2943 String prmTypeC = checkAndGetCplusArgClsType(memTypes.get(i), members.get(i));
2944 println("retCls[retPos] = \"" + prmTypeC + "\";");
2945 println("retObj[retPos++] = &retParam" + i + ";");
2948 println("rmiCall->getStructObjects(retCls, numRet, retObj);");
2949 if (isArrayOrList(retType, retType)) { // An array or list
2950 println("vector<" + simpleType + "> structRet(retLen);");
2952 println(simpleType + " structRet;");
2953 writeStructRetMembersCplusStub(simpleType, retType);
2958 * HELPER: writeStdMethodBodyCplusStub() writes the standard method body in the stub class
2960 private void writeStdMethodBodyCplusStub(InterfaceDecl intDecl, List<String> methParams,
2961 List<String> methPrmTypes, String method) {
2963 checkAndWriteStructSetupCplusStub(methParams, methPrmTypes, intDecl, method);
2964 println("int methodId = " + intDecl.getMethodNumId(method) + ";");
2965 String retType = intDecl.getMethodType(method);
2966 println("string retType = \"" + checkAndGetCplusRetClsType(getStructType(getEnumType(retType))) + "\";");
2967 // Generate array of parameter types
2968 if (isStructPresent(methParams, methPrmTypes)) {
2969 writeStructParamClassCplusStub(methParams, methPrmTypes);
2971 println("int numParam = " + methParams.size() + ";");
2972 print("string paramCls[] = { ");
2973 for (int i = 0; i < methParams.size(); i++) {
2974 String paramTypeC = checkAndGetCplusArgClsType(methPrmTypes.get(i), methParams.get(i));
2975 print("\"" + paramTypeC + "\"");
2976 // Check if this is the last element (don't print a comma)
2977 if (i != methParams.size() - 1) {
2982 checkAndWriteEnumTypeCplusStub(methParams, methPrmTypes);
2983 // Generate array of parameter objects
2984 print("void* paramObj[] = { ");
2985 for (int i = 0; i < methParams.size(); i++) {
2986 print("&" + getEnumParam(methPrmTypes.get(i), getSimpleIdentifier(methParams.get(i)), i));
2987 // Check if this is the last element (don't print a comma)
2988 if (i != methParams.size() - 1) {
2994 // Check if this is "void"
2995 if (retType.equals("void")) {
2996 println("void* retObj = NULL;");
2997 println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
2998 } else { // We do have a return value
2999 // Generate array of parameter types
3000 if (isStructClass(getGenericType(getSimpleArrayType(retType)))) {
3001 writeStructReturnCplusStub(getGenericType(getSimpleArrayType(retType)), retType);
3003 // Check if the return value NONPRIMITIVES
3004 if (isEnumClass(getSimpleArrayType(getGenericType(retType)))) {
3005 checkAndWriteEnumRetTypeCplusStub(retType);
3007 //if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
3008 if (isArrayOrList(retType,retType))
3009 println(checkAndGetCplusType(retType) + " retVal;");
3011 println(checkAndGetCplusType(retType) + " retVal = " + generateCplusInitializer(retType) + ";");
3013 println("void* retObj = &retVal;");
3014 println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
3015 println("return retVal;");
3023 * HELPER: writePropertiesCplusStub() writes the properties of the stub class
3025 private void writePropertiesCplusPermission(String intface) {
3027 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3028 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3029 String newIntface = intMeth.getKey();
3030 int newObjectId = getNewIntfaceObjectId(newIntface);
3031 println("const static int object" + newObjectId + "Id = " + newObjectId + ";\t//" + newIntface);
3032 println("static set<int> set" + newObjectId + "Allowed;");
3037 * HELPER: writePropertiesCplusStub() writes the properties of the stub class
3039 private void writePropertiesCplusStub(String intface, String newIntface, boolean callbackExist, Set<String> callbackClasses) {
3041 println("IoTRMICall *rmiCall;");
3042 //println("IoTRMIObject\t\t\t*rmiObj;");
3043 println("string address;");
3044 println("vector<int> ports;\n");
3045 // Get the object Id
3046 Integer objId = mapIntfaceObjId.get(intface);
3047 println("const static int objectId = " + objId + ";");
3048 mapNewIntfaceObjId.put(newIntface, objId);
3049 mapIntfaceObjId.put(intface, objId++);
3050 if (callbackExist) {
3051 // We assume that each class only has one callback interface for now
3052 Iterator it = callbackClasses.iterator();
3053 String callbackType = (String) it.next();
3054 println("// Callback properties");
3055 println("IoTRMIObject *rmiObj;");
3056 println("vector<" + callbackType + "*> vecCallbackObj;");
3057 println("static int objIdCnt;");
3058 // Generate permission stuff for callback stubs
3059 writePropertiesCplusPermission(callbackType);
3066 * HELPER: writeConstructorCplusStub() writes the constructor of the stub class
3068 private void writeConstructorCplusStub(String newStubClass, boolean callbackExist, Set<String> callbackClasses) {
3070 println(newStubClass +
3071 "(int _port, const char* _address, int _rev, bool* _bResult, vector<int> _ports) {");
3072 println("address = _address;");
3073 println("ports = _ports;");
3074 println("rmiCall = new IoTRMICall(_port, _address, _rev, _bResult);");
3075 if (callbackExist) {
3076 Iterator it = callbackClasses.iterator();
3077 String callbackType = (String) it.next();
3078 println("thread th1 (&" + newStubClass + "::___initCallBack, this);");
3079 println("th1.detach();");
3080 println("___regCB();");
3087 * HELPER: writeDeconstructorCplusStub() writes the deconstructor of the stub class
3089 private void writeDeconstructorCplusStub(String newStubClass, boolean callbackExist, Set<String> callbackClasses) {
3091 println("~" + newStubClass + "() {");
3092 println("if (rmiCall != NULL) {");
3093 println("delete rmiCall;");
3094 println("rmiCall = NULL;");
3096 if (callbackExist) {
3097 // We assume that each class only has one callback interface for now
3098 println("if (rmiObj != NULL) {");
3099 println("delete rmiObj;");
3100 println("rmiObj = NULL;");
3102 Iterator it = callbackClasses.iterator();
3103 String callbackType = (String) it.next();
3104 println("for(" + callbackType + "* cb : vecCallbackObj) {");
3105 println("delete cb;");
3106 println("cb = NULL;");
3115 * HELPER: writeCplusMethodCallbackPermission() writes permission checks in stub for callbacks
3117 private void writeCplusMethodCallbackPermission(String intface) {
3119 println("int methodId = IoTRMIObject::getMethodId(method);");
3120 // Get all the different stubs
3121 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3122 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3123 String newIntface = intMeth.getKey();
3124 int newObjectId = getNewIntfaceObjectId(newIntface);
3125 println("if (set" + newObjectId + "Allowed.find(methodId) == set" + newObjectId + "Allowed.end()) {");
3126 println("cerr << \"Callback object for " + intface + " is not allowed to access method: \" << methodId;");
3127 println("exit(-1);");
3134 * HELPER: writeInitCallbackCplusStub() writes the initialization of callback
3136 private void writeInitCallbackCplusStub(String intface, InterfaceDecl intDecl) {
3138 println("void ___initCallBack() {");
3139 println("bool bResult = false;");
3140 println("rmiObj = new IoTRMIObject(ports[0], &bResult);");
3141 println("while (true) {");
3142 println("char* method = rmiObj->getMethodBytes();");
3143 writeCplusMethodCallbackPermission(intface);
3144 println("int objId = IoTRMIObject::getObjectId(method);");
3145 println("if (objId < vecCallbackObj.size()) { // Check if still within range");
3146 println(intface + "_CallbackSkeleton* skel = dynamic_cast<" + intface +
3147 "_CallbackSkeleton*> (vecCallbackObj.at(objId));");
3148 println("skel->invokeMethod(rmiObj);");
3151 println("cerr << \"Illegal object Id: \" << to_string(objId);");
3152 // TODO: perhaps need to change this into "throw" to make it cleaner (allow stack unfolding)
3153 println("exit(-1);");
3161 * HELPER: writeCplusInitCallbackPermission() writes the permission for callback
3163 private void writeCplusInitCallbackPermission(String intface, InterfaceDecl intDecl, boolean callbackExist) {
3165 if (callbackExist) {
3166 String method = "___initCallBack()";
3167 int methodNumId = intDecl.getHelperMethodNumId(method);
3168 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3169 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3170 String newIntface = intMeth.getKey();
3171 int newObjectId = getNewIntfaceObjectId(newIntface);
3172 println("set" + newObjectId + "Allowed.insert(" + methodNumId + ");");
3179 * HELPER: writeInitCallbackSendInfoCplusStub() writes the initialization (send info part) of callback
3181 private void writeInitCallbackSendInfoCplusStub(InterfaceDecl intDecl) {
3183 // Generate info sending part
3184 println("void ___regCB() {");
3185 println("int numParam = 3;");
3186 String method = "___initCallBack()";
3187 int methodNumId = intDecl.getHelperMethodNumId(method);
3188 println("int methodId = " + methodNumId + ";");
3189 //writeCplusCallbackPermission(intface, methodNumId);
3190 println("string retType = \"void\";");
3191 println("string paramCls[] = { \"int\", \"string\", \"int\" };");
3192 println("int rev = 0;");
3193 println("void* paramObj[] = { &ports[0], &address, &rev };");
3194 println("void* retObj = NULL;");
3195 println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
3201 * generateCPlusStubClasses() generate stubs based on the methods list in C++
3203 public void generateCPlusStubClasses() throws IOException {
3205 // Create a new directory
3206 String path = createDirectories(dir, subdir);
3207 for (String intface : mapIntfacePTH.keySet()) {
3209 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3210 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3211 // Open a new file to write into
3212 String newIntface = intMeth.getKey();
3213 String newStubClass = newIntface + "_Stub";
3214 FileWriter fw = new FileWriter(path + "/" + newStubClass + ".hpp");
3215 pw = new PrintWriter(new BufferedWriter(fw));
3216 // Write file headers
3217 println("#ifndef _" + newStubClass.toUpperCase() + "_HPP__");
3218 println("#define _" + newStubClass.toUpperCase() + "_HPP__");
3219 println("#include <iostream>");
3220 // Find out if there are callback objects
3221 Set<String> methods = intMeth.getValue();
3222 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
3223 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
3224 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
3225 boolean callbackExist = !callbackClasses.isEmpty();
3226 if (callbackExist) // Need thread library if this has callback
3227 println("#include <thread>");
3228 println("#include \"" + newIntface + ".hpp\""); println("");
3229 println("using namespace std;"); println("");
3230 println("class " + newStubClass + " : public " + newIntface); println("{");
3231 println("private:\n");
3232 writePropertiesCplusStub(intface, newIntface, callbackExist, callbackClasses);
3233 println("public:\n");
3234 // Add default constructor and destructor
3235 println(newStubClass + "() { }"); println("");
3236 writeConstructorCplusStub(newStubClass, callbackExist, callbackClasses);
3237 writeDeconstructorCplusStub(newStubClass, callbackExist, callbackClasses);
3239 writeMethodCplusStub(methods, intDecl, callbackClasses);
3240 print("}"); println(";");
3242 writePermissionInitializationCplus(intface, newStubClass, intDecl);
3243 writeObjectIdCountInitializationCplus(newStubClass, callbackExist);
3246 System.out.println("IoTCompiler: Generated stub class " + newStubClass + ".hpp...");
3253 * HELPER: writePropertiesCplusCallbackStub() writes the properties of the stub class
3255 private void writePropertiesCplusCallbackStub(String intface, String newIntface, boolean callbackExist, Set<String> callbackClasses) {
3257 println("IoTRMICall *rmiCall;");
3258 // Get the object Id
3259 println("int objectId;");
3260 if (callbackExist) {
3261 // We assume that each class only has one callback interface for now
3262 Iterator it = callbackClasses.iterator();
3263 String callbackType = (String) it.next();
3264 println("// Callback properties");
3265 println("IoTRMIObject *rmiObj;");
3266 println("vector<" + callbackType + "*> vecCallbackObj;");
3267 println("static int objIdCnt;");
3268 // TODO: Need to initialize address and ports if we want to have callback-in-callback
3269 println("string address;");
3270 println("vector<int> ports;\n");
3271 writePropertiesCplusPermission(callbackType);
3278 * HELPER: writeConstructorCplusCallbackStub() writes the constructor of the stub class
3280 private void writeConstructorCplusCallbackStub(String newStubClass, boolean callbackExist, Set<String> callbackClasses) {
3282 println(newStubClass + "(IoTRMICall* _rmiCall, int _objectId) {");
3283 println("objectId = _objectId;");
3284 println("rmiCall = _rmiCall;");
3285 if (callbackExist) {
3286 Iterator it = callbackClasses.iterator();
3287 String callbackType = (String) it.next();
3288 println("thread th1 (&" + newStubClass + "::___initCallBack, this);");
3289 println("th1.detach();");
3290 println("___regCB();");
3297 * generateCPlusCallbackStubClasses() generate callback stubs based on the methods list in C++
3299 public void generateCPlusCallbackStubClasses() throws IOException {
3301 // Create a new directory
3302 String path = createDirectories(dir, subdir);
3303 for (String intface : mapIntfacePTH.keySet()) {
3305 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3306 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3307 // Open a new file to write into
3308 String newIntface = intMeth.getKey();
3309 String newStubClass = newIntface + "_CallbackStub";
3310 FileWriter fw = new FileWriter(path + "/" + newStubClass + ".hpp");
3311 pw = new PrintWriter(new BufferedWriter(fw));
3312 // Find out if there are callback objects
3313 Set<String> methods = intMeth.getValue();
3314 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
3315 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
3316 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
3317 boolean callbackExist = !callbackClasses.isEmpty();
3318 // Write file headers
3319 println("#ifndef _" + newStubClass.toUpperCase() + "_HPP__");
3320 println("#define _" + newStubClass.toUpperCase() + "_HPP__");
3321 println("#include <iostream>");
3323 println("#include <thread>");
3324 println("#include \"" + newIntface + ".hpp\""); println("");
3325 println("using namespace std;"); println("");
3326 println("class " + newStubClass + " : public " + newIntface); println("{");
3327 println("private:\n");
3328 writePropertiesCplusCallbackStub(intface, newIntface, callbackExist, callbackClasses);
3329 println("public:\n");
3330 // Add default constructor and destructor
3331 println(newStubClass + "() { }"); println("");
3332 writeConstructorCplusCallbackStub(newStubClass, callbackExist, callbackClasses);
3333 writeDeconstructorCplusStub(newStubClass, callbackExist, callbackClasses);
3335 writeMethodCplusStub(methods, intDecl, callbackClasses);
3338 writePermissionInitializationCplus(intface, newStubClass, intDecl);
3339 writeObjectIdCountInitializationCplus(newStubClass, callbackExist);
3342 System.out.println("IoTCompiler: Generated callback stub class " + newIntface + ".hpp...");
3349 * HELPER: writePropertiesCplusSkeleton() writes the properties of the skeleton class
3351 private void writePropertiesCplusSkeleton(String intface, boolean callbackExist, Set<String> callbackClasses) {
3353 println(intface + " *mainObj;");
3355 if (callbackExist) {
3356 Iterator it = callbackClasses.iterator();
3357 String callbackType = (String) it.next();
3358 String exchangeType = checkAndGetParamClass(callbackType);
3359 println("// Callback properties");
3360 println("static int objIdCnt;");
3361 println("vector<" + exchangeType + "*> vecCallbackObj;");
3362 println("IoTRMICall *rmiCall;");
3364 println("IoTRMIObject *rmiObj;\n");
3365 // Keep track of object Ids of all stubs registered to this interface
3366 writePropertiesCplusPermission(intface);
3372 * HELPER: writeObjectIdCountInitializationCplus() writes the initialization of objIdCnt variable
3374 private void writeObjectIdCountInitializationCplus(String newSkelClass, boolean callbackExist) {
3377 println("int " + newSkelClass + "::objIdCnt = 0;");
3382 * HELPER: writePermissionInitializationCplus() writes the initialization of permission set
3384 private void writePermissionInitializationCplus(String intface, String newSkelClass, InterfaceDecl intDecl) {
3386 // Keep track of object Ids of all stubs registered to this interface
3387 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3388 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3389 String newIntface = intMeth.getKey();
3390 int newObjectId = getNewIntfaceObjectId(newIntface);
3391 print("set<int> " + newSkelClass + "::set" + newObjectId + "Allowed {");
3392 Set<String> methodIds = intMeth.getValue();
3394 for (String methodId : methodIds) {
3395 int methodNumId = intDecl.getMethodNumId(methodId);
3396 print(Integer.toString(methodNumId));
3397 // Check if this is the last element (don't print a comma)
3398 if (i != methodIds.size() - 1) {
3409 * HELPER: writeStructPermissionCplusSkeleton() writes permission for struct helper
3411 private void writeStructPermissionCplusSkeleton(Collection<String> methods, InterfaceDecl intDecl, String intface) {
3413 // Use this set to handle two same methodIds
3414 for (String method : methods) {
3415 List<String> methParams = intDecl.getMethodParams(method);
3416 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
3417 // Check for params with structs
3418 for (int i = 0; i < methParams.size(); i++) {
3419 String paramType = methPrmTypes.get(i);
3420 String param = methParams.get(i);
3421 String simpleType = getGenericType(paramType);
3422 if (isStructClass(simpleType)) {
3423 int methodNumId = intDecl.getMethodNumId(method);
3424 String helperMethod = methodNumId + "struct" + i;
3425 int helperMethodNumId = intDecl.getHelperMethodNumId(helperMethod);
3426 // Iterate over interfaces to give permissions to
3427 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3428 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3429 String newIntface = intMeth.getKey();
3430 int newObjectId = getNewIntfaceObjectId(newIntface);
3431 println("set" + newObjectId + "Allowed.insert(" + helperMethodNumId + ");");
3440 * HELPER: writeConstructorCplusSkeleton() writes the constructor of the skeleton class
3442 private void writeConstructorCplusSkeleton(String newSkelClass, String intface, boolean callbackExist, InterfaceDecl intDecl, Collection<String> methods) {
3444 println(newSkelClass + "(" + intface + " *_mainObj, int _port) {");
3445 println("bool _bResult = false;");
3446 println("mainObj = _mainObj;");
3447 println("rmiObj = new IoTRMIObject(_port, &_bResult);");
3448 writeCplusInitCallbackPermission(intface, intDecl, callbackExist);
3449 writeStructPermissionCplusSkeleton(methods, intDecl, intface);
3450 println("___waitRequestInvokeMethod();");
3456 * HELPER: writeDeconstructorCplusSkeleton() writes the deconstructor of the skeleton class
3458 private void writeDeconstructorCplusSkeleton(String newSkelClass, boolean callbackExist, Set<String> callbackClasses) {
3460 println("~" + newSkelClass + "() {");
3461 println("if (rmiObj != NULL) {");
3462 println("delete rmiObj;");
3463 println("rmiObj = NULL;");
3465 if (callbackExist) {
3466 // We assume that each class only has one callback interface for now
3467 println("if (rmiCall != NULL) {");
3468 println("delete rmiCall;");
3469 println("rmiCall = NULL;");
3471 Iterator it = callbackClasses.iterator();
3472 String callbackType = (String) it.next();
3473 String exchangeType = checkAndGetParamClass(callbackType);
3474 println("for(" + exchangeType + "* cb : vecCallbackObj) {");
3475 println("delete cb;");
3476 println("cb = NULL;");
3485 * HELPER: writeStdMethodBodyCplusSkeleton() writes the standard method body in the skeleton class
3487 private void writeStdMethodBodyCplusSkeleton(List<String> methParams, String methodId, String methodType) {
3489 if (methodType.equals("void"))
3490 print("mainObj->" + methodId + "(");
3492 print("return mainObj->" + methodId + "(");
3493 for (int i = 0; i < methParams.size(); i++) {
3495 print(getSimpleIdentifier(methParams.get(i)));
3496 // Check if this is the last element (don't print a comma)
3497 if (i != methParams.size() - 1) {
3506 * HELPER: writeInitCallbackCplusSkeleton() writes the init callback method for skeleton class
3508 private void writeInitCallbackCplusSkeleton(boolean callbackSkeleton) {
3510 // This is a callback skeleton generation
3511 if (callbackSkeleton)
3512 println("void ___regCB(IoTRMIObject* rmiObj) {");
3514 println("void ___regCB() {");
3515 println("int numParam = 3;");
3516 println("int param1 = 0;");
3517 println("string param2 = \"\";");
3518 println("int param3 = 0;");
3519 println("string paramCls[] = { \"int\", \"string\", \"int\" };");
3520 println("void* paramObj[] = { ¶m1, ¶m2, ¶m3 };");
3521 println("rmiObj->getMethodParams(paramCls, numParam, paramObj);");
3522 println("bool bResult = false;");
3523 println("rmiCall = new IoTRMICall(param1, param2.c_str(), param3, &bResult);");
3529 * HELPER: writeMethodCplusSkeleton() writes the method of the skeleton class
3531 private void writeMethodCplusSkeleton(Collection<String> methods, InterfaceDecl intDecl,
3532 Set<String> callbackClasses, boolean callbackSkeleton) {
3534 for (String method : methods) {
3536 List<String> methParams = intDecl.getMethodParams(method);
3537 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
3538 String methodId = intDecl.getMethodId(method);
3539 String methodType = checkAndGetCplusType(intDecl.getMethodType(method));
3540 print(methodType + " " + methodId + "(");
3541 boolean isCallbackMethod = false;
3542 String callbackType = null;
3543 for (int i = 0; i < methParams.size(); i++) {
3545 String origParamType = methPrmTypes.get(i);
3546 if (callbackClasses.contains(origParamType)) { // Check if this has callback object
3547 isCallbackMethod = true;
3548 callbackType = origParamType;
3550 String paramType = checkAndGetParamClass(methPrmTypes.get(i));
3551 String methPrmType = checkAndGetCplusType(paramType);
3552 String methParamComplete = checkAndGetCplusArray(methPrmType, methParams.get(i));
3553 print(methParamComplete);
3554 // Check if this is the last element (don't print a comma)
3555 if (i != methParams.size() - 1) {
3560 // Now, write the body of skeleton!
3561 writeStdMethodBodyCplusSkeleton(methParams, methodId, intDecl.getMethodType(method));
3563 if (isCallbackMethod)
3564 writeInitCallbackCplusSkeleton(callbackSkeleton);
3570 * HELPER: writeCallbackCplusNumStubs() writes the numStubs variable
3572 private void writeCallbackCplusNumStubs(List<String> methParams, List<String> methPrmTypes, String callbackType) {
3574 for (int i = 0; i < methParams.size(); i++) {
3575 String paramType = methPrmTypes.get(i);
3576 String param = methParams.get(i);
3577 //if (callbackType.equals(paramType)) {
3578 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
3579 String exchParamType = checkAndGetParamClass(paramType);
3580 // Print array if this is array or list if this is a list of callback objects
3581 println("int numStubs" + i + " = 0;");
3588 * HELPER: writeCallbackCplusStubGeneration() writes the callback stub generation part
3590 private void writeCallbackCplusStubGeneration(List<String> methParams, List<String> methPrmTypes, String callbackType) {
3592 // Iterate over callback objects
3593 for (int i = 0; i < methParams.size(); i++) {
3594 String paramType = methPrmTypes.get(i);
3595 String param = methParams.get(i);
3596 // Generate a loop if needed
3597 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
3598 String exchParamType = checkAndGetParamClass(paramType);
3599 if (isArrayOrList(paramType, param)) {
3600 println("vector<" + exchParamType + "> stub;");
3601 println("for (int objId = 0; objId < numStubs" + i + "; objId++) {");
3602 println(exchParamType + "* cb" + i + " = new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt);");
3603 println("stub" + i + ".push_back(cb);");
3604 println("vecCallbackObj.push_back(cb);");
3605 println("objIdCnt++;");
3608 println(exchParamType + "* stub" + i + " = new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt);");
3609 println("vecCallbackObj.push_back(stub" + i + ");");
3610 println("objIdCnt++;");
3618 * HELPER: checkAndWriteEnumTypeCplusSkeleton() writes the enum type (convert from enum to int)
3620 private void checkAndWriteEnumTypeCplusSkeleton(List<String> methParams, List<String> methPrmTypes) {
3622 // Iterate and find enum declarations
3623 for (int i = 0; i < methParams.size(); i++) {
3624 String paramType = methPrmTypes.get(i);
3625 String param = methParams.get(i);
3626 String simpleType = getGenericType(paramType);
3627 if (isEnumClass(simpleType)) {
3628 // Check if this is enum type
3629 if (isArrayOrList(paramType, param)) { // An array
3630 println("int len" + i + " = paramEnumInt" + i + ".size();");
3631 println("vector<" + simpleType + "> paramEnum" + i + "(len" + i + ");");
3632 println("for (int i=0; i < len" + i + "; i++) {");
3633 println("paramEnum" + i + "[i] = (" + simpleType + ") paramEnumInt" + i + "[i];");
3635 } else { // Just one element
3636 println(simpleType + " paramEnum" + i + ";");
3637 println("paramEnum" + i + " = (" + simpleType + ") paramEnumInt" + i + "[0];");
3645 * HELPER: checkAndWriteEnumRetTypeCplusSkeleton() writes the enum return type (convert from enum to int)
3647 private void checkAndWriteEnumRetTypeCplusSkeleton(String retType) {
3649 // Strips off array "[]" for return type
3650 String pureType = getSimpleArrayType(getGenericType(retType));
3651 // Take the inner type of generic
3652 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
3653 pureType = getGenericType(retType);
3654 if (isEnumClass(pureType)) {
3655 // Check if this is enum type
3657 if (isArrayOrList(retType, retType)) { // An array
3658 println("int retLen = retEnum.size();");
3659 println("vector<int> retEnumInt(retLen);");
3660 println("for (int i=0; i < retLen; i++) {");
3661 println("retEnumInt[i] = (int) retEnum[i];");
3663 } else { // Just one element
3664 println("vector<int> retEnumInt(1);");
3665 println("retEnumInt[0] = (int) retEnum;");
3672 * HELPER: writeMethodHelperReturnCplusSkeleton() writes the return statement part in skeleton
3674 private void writeMethodInputParameters(List<String> methParams, List<String> methPrmTypes,
3675 Set<String> callbackClasses, String methodId) {
3677 print(methodId + "(");
3678 for (int i = 0; i < methParams.size(); i++) {
3679 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
3680 if (callbackClasses.contains(paramType))
3682 else if (isEnumClass(getGenericType(paramType))) // Check if this is enum type
3683 print("paramEnum" + i);
3684 else if (isStructClass(getGenericType(paramType))) // Struct type
3685 print("paramStruct" + i);
3687 print(getSimpleIdentifier(methParams.get(i)));
3688 if (i != methParams.size() - 1) {
3697 * HELPER: writeMethodHelperReturnCplusSkeleton() writes the return statement part in skeleton
3699 private void writeMethodHelperReturnCplusSkeleton(InterfaceDecl intDecl, List<String> methParams,
3700 List<String> methPrmTypes, String method, boolean isCallbackMethod, String callbackType,
3701 String methodId, Set<String> callbackClasses) {
3703 println("rmiObj->getMethodParams(paramCls, numParam, paramObj);");
3704 if (isCallbackMethod)
3705 writeCallbackCplusStubGeneration(methParams, methPrmTypes, callbackType);
3706 checkAndWriteEnumTypeCplusSkeleton(methParams, methPrmTypes);
3707 writeStructMembersInitCplusSkeleton(intDecl, methParams, methPrmTypes, method);
3708 // Check if this is "void"
3709 String retType = intDecl.getMethodType(method);
3710 // Check if this is "void"
3711 if (retType.equals("void")) {
3712 writeMethodInputParameters(methParams, methPrmTypes, callbackClasses, methodId);
3713 } else { // We do have a return value
3714 if (isEnumClass(getSimpleArrayType(getGenericType(retType)))) // Enum type
3715 print(checkAndGetCplusType(retType) + " retEnum = ");
3716 else if (isStructClass(getSimpleArrayType(getGenericType(retType)))) // Struct type
3717 print(checkAndGetCplusType(retType) + " retStruct = ");
3719 print(checkAndGetCplusType(retType) + " retVal = ");
3720 writeMethodInputParameters(methParams, methPrmTypes, callbackClasses, methodId);
3721 checkAndWriteEnumRetTypeCplusSkeleton(retType);
3722 if (isStructClass(getSimpleArrayType(getGenericType(retType)))) // Struct type
3723 writeStructReturnCplusSkeleton(getSimpleArrayType(getGenericType(retType)), retType);
3724 if (isEnumClass(getSimpleArrayType(getGenericType(retType)))) // Enum type
3725 println("void* retObj = &retEnumInt;");
3727 if (!isStructClass(getSimpleArrayType(getGenericType(retType)))) // Struct type
3728 println("void* retObj = &retVal;");
3729 String retTypeC = checkAndGetCplusType(retType);
3730 if (isStructClass(getSimpleArrayType(getGenericType(retType)))) // Struct type
3731 println("rmiObj->sendReturnObj(retObj, retCls, numRetObj);");
3733 println("rmiObj->sendReturnObj(retObj, \"" + checkAndGetCplusRetClsType(getEnumType(retType)) + "\");");
3739 * HELPER: writeStdMethodHelperBodyCplusSkeleton() writes the standard method body helper in the skeleton class
3741 private void writeStdMethodHelperBodyCplusSkeleton(InterfaceDecl intDecl, List<String> methParams,
3742 List<String> methPrmTypes, String method, String methodId, Set<String> callbackClasses) {
3744 // Generate array of parameter types
3745 boolean isCallbackMethod = false;
3746 String callbackType = null;
3747 print("string paramCls[] = { ");
3748 for (int i = 0; i < methParams.size(); i++) {
3749 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
3750 if (callbackClasses.contains(paramType)) {
3751 isCallbackMethod = true;
3752 callbackType = paramType;
3754 } else { // Generate normal classes if it's not a callback object
3755 String paramTypeC = checkAndGetCplusArgClsType(methPrmTypes.get(i), methParams.get(i));
3756 print("\"" + paramTypeC + "\"");
3758 if (i != methParams.size() - 1) {
3763 println("int numParam = " + methParams.size() + ";");
3764 if (isCallbackMethod)
3765 writeCallbackCplusNumStubs(methParams, methPrmTypes, callbackType);
3766 // Generate parameters
3767 for (int i = 0; i < methParams.size(); i++) {
3768 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
3769 if (!callbackClasses.contains(paramType)) {
3770 String methParamType = methPrmTypes.get(i);
3771 if (isEnumClass(getSimpleArrayType(getGenericType(methParamType)))) {
3772 // Check if this is enum type
3773 println("vector<int> paramEnumInt" + i + ";");
3775 String methPrmType = checkAndGetCplusType(methParamType);
3776 String methParamComplete = checkAndGetCplusArray(methPrmType, methParams.get(i));
3777 println(methParamComplete + ";");
3781 // Generate array of parameter objects
3782 print("void* paramObj[] = { ");
3783 for (int i = 0; i < methParams.size(); i++) {
3784 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
3785 if (callbackClasses.contains(paramType))
3786 print("&numStubs" + i);
3787 else if (isEnumClass(getGenericType(paramType))) // Check if this is enum type
3788 print("¶mEnumInt" + i);
3790 print("&" + getSimpleIdentifier(methParams.get(i)));
3791 if (i != methParams.size() - 1) {
3796 // Write the return value part
3797 writeMethodHelperReturnCplusSkeleton(intDecl, methParams, methPrmTypes, method, isCallbackMethod,
3798 callbackType, methodId, callbackClasses);
3803 * HELPER: writeStructMembersCplusSkeleton() writes member parameters of struct
3805 private void writeStructMembersCplusSkeleton(String simpleType, String paramType,
3806 String param, String method, InterfaceDecl intDecl, int iVar) {
3808 // Get the struct declaration for this struct and generate initialization code
3809 StructDecl structDecl = getStructDecl(simpleType);
3810 List<String> memTypes = structDecl.getMemberTypes(simpleType);
3811 List<String> members = structDecl.getMembers(simpleType);
3812 int methodNumId = intDecl.getMethodNumId(method);
3813 String counter = "struct" + methodNumId + "Size" + iVar;
3814 println("int pos = 0;");
3816 if (isArrayOrList(paramType, param)) { // An array or list
3817 for (int i = 0; i < members.size(); i++) {
3818 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
3819 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
3820 println(getSimpleType(getEnumType(prmType)) + " param" + i + "[" + counter + "];");
3822 } else { // Just one struct element
3823 for (int i = 0; i < members.size(); i++) {
3824 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
3825 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
3826 println(getSimpleType(getEnumType(prmType)) + " param" + i + ";");
3829 if (isArrayOrList(paramType, param)) { // An array or list
3830 println("for(int i = 0; i < " + counter + "; i++) {");
3832 if (isArrayOrList(paramType, param)) { // An array or list
3833 for (int i = 0; i < members.size(); i++) {
3834 String prmTypeC = checkAndGetCplusArgClsType(memTypes.get(i), members.get(i));
3835 println("paramCls[pos] = \"" + prmTypeC + "\";");
3836 println("paramObj[pos++] = ¶m" + i + "[i];");
3839 } else { // Just one struct element
3840 for (int i = 0; i < members.size(); i++) {
3841 String prmTypeC = checkAndGetCplusArgClsType(memTypes.get(i), members.get(i));
3842 println("paramCls[pos] = \"" + prmTypeC + "\";");
3843 println("paramObj[pos++] = ¶m" + i + ";");
3850 * HELPER: writeStructMembersInitCplusSkeleton() writes member parameters initialization of struct
3852 private void writeStructMembersInitCplusSkeleton(InterfaceDecl intDecl, List<String> methParams,
3853 List<String> methPrmTypes, String method) {
3855 for (int i = 0; i < methParams.size(); i++) {
3856 String paramType = methPrmTypes.get(i);
3857 String param = methParams.get(i);
3858 String simpleType = getGenericType(paramType);
3859 if (isStructClass(simpleType)) {
3860 int methodNumId = intDecl.getMethodNumId(method);
3861 String counter = "struct" + methodNumId + "Size" + i;
3863 if (isArrayOrList(paramType, param)) { // An array or list
3864 println("vector<" + simpleType + "> paramStruct" + i + "(" + counter + ");");
3866 println(simpleType + " paramStruct" + i + ";");
3867 // Initialize members
3868 StructDecl structDecl = getStructDecl(simpleType);
3869 List<String> members = structDecl.getMembers(simpleType);
3870 List<String> memTypes = structDecl.getMemberTypes(simpleType);
3871 if (isArrayOrList(paramType, param)) { // An array or list
3872 println("for(int i = 0; i < " + counter + "; i++) {");
3873 for (int j = 0; j < members.size(); j++) {
3874 print("paramStruct" + i + "[i]." + getSimpleIdentifier(members.get(j)));
3875 println(" = param" + j + "[i];");
3878 } else { // Just one struct element
3879 for (int j = 0; j < members.size(); j++) {
3880 print("paramStruct" + i + "." + getSimpleIdentifier(members.get(j)));
3881 println(" = param" + j + ";");
3890 * HELPER: writeStructReturnCplusSkeleton() writes parameters of struct for return statement
3892 private void writeStructReturnCplusSkeleton(String simpleType, String retType) {
3894 // Minimum retLen is 1 if this is a single struct object
3895 if (isArrayOrList(retType, retType))
3896 println("int retLen = retStruct.size();");
3897 else // Just single struct object
3898 println("int retLen = 1;");
3899 println("void* retLenObj = &retLen;");
3900 println("rmiObj->sendReturnObj(retLenObj, \"int\");");
3901 int numMem = getNumOfMembers(simpleType);
3902 println("int numRetObj = " + numMem + "*retLen;");
3903 println("string retCls[numRetObj];");
3904 println("void* retObj[numRetObj];");
3905 println("int retPos = 0;");
3906 // Get the struct declaration for this struct and generate initialization code
3907 StructDecl structDecl = getStructDecl(simpleType);
3908 List<String> memTypes = structDecl.getMemberTypes(simpleType);
3909 List<String> members = structDecl.getMembers(simpleType);
3910 if (isArrayOrList(retType, retType)) { // An array or list
3911 println("for(int i = 0; i < retLen; i++) {");
3912 for (int i = 0; i < members.size(); i++) {
3913 String prmTypeC = checkAndGetCplusArgClsType(memTypes.get(i), members.get(i));
3914 println("retCls[retPos] = \"" + prmTypeC + "\";");
3915 print("retObj[retPos++] = &retStruct[i].");
3916 print(getEnumParam(memTypes.get(i), getSimpleIdentifier(members.get(i)), i));
3920 } else { // Just one struct element
3921 for (int i = 0; i < members.size(); i++) {
3922 String prmTypeC = checkAndGetCplusArgClsType(memTypes.get(i), members.get(i));
3923 println("retCls[retPos] = \"" + prmTypeC + "\";");
3924 print("retObj[retPos++] = &retStruct.");
3925 print(getEnumParam(memTypes.get(i), getSimpleIdentifier(members.get(i)), i));
3934 * HELPER: writeMethodHelperStructCplusSkeleton() writes the struct in skeleton
3936 private void writeMethodHelperStructCplusSkeleton(InterfaceDecl intDecl, List<String> methParams,
3937 List<String> methPrmTypes, String method, String methodId, Set<String> callbackClasses) {
3939 // Generate array of parameter objects
3940 boolean isCallbackMethod = false;
3941 String callbackType = null;
3942 print("int numParam = ");
3943 writeLengthStructParamClassSkeleton(methParams, methPrmTypes, method, intDecl);
3945 println("string paramCls[numParam];");
3946 println("void* paramObj[numParam];");
3947 // Iterate again over the parameters
3948 for (int i = 0; i < methParams.size(); i++) {
3949 String paramType = methPrmTypes.get(i);
3950 String param = methParams.get(i);
3951 String simpleType = getGenericType(paramType);
3952 if (isStructClass(simpleType)) {
3953 writeStructMembersCplusSkeleton(simpleType, paramType, param, method, intDecl, i);
3955 String prmType = returnGenericCallbackType(methPrmTypes.get(i));
3956 if (callbackClasses.contains(prmType)) {
3957 isCallbackMethod = true;
3958 callbackType = paramType;
3959 writeCallbackCplusNumStubs(methParams, methPrmTypes, callbackType);
3960 println("paramCls[pos] = \"int\";");
3961 println("paramObj[pos++] = &numStubs" + i + ";");
3962 } else { // Generate normal classes if it's not a callback object
3963 String paramTypeC = checkAndGetCplusType(methPrmTypes.get(i));
3964 if (isEnumClass(getGenericType(paramTypeC))) { // Check if this is enum type
3965 println("vector<int> paramEnumInt" + i + ";");
3967 String methParamComplete = checkAndGetCplusArray(paramTypeC, methParams.get(i));
3968 println(methParamComplete + ";");
3970 String prmTypeC = checkAndGetCplusArgClsType(methPrmTypes.get(i), methParams.get(i));
3971 println("paramCls[pos] = \"" + prmTypeC + "\";");
3972 if (isEnumClass(getGenericType(paramType))) // Check if this is enum type
3973 println("paramObj[pos++] = ¶mEnumInt" + i);
3975 println("paramObj[pos++] = &" + getSimpleIdentifier(methParams.get(i)) + ";");
3979 // Write the return value part
3980 writeMethodHelperReturnCplusSkeleton(intDecl, methParams, methPrmTypes, method, isCallbackMethod,
3981 callbackType, methodId, callbackClasses);
3986 * HELPER: writeMethodHelperCplusSkeleton() writes the method helper of the skeleton class
3988 private void writeMethodHelperCplusSkeleton(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
3990 // Use this set to handle two same methodIds
3991 Set<String> uniqueMethodIds = new HashSet<String>();
3992 for (String method : methods) {
3994 List<String> methParams = intDecl.getMethodParams(method);
3995 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
3996 if (isStructPresent(methParams, methPrmTypes)) { // Treat struct differently
3997 String methodId = intDecl.getMethodId(method);
3999 String helperMethod = methodId;
4000 if (uniqueMethodIds.contains(methodId))
4001 helperMethod = helperMethod + intDecl.getMethodNumId(method);
4003 uniqueMethodIds.add(methodId);
4004 String retType = intDecl.getMethodType(method);
4005 print(helperMethod + "(");
4006 boolean begin = true;
4007 for (int i = 0; i < methParams.size(); i++) { // Print size variables
4008 String paramType = methPrmTypes.get(i);
4009 String param = methParams.get(i);
4010 String simpleType = getGenericType(paramType);
4011 if (isStructClass(simpleType)) {
4012 if (!begin) { // Generate comma for not the beginning variable
4013 print(", "); begin = false;
4015 int methodNumId = intDecl.getMethodNumId(method);
4016 print("int struct" + methodNumId + "Size" + i);
4020 writeMethodHelperStructCplusSkeleton(intDecl, methParams, methPrmTypes, method, methodId, callbackClasses);
4023 String methodId = intDecl.getMethodId(method);
4025 String helperMethod = methodId;
4026 if (uniqueMethodIds.contains(methodId))
4027 helperMethod = helperMethod + intDecl.getMethodNumId(method);
4029 uniqueMethodIds.add(methodId);
4030 // Check if this is "void"
4031 String retType = intDecl.getMethodType(method);
4032 println(helperMethod + "() {");
4033 // Now, write the helper body of skeleton!
4034 writeStdMethodHelperBodyCplusSkeleton(intDecl, methParams, methPrmTypes, method, methodId, callbackClasses);
4038 // Write method helper for structs
4039 writeMethodHelperStructSetupCplusSkeleton(methods, intDecl);
4044 * HELPER: writeMethodHelperStructSetupCplusSkeleton() writes the method helper of struct in skeleton class
4046 private void writeMethodHelperStructSetupCplusSkeleton(Collection<String> methods,
4047 InterfaceDecl intDecl) {
4049 // Use this set to handle two same methodIds
4050 for (String method : methods) {
4052 List<String> methParams = intDecl.getMethodParams(method);
4053 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4054 // Check for params with structs
4055 for (int i = 0; i < methParams.size(); i++) {
4056 String paramType = methPrmTypes.get(i);
4057 String param = methParams.get(i);
4058 String simpleType = getGenericType(paramType);
4059 if (isStructClass(simpleType)) {
4060 int methodNumId = intDecl.getMethodNumId(method);
4062 String helperMethod = methodNumId + "struct" + i;
4063 println(helperMethod + "() {");
4064 // Now, write the helper body of skeleton!
4065 println("string paramCls[] = { \"int\" };");
4066 println("int numParam = 1;");
4067 println("int param0 = 0;");
4068 println("void* paramObj[] = { ¶m0 };");
4069 println("rmiObj->getMethodParams(paramCls, numParam, paramObj);");
4070 println("return param0;");
4079 * HELPER: writeMethodHelperStructSetupCplusCallbackSkeleton() writes the method helper of struct in skeleton class
4081 private void writeMethodHelperStructSetupCplusCallbackSkeleton(Collection<String> methods,
4082 InterfaceDecl intDecl) {
4084 // Use this set to handle two same methodIds
4085 for (String method : methods) {
4087 List<String> methParams = intDecl.getMethodParams(method);
4088 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4089 // Check for params with structs
4090 for (int i = 0; i < methParams.size(); i++) {
4091 String paramType = methPrmTypes.get(i);
4092 String param = methParams.get(i);
4093 String simpleType = getGenericType(paramType);
4094 if (isStructClass(simpleType)) {
4095 int methodNumId = intDecl.getMethodNumId(method);
4097 String helperMethod = methodNumId + "struct" + i;
4098 println(helperMethod + "(IoTRMIObject* rmiObj) {");
4099 // Now, write the helper body of skeleton!
4100 println("string paramCls[] = { \"int\" };");
4101 println("int numParam = 1;");
4102 println("int param0 = 0;");
4103 println("void* paramObj[] = { ¶m0 };");
4104 println("rmiObj->getMethodParams(paramCls, numParam, paramObj);");
4105 println("return param0;");
4114 * HELPER: writeCplusMethodPermission() writes permission checks in skeleton
4116 private void writeCplusMethodPermission(String intface) {
4118 // Get all the different stubs
4119 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
4120 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
4121 String newIntface = intMeth.getKey();
4122 int newObjectId = getNewIntfaceObjectId(newIntface);
4123 println("if (_objectId == object" + newObjectId + "Id) {");
4124 println("if (set" + newObjectId + "Allowed.find(methodId) == set" + newObjectId + "Allowed.end()) {");
4125 println("cerr << \"Object with object Id: \" << _objectId << \" is not allowed to access method: \" << methodId << endl;");
4126 println("exit(-1);");
4130 println("cerr << \"Object Id: \" << _objectId << \" not recognized!\" << endl;");
4131 println("exit(-1);");
4138 * HELPER: writeCplusWaitRequestInvokeMethod() writes the main loop of the skeleton class
4140 private void writeCplusWaitRequestInvokeMethod(Collection<String> methods, InterfaceDecl intDecl, boolean callbackExist, String intface) {
4142 // Use this set to handle two same methodIds
4143 Set<String> uniqueMethodIds = new HashSet<String>();
4144 println("void ___waitRequestInvokeMethod() {");
4145 // Write variables here if we have callbacks or enums or structs
4146 writeCountVarStructSkeleton(methods, intDecl);
4147 println("while (true) {");
4148 println("rmiObj->getMethodBytes();");
4149 println("int _objectId = rmiObj->getObjectId();");
4150 println("int methodId = rmiObj->getMethodId();");
4151 // Generate permission check
4152 writeCplusMethodPermission(intface);
4153 println("switch (methodId) {");
4154 // Print methods and method Ids
4155 for (String method : methods) {
4156 String methodId = intDecl.getMethodId(method);
4157 int methodNumId = intDecl.getMethodNumId(method);
4158 print("case " + methodNumId + ": ___");
4159 String helperMethod = methodId;
4160 if (uniqueMethodIds.contains(methodId))
4161 helperMethod = helperMethod + methodNumId;
4163 uniqueMethodIds.add(methodId);
4164 print(helperMethod + "(");
4165 writeInputCountVarStructSkeleton(method, intDecl);
4166 println("); break;");
4168 String method = "___initCallBack()";
4169 // Print case -9999 (callback handler) if callback exists
4170 if (callbackExist) {
4171 int methodId = intDecl.getHelperMethodNumId(method);
4172 println("case " + methodId + ": ___regCB(); break;");
4174 writeMethodCallStructSkeleton(methods, intDecl);
4175 println("default: ");
4176 println("cerr << \"Method Id \" << methodId << \" not recognized!\" << endl;");
4177 println("throw exception();");
4185 * generateCplusSkeletonClass() generate skeletons based on the methods list in C++
4187 public void generateCplusSkeletonClass() throws IOException {
4189 // Create a new directory
4190 String path = createDirectories(dir, subdir);
4191 for (String intface : mapIntfacePTH.keySet()) {
4192 // Open a new file to write into
4193 String newSkelClass = intface + "_Skeleton";
4194 FileWriter fw = new FileWriter(path + "/" + newSkelClass + ".hpp");
4195 pw = new PrintWriter(new BufferedWriter(fw));
4196 // Write file headers
4197 println("#ifndef _" + newSkelClass.toUpperCase() + "_HPP__");
4198 println("#define _" + newSkelClass.toUpperCase() + "_HPP__");
4199 println("#include <iostream>");
4200 println("#include \"" + intface + ".hpp\"\n");
4201 // Pass in set of methods and get import classes
4202 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4203 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
4204 List<String> methods = intDecl.getMethods();
4205 Set<String> includeClasses = getIncludeClasses(methods, intDecl, intface, true);
4206 List<String> stdIncludeClasses = getStandardCplusIncludeClasses();
4207 List<String> allIncludeClasses = getAllLibClasses(stdIncludeClasses, includeClasses);
4208 printIncludeStatements(allIncludeClasses); println("");
4209 println("using namespace std;\n");
4210 // Find out if there are callback objects
4211 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
4212 boolean callbackExist = !callbackClasses.isEmpty();
4213 // Write class header
4214 println("class " + newSkelClass + " : public " + intface); println("{");
4215 println("private:\n");
4217 writePropertiesCplusSkeleton(intface, callbackExist, callbackClasses);
4218 println("public:\n");
4219 // Write constructor
4220 writeConstructorCplusSkeleton(newSkelClass, intface, callbackExist, intDecl, methods);
4221 // Write deconstructor
4222 writeDeconstructorCplusSkeleton(newSkelClass, callbackExist, callbackClasses);
4224 writeMethodCplusSkeleton(methods, intDecl, callbackClasses, false);
4225 // Write method helper
4226 writeMethodHelperCplusSkeleton(methods, intDecl, callbackClasses);
4227 // Write waitRequestInvokeMethod() - main loop
4228 writeCplusWaitRequestInvokeMethod(methods, intDecl, callbackExist, intface);
4230 writePermissionInitializationCplus(intface, newSkelClass, intDecl);
4231 writeObjectIdCountInitializationCplus(newSkelClass, callbackExist);
4234 System.out.println("IoTCompiler: Generated skeleton class " + newSkelClass + ".hpp...");
4240 * HELPER: writePropertiesCplusCallbackSkeleton() writes the properties of the callback skeleton class
4242 private void writePropertiesCplusCallbackSkeleton(String intface, boolean callbackExist, Set<String> callbackClasses) {
4244 println(intface + " *mainObj;");
4245 // Keep track of object Ids of all stubs registered to this interface
4246 println("int objectId;");
4248 if (callbackExist) {
4249 Iterator it = callbackClasses.iterator();
4250 String callbackType = (String) it.next();
4251 String exchangeType = checkAndGetParamClass(callbackType);
4252 println("// Callback properties");
4253 println("IoTRMICall* rmiCall;");
4254 println("vector<" + exchangeType + "*> vecCallbackObj;");
4255 println("static int objIdCnt;");
4262 * HELPER: writeConstructorCplusCallbackSkeleton() writes the constructor of the skeleton class
4264 private void writeConstructorCplusCallbackSkeleton(String newSkelClass, String intface, boolean callbackExist, InterfaceDecl intDecl, Collection<String> methods) {
4266 println(newSkelClass + "(" + intface + " *_mainObj, int _objectId) {");
4267 println("mainObj = _mainObj;");
4268 println("objectId = _objectId;");
4274 * HELPER: writeDeconstructorCplusStub() writes the deconstructor of the stub class
4276 private void writeDeconstructorCplusCallbackSkeleton(String newStubClass, boolean callbackExist,
4277 Set<String> callbackClasses) {
4279 println("~" + newStubClass + "() {");
4280 if (callbackExist) {
4281 // We assume that each class only has one callback interface for now
4282 println("if (rmiCall != NULL) {");
4283 println("delete rmiCall;");
4284 println("rmiCall = NULL;");
4286 Iterator it = callbackClasses.iterator();
4287 String callbackType = (String) it.next();
4288 String exchangeType = checkAndGetParamClass(callbackType);
4289 println("for(" + exchangeType + "* cb : vecCallbackObj) {");
4290 println("delete cb;");
4291 println("cb = NULL;");
4300 * HELPER: writeMethodHelperCplusCallbackSkeleton() writes the method helper of callback skeleton class
4302 private void writeMethodHelperCplusCallbackSkeleton(Collection<String> methods, InterfaceDecl intDecl,
4303 Set<String> callbackClasses) {
4305 // Use this set to handle two same methodIds
4306 Set<String> uniqueMethodIds = new HashSet<String>();
4307 for (String method : methods) {
4309 List<String> methParams = intDecl.getMethodParams(method);
4310 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4311 if (isStructPresent(methParams, methPrmTypes)) { // Treat struct differently
4312 String methodId = intDecl.getMethodId(method);
4314 String helperMethod = methodId;
4315 if (uniqueMethodIds.contains(methodId))
4316 helperMethod = helperMethod + intDecl.getMethodNumId(method);
4318 uniqueMethodIds.add(methodId);
4319 String retType = intDecl.getMethodType(method);
4320 print(helperMethod + "(");
4321 boolean begin = true;
4322 for (int i = 0; i < methParams.size(); i++) { // Print size variables
4323 String paramType = methPrmTypes.get(i);
4324 String param = methParams.get(i);
4325 String simpleType = getGenericType(paramType);
4326 if (isStructClass(simpleType)) {
4327 if (!begin) { // Generate comma for not the beginning variable
4328 print(", "); begin = false;
4330 int methodNumId = intDecl.getMethodNumId(method);
4331 print("int struct" + methodNumId + "Size" + i);
4334 println(", IoTRMIObject* rmiObj) {");
4335 writeMethodHelperStructCplusSkeleton(intDecl, methParams, methPrmTypes, method, methodId, callbackClasses);
4338 String methodId = intDecl.getMethodId(method);
4340 String helperMethod = methodId;
4341 if (uniqueMethodIds.contains(methodId))
4342 helperMethod = helperMethod + intDecl.getMethodNumId(method);
4344 uniqueMethodIds.add(methodId);
4345 // Check if this is "void"
4346 String retType = intDecl.getMethodType(method);
4347 println(helperMethod + "(IoTRMIObject* rmiObj) {");
4348 // Now, write the helper body of skeleton!
4349 writeStdMethodHelperBodyCplusSkeleton(intDecl, methParams, methPrmTypes, method, methodId, callbackClasses);
4353 // Write method helper for structs
4354 writeMethodHelperStructSetupCplusCallbackSkeleton(methods, intDecl);
4359 * HELPER: writeCplusCallbackWaitRequestInvokeMethod() writes the request invoke method of the skeleton callback class
4361 private void writeCplusCallbackWaitRequestInvokeMethod(Collection<String> methods, InterfaceDecl intDecl,
4362 boolean callbackExist) {
4364 // Use this set to handle two same methodIds
4365 Set<String> uniqueMethodIds = new HashSet<String>();
4366 println("void invokeMethod(IoTRMIObject* rmiObj) {");
4367 // Write variables here if we have callbacks or enums or structs
4368 writeCountVarStructSkeleton(methods, intDecl);
4369 // Write variables here if we have callbacks or enums or structs
4370 println("int methodId = rmiObj->getMethodId();");
4371 // TODO: code the permission check here!
4372 println("switch (methodId) {");
4373 // Print methods and method Ids
4374 for (String method : methods) {
4375 String methodId = intDecl.getMethodId(method);
4376 int methodNumId = intDecl.getMethodNumId(method);
4377 print("case " + methodNumId + ": ___");
4378 String helperMethod = methodId;
4379 if (uniqueMethodIds.contains(methodId))
4380 helperMethod = helperMethod + methodNumId;
4382 uniqueMethodIds.add(methodId);
4383 print(helperMethod + "(");
4384 if (writeInputCountVarStructSkeleton(method, intDecl))
4385 println(", rmiObj); break;");
4387 println("rmiObj); break;");
4389 String method = "___initCallBack()";
4390 // Print case -9999 (callback handler) if callback exists
4391 if (callbackExist) {
4392 int methodId = intDecl.getHelperMethodNumId(method);
4393 println("case " + methodId + ": ___regCB(rmiObj); break;");
4395 writeMethodCallStructCallbackSkeleton(methods, intDecl);
4396 println("default: ");
4397 println("cerr << \"Method Id \" << methodId << \" not recognized!\" << endl;");
4398 println("throw exception();");
4405 * generateCplusCallbackSkeletonClass() generate callback skeletons based on the methods list in C++
4407 public void generateCplusCallbackSkeletonClass() throws IOException {
4409 // Create a new directory
4410 String path = createDirectories(dir, subdir);
4411 for (String intface : mapIntfacePTH.keySet()) {
4412 // Open a new file to write into
4413 String newSkelClass = intface + "_CallbackSkeleton";
4414 FileWriter fw = new FileWriter(path + "/" + newSkelClass + ".hpp");
4415 pw = new PrintWriter(new BufferedWriter(fw));
4416 // Write file headers
4417 println("#ifndef _" + newSkelClass.toUpperCase() + "_HPP__");
4418 println("#define _" + newSkelClass.toUpperCase() + "_HPP__");
4419 println("#include <iostream>");
4420 println("#include \"" + intface + ".hpp\"\n");
4421 // Pass in set of methods and get import classes
4422 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4423 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
4424 List<String> methods = intDecl.getMethods();
4425 Set<String> includeClasses = getIncludeClasses(methods, intDecl, intface, true);
4426 List<String> stdIncludeClasses = getStandardCplusIncludeClasses();
4427 List<String> allIncludeClasses = getAllLibClasses(stdIncludeClasses, includeClasses);
4428 printIncludeStatements(allIncludeClasses); println("");
4429 // Find out if there are callback objects
4430 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
4431 boolean callbackExist = !callbackClasses.isEmpty();
4432 println("using namespace std;\n");
4433 // Write class header
4434 println("class " + newSkelClass + " : public " + intface); println("{");
4435 println("private:\n");
4437 writePropertiesCplusCallbackSkeleton(intface, callbackExist, callbackClasses);
4438 println("public:\n");
4439 // Write constructor
4440 writeConstructorCplusCallbackSkeleton(newSkelClass, intface, callbackExist, intDecl, methods);
4441 // Write deconstructor
4442 writeDeconstructorCplusCallbackSkeleton(newSkelClass, callbackExist, callbackClasses);
4444 writeMethodCplusSkeleton(methods, intDecl, callbackClasses, true);
4445 // Write method helper
4446 writeMethodHelperCplusCallbackSkeleton(methods, intDecl, callbackClasses);
4447 // Write waitRequestInvokeMethod() - main loop
4448 writeCplusCallbackWaitRequestInvokeMethod(methods, intDecl, callbackExist);
4450 writeObjectIdCountInitializationCplus(newSkelClass, callbackExist);
4453 System.out.println("IoTCompiler: Generated callback skeleton class " + newSkelClass + ".hpp...");
4459 * generateInitializer() generate initializer based on type
4461 public String generateCplusInitializer(String type) {
4463 // Generate dummy returns for now
4464 if (type.equals("short")||
4465 type.equals("int") ||
4466 type.equals("long") ||
4467 type.equals("float")||
4468 type.equals("double")) {
4471 } else if ( type.equals("String") ||
4472 type.equals("string")) {
4475 } else if ( type.equals("char") ||
4476 type.equals("byte")) {
4479 } else if ( type.equals("boolean")) {
4489 * setDirectory() sets a new directory for stub files
4491 public void setDirectory(String _subdir) {
4498 * printUsage() prints the usage of this compiler
4500 public static void printUsage() {
4502 System.out.println();
4503 System.out.println("Sentinel interface and stub compiler version 1.0");
4504 System.out.println("Copyright (c) 2015-2016 University of California, Irvine - Programming Language Group.");
4505 System.out.println("All rights reserved.");
4506 System.out.println("Usage:");
4507 System.out.println("\tjava IoTCompiler -help / --help / -h\n");
4508 System.out.println("\t\tDisplay this help texts\n\n");
4509 System.out.println("\tjava IoTCompiler [<main-policy-file> <req-policy-file>]");
4510 System.out.println("\tjava IoTCompiler [<main-policy-file> <req-policy-file>] [options]\n");
4511 System.out.println("\t\tTake one or more pairs of main-req policy files, and generate Java and/or C++ files\n");
4512 System.out.println("Options:");
4513 System.out.println("\t-java\t<directory>\tGenerate Java stub files");
4514 System.out.println("\t-cplus\t<directory>\tGenerate C++ stub files");
4515 System.out.println();
4520 * parseFile() prepares Lexer and Parser objects, then parses the file
4522 public static ParseNode parseFile(String file) {
4524 ParseNode pn = null;
4526 ComplexSymbolFactory csf = new ComplexSymbolFactory();
4527 ScannerBuffer lexer =
4528 new ScannerBuffer(new Lexer(new BufferedReader(new FileReader(file)),csf));
4529 Parser parse = new Parser(lexer,csf);
4530 pn = (ParseNode) parse.parse().value;
4531 } catch (Exception e) {
4532 e.printStackTrace();
4533 throw new Error("IoTCompiler: ERROR parsing policy file or wrong command line option: " + file + "\n");
4541 * Basic helper functions
4544 boolean newline=true;
4547 private void print(String str) {
4550 if (str.equals("}"))
4552 for(int i=0; i<tab; i++)
4562 * This function converts Java to C++ type for compilation
4564 private String convertType(String type) {
4566 if (mapPrimitives.containsKey(type))
4567 return mapPrimitives.get(type);
4574 * A collection of methods with print-to-file functionality
4576 private void println(String str) {
4579 if (str.contains("}") && !str.contains("{"))
4581 for(int i=0; i<tab; i++)
4590 private void updatetabbing(String str) {
4592 tablevel+=count(str,'{')-count(str,'}');
4596 private int count(String str, char key) {
4597 char[] array = str.toCharArray();
4599 for(int i=0; i<array.length; i++) {
4600 if (array[i] == key)
4607 private void createDirectory(String dirName) {
4609 File file = new File(dirName);
4610 if (!file.exists()) {
4612 System.out.println("IoTCompiler: Directory " + dirName + " has been created!");
4614 System.out.println("IoTCompiler: Failed to create directory " + dirName + "!");
4617 System.out.println("IoTCompiler: Directory " + dirName + " exists...");
4622 // Create a directory and possibly a sub directory
4623 private String createDirectories(String dir, String subdir) {
4626 createDirectory(path);
4627 if (subdir != null) {
4628 path = path + "/" + subdir;
4629 createDirectory(path);
4635 // Inserting array members into a Map object
4636 // that maps arrKey to arrVal objects
4637 private void arraysToMap(Map map, Object[] arrKey, Object[] arrVal) {
4639 for(int i = 0; i < arrKey.length; i++) {
4641 map.put(arrKey[i], arrVal[i]);
4646 // Check and find object Id for new interface in mapNewIntfaceObjId (callbacks)
4647 // Throw an error if the new interface is not found!
4648 // Basically the compiler needs to parse the policy (and requires) files for callback class first
4649 private int getNewIntfaceObjectId(String newIntface) {
4651 if (!mapNewIntfaceObjId.containsKey(newIntface)) {
4652 throw new Error("IoTCompiler: Need to parse policy and requires files for callback class first! " +
4653 "Please place the two files for callback class in front...\n");
4655 int retObjId = mapNewIntfaceObjId.get(newIntface);
4661 // Return parameter category, i.e. PRIMITIVES, NONPRIMITIVES, USERDEFINED, ENUM, or STRUCT
4662 private ParamCategory getParamCategory(String paramType) {
4664 if (mapPrimitives.containsKey(paramType)) {
4665 return ParamCategory.PRIMITIVES;
4666 // We can either use mapNonPrimitivesJava or mapNonPrimitivesCplus here
4667 } else if (mapNonPrimitivesJava.containsKey(getSimpleType(paramType))) {
4668 return ParamCategory.NONPRIMITIVES;
4669 } else if (isEnumClass(paramType)) {
4670 return ParamCategory.ENUM;
4671 } else if (isStructClass(paramType)) {
4672 return ParamCategory.STRUCT;
4674 return ParamCategory.USERDEFINED;
4678 // Return full class name for non-primitives to generate Java import statements
4679 // e.g. java.util.Set for Set
4680 private String getNonPrimitiveJavaClass(String paramNonPrimitives) {
4682 return mapNonPrimitivesJava.get(paramNonPrimitives);
4686 // Return full class name for non-primitives to generate Cplus include statements
4687 // e.g. #include <set> for Set
4688 private String getNonPrimitiveCplusClass(String paramNonPrimitives) {
4690 return mapNonPrimitivesCplus.get(paramNonPrimitives);
4694 // Get simple types, e.g. HashSet for HashSet<...>
4695 // Basically strip off the "<...>"
4696 private String getSimpleType(String paramType) {
4698 // Check if this is generics
4699 if(paramType.contains("<")) {
4700 String[] type = paramType.split("<");
4707 // Generate a set of standard classes for import statements
4708 private List<String> getStandardJavaIntfaceImportClasses() {
4710 List<String> importClasses = new ArrayList<String>();
4711 // Add the standard list first
4712 importClasses.add("java.util.List");
4713 importClasses.add("java.util.ArrayList");
4715 return importClasses;
4719 // Generate a set of standard classes for import statements
4720 private List<String> getStandardJavaImportClasses() {
4722 List<String> importClasses = new ArrayList<String>();
4723 // Add the standard list first
4724 importClasses.add("java.io.IOException");
4725 importClasses.add("java.util.List");
4726 importClasses.add("java.util.ArrayList");
4727 importClasses.add("java.util.Arrays");
4728 importClasses.add("iotrmi.Java.IoTRMICall");
4729 importClasses.add("iotrmi.Java.IoTRMIObject");
4731 return importClasses;
4735 // Generate a set of standard classes for import statements
4736 private List<String> getStandardCplusIncludeClasses() {
4738 List<String> importClasses = new ArrayList<String>();
4739 // Add the standard list first
4740 importClasses.add("<vector>");
4741 importClasses.add("<set>");
4742 importClasses.add("\"IoTRMICall.hpp\"");
4743 importClasses.add("\"IoTRMIObject.hpp\"");
4745 return importClasses;
4749 // Combine all classes for import statements
4750 private List<String> getAllLibClasses(Collection<String> stdLibClasses, Collection<String> libClasses) {
4752 List<String> allLibClasses = new ArrayList<String>(stdLibClasses);
4753 // Iterate over the list of import classes
4754 for (String str : libClasses) {
4755 if (!allLibClasses.contains(str)) {
4756 allLibClasses.add(str);
4759 return allLibClasses;
4764 // Generate a set of classes for import statements
4765 private Set<String> getImportClasses(Collection<String> methods, InterfaceDecl intDecl) {
4767 Set<String> importClasses = new HashSet<String>();
4768 for (String method : methods) {
4769 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4770 for (String paramType : methPrmTypes) {
4772 String simpleType = getSimpleType(paramType);
4773 if (getParamCategory(simpleType) == ParamCategory.NONPRIMITIVES) {
4774 importClasses.add(getNonPrimitiveJavaClass(simpleType));
4778 return importClasses;
4782 // Handle and return the correct enum declaration
4783 // In Java, if we declare enum in Camera interface, then it becomes "Camera.<enum>"
4784 private String getEnumParamDecl(String type, InterfaceDecl intDecl) {
4786 // Strips off array "[]" for return type
4787 String pureType = getSimpleArrayType(type);
4788 // Take the inner type of generic
4789 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
4790 pureType = getTypeOfGeneric(type)[0];
4791 if (isEnumClass(pureType)) {
4792 String enumType = intDecl.getInterface() + "." + type;
4799 // Handle and return the correct type
4800 private String getEnumParam(String type, String param, int i) {
4802 // Strips off array "[]" for return type
4803 String pureType = getSimpleArrayType(type);
4804 // Take the inner type of generic
4805 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
4806 pureType = getTypeOfGeneric(type)[0];
4807 if (isEnumClass(pureType)) {
4808 String enumParam = "paramEnum" + i;
4815 // Handle and return the correct enum declaration translate into int[]
4816 private String getEnumType(String type) {
4818 // Strips off array "[]" for return type
4819 String pureType = getSimpleArrayType(type);
4820 // Take the inner type of generic
4821 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
4822 pureType = getGenericType(type);
4823 if (isEnumClass(pureType)) {
4824 String enumType = "int[]";
4830 // Handle and return the correct enum declaration translate into int* for C
4831 private String getEnumCplusClsType(String type) {
4833 // Strips off array "[]" for return type
4834 String pureType = getSimpleArrayType(type);
4835 // Take the inner type of generic
4836 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
4837 pureType = getGenericType(type);
4838 if (isEnumClass(pureType)) {
4839 String enumType = "int*";
4846 // Handle and return the correct struct declaration
4847 private String getStructType(String type) {
4849 // Strips off array "[]" for return type
4850 String pureType = getSimpleArrayType(type);
4851 // Take the inner type of generic
4852 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
4853 pureType = getGenericType(type);
4854 if (isStructClass(pureType)) {
4855 String structType = "int";
4862 // Check if this an enum declaration
4863 private boolean isEnumClass(String type) {
4865 // Just iterate over the set of interfaces
4866 for (String intface : mapIntfacePTH.keySet()) {
4867 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4868 EnumDecl enumDecl = (EnumDecl) decHandler.getEnumDecl(intface);
4869 Set<String> setEnumDecl = enumDecl.getEnumDeclarations();
4870 if (setEnumDecl.contains(type))
4877 // Check if this an struct declaration
4878 private boolean isStructClass(String type) {
4880 // Just iterate over the set of interfaces
4881 for (String intface : mapIntfacePTH.keySet()) {
4882 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4883 StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
4884 List<String> listStructDecl = structDecl.getStructTypes();
4885 if (listStructDecl.contains(type))
4892 // Return a struct declaration
4893 private StructDecl getStructDecl(String type) {
4895 // Just iterate over the set of interfaces
4896 for (String intface : mapIntfacePTH.keySet()) {
4897 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4898 StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
4899 List<String> listStructDecl = structDecl.getStructTypes();
4900 if (listStructDecl.contains(type))
4907 // Return number of members (-1 if not found)
4908 private int getNumOfMembers(String type) {
4910 // Just iterate over the set of interfaces
4911 for (String intface : mapIntfacePTH.keySet()) {
4912 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4913 StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
4914 List<String> listStructDecl = structDecl.getStructTypes();
4915 if (listStructDecl.contains(type))
4916 return structDecl.getNumOfMembers(type);
4922 // Generate a set of classes for include statements
4923 private Set<String> getIncludeClasses(Collection<String> methods, InterfaceDecl intDecl, String intface, boolean needExchange) {
4925 Set<String> includeClasses = new HashSet<String>();
4926 for (String method : methods) {
4928 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4929 List<String> methParams = intDecl.getMethodParams(method);
4930 for (int i = 0; i < methPrmTypes.size(); i++) {
4932 String simpleType = getSimpleType(methPrmTypes.get(i));
4933 String param = methParams.get(i);
4934 if (getParamCategory(simpleType) == ParamCategory.NONPRIMITIVES) {
4935 includeClasses.add("<" + getNonPrimitiveCplusClass(simpleType) + ">");
4936 } else if (getParamCategory(simpleType) == ParamCategory.USERDEFINED) {
4937 // For original interface, we need it exchanged... not for stub interfaces
4939 includeClasses.add("\"" + exchangeParamType(simpleType) + ".hpp\"");
4940 includeClasses.add("\"" + exchangeParamType(simpleType) + "_CallbackStub.hpp\"");
4942 includeClasses.add("\"" + simpleType + ".hpp\"");
4943 includeClasses.add("\"" + simpleType + "_CallbackSkeleton.hpp\"");
4945 } else if (getParamCategory(getSimpleArrayType(simpleType)) == ParamCategory.ENUM) {
4946 includeClasses.add("\"" + simpleType + ".hpp\"");
4947 } else if (getParamCategory(getSimpleArrayType(simpleType)) == ParamCategory.STRUCT) {
4948 includeClasses.add("\"" + simpleType + ".hpp\"");
4949 } else if (param.contains("[]")) {
4950 // Check if this is array for C++; translate into vector
4951 includeClasses.add("<vector>");
4955 return includeClasses;
4959 // Generate a set of callback classes
4960 private Set<String> getCallbackClasses(Collection<String> methods, InterfaceDecl intDecl) {
4962 Set<String> callbackClasses = new HashSet<String>();
4963 for (String method : methods) {
4965 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4966 List<String> methParams = intDecl.getMethodParams(method);
4967 for (int i = 0; i < methPrmTypes.size(); i++) {
4969 String type = methPrmTypes.get(i);
4970 if (getParamCategory(type) == ParamCategory.USERDEFINED) {
4971 callbackClasses.add(type);
4972 } else if (getParamCategory(type) == ParamCategory.NONPRIMITIVES) {
4973 // Can be a List<...> of callback objects ...
4974 String genericType = getTypeOfGeneric(type)[0];
4975 if (getParamCategory(type) == ParamCategory.USERDEFINED) {
4976 callbackClasses.add(type);
4981 return callbackClasses;
4985 // Print import statements into file
4986 private void printImportStatements(Collection<String> importClasses) {
4988 for(String cls : importClasses) {
4989 println("import " + cls + ";");
4994 // Print include statements into file
4995 private void printIncludeStatements(Collection<String> includeClasses) {
4997 for(String cls : includeClasses) {
4998 println("#include " + cls);
5003 // Get the C++ version of a non-primitive type
5004 // e.g. set for Set and map for Map
5005 // Input nonPrimitiveType has to be generics in format
5006 private String[] getTypeOfGeneric(String nonPrimitiveType) {
5008 // Handle <, >, and , for 2-type generic/template
5009 String[] substr = nonPrimitiveType.split("<")[1].split(">")[0].split(",");
5014 // Gets generic type inside "<" and ">"
5015 private String getGenericType(String type) {
5017 // Handle <, >, and , for 2-type generic/template
5018 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES) {
5019 String[] substr = type.split("<")[1].split(">")[0].split(",");
5026 // This helper function strips off array declaration, e.g. int[] becomes int
5027 private String getSimpleArrayType(String type) {
5029 // Handle [ for array declaration
5030 String substr = type;
5031 if (type.contains("[]")) {
5032 substr = type.split("\\[\\]")[0];
5038 // This helper function strips off array declaration, e.g. D[] becomes D
5039 private String getSimpleIdentifier(String ident) {
5041 // Handle [ for array declaration
5042 String substr = ident;
5043 if (ident.contains("[]")) {
5044 substr = ident.split("\\[\\]")[0];
5050 // Checks and gets type in C++
5051 private String checkAndGetCplusType(String paramType) {
5053 if (getParamCategory(paramType) == ParamCategory.PRIMITIVES) {
5054 return convertType(paramType);
5055 } else if (getParamCategory(paramType) == ParamCategory.NONPRIMITIVES) {
5057 // Check for generic/template format
5058 if (paramType.contains("<") && paramType.contains(">")) {
5060 String genericClass = getSimpleType(paramType);
5061 String[] genericType = getTypeOfGeneric(paramType);
5062 String cplusTemplate = null;
5063 if (genericType.length == 1) // Generic/template with one type
5064 cplusTemplate = getNonPrimitiveCplusClass(genericClass) +
5065 "<" + convertType(genericType[0]) + ">";
5066 else // Generic/template with two types
5067 cplusTemplate = getNonPrimitiveCplusClass(genericClass) +
5068 "<" + convertType(genericType[0]) + "," + convertType(genericType[1]) + ">";
5069 return cplusTemplate;
5071 return getNonPrimitiveCplusClass(paramType);
5072 } else if(paramType.contains("[]")) { // Array type (used for return type only)
5073 String cArray = "vector<" + convertType(getSimpleArrayType(paramType)) + ">";
5075 } else if(getParamCategory(paramType) == ParamCategory.USERDEFINED) {
5076 return paramType + "*";
5078 // Just return it as is if it's not non-primitives
5080 //return checkAndGetParamClass(paramType, true);
5084 // Detect array declaration, e.g. int A[],
5085 // then generate "int A[]" in C++ as "vector<int> A"
5086 private String checkAndGetCplusArray(String paramType, String param) {
5088 String paramComplete = null;
5089 // Check for array declaration
5090 if (param.contains("[]")) {
5091 paramComplete = "vector<" + paramType + "> " + param.replace("[]","");
5093 // Just return it as is if it's not an array
5094 paramComplete = paramType + " " + param;
5096 return paramComplete;
5100 // Detect array declaration, e.g. int A[],
5101 // then generate "int A[]" in C++ as "vector<int> A"
5102 // This method just returns the type
5103 private String checkAndGetCplusArrayType(String paramType) {
5105 String paramTypeRet = null;
5106 // Check for array declaration
5107 if (paramType.contains("[]")) {
5108 String type = paramType.split("\\[\\]")[0];
5109 paramTypeRet = checkAndGetCplusType(type) + "[]";
5110 } else if (paramType.contains("vector")) {
5111 // Just return it as is if it's not an array
5112 String type = paramType.split("<")[1].split(">")[0];
5113 paramTypeRet = checkAndGetCplusType(type) + "[]";
5115 paramTypeRet = paramType;
5117 return paramTypeRet;
5121 // Detect array declaration, e.g. int A[],
5122 // then generate "int A[]" in C++ as "vector<int> A"
5123 // This method just returns the type
5124 private String checkAndGetCplusArrayType(String paramType, String param) {
5126 String paramTypeRet = null;
5127 // Check for array declaration
5128 if (param.contains("[]")) {
5129 paramTypeRet = checkAndGetCplusType(paramType) + "[]";
5130 } else if (paramType.contains("vector")) {
5131 // Just return it as is if it's not an array
5132 String type = paramType.split("<")[1].split(">")[0];
5133 paramTypeRet = checkAndGetCplusType(type) + "[]";
5135 paramTypeRet = paramType;
5137 return paramTypeRet;
5141 // Return the class type for class resolution (for return value)
5142 // - Check and return C++ array class, e.g. int A[] into int*
5143 // - Check and return C++ vector class, e.g. List<Integer> A into vector<int>
5144 private String checkAndGetCplusRetClsType(String paramType) {
5146 String paramTypeRet = null;
5147 // Check for array declaration
5148 if (paramType.contains("[]")) {
5149 String type = paramType.split("\\[\\]")[0];
5150 paramTypeRet = getSimpleArrayType(type) + "*";
5151 } else if (paramType.contains("<") && paramType.contains(">")) {
5152 // Just return it as is if it's not an array
5153 String type = paramType.split("<")[1].split(">")[0];
5154 paramTypeRet = "vector<" + getGenericType(type) + ">";
5156 paramTypeRet = paramType;
5158 return paramTypeRet;
5162 // Return the class type for class resolution (for method arguments)
5163 // - Check and return C++ array class, e.g. int A[] into int*
5164 // - Check and return C++ vector class, e.g. List<Integer> A into vector<int>
5165 private String checkAndGetCplusArgClsType(String paramType, String param) {
5167 String paramTypeRet = getEnumCplusClsType(paramType);
5168 if (!paramTypeRet.equals(paramType))
5169 // Just return if it is an enum type
5170 // Type will still be the same if it's not an enum type
5171 return paramTypeRet;
5173 // Check for array declaration
5174 if (param.contains("[]")) {
5175 paramTypeRet = getSimpleArrayType(paramType) + "*";
5176 } else if (paramType.contains("<") && paramType.contains(">")) {
5177 // Just return it as is if it's not an array
5178 String type = paramType.split("<")[1].split(">")[0];
5179 paramTypeRet = "vector<" + getGenericType(type) + ">";
5181 paramTypeRet = paramType;
5183 return paramTypeRet;
5187 // Detect array declaration, e.g. int A[],
5188 // then generate type "int[]"
5189 private String checkAndGetArray(String paramType, String param) {
5191 String paramTypeRet = null;
5192 // Check for array declaration
5193 if (param.contains("[]")) {
5194 paramTypeRet = paramType + "[]";
5196 // Just return it as is if it's not an array
5197 paramTypeRet = paramType;
5199 return paramTypeRet;
5203 // Is array or list?
5204 private boolean isArrayOrList(String paramType, String param) {
5206 // Check for array declaration
5209 else if (isList(paramType))
5217 // For return type we use retType as input parameter
5218 private boolean isArray(String param) {
5220 // Check for array declaration
5221 if (param.contains("[]"))
5229 private boolean isList(String paramType) {
5231 // Check for array declaration
5232 if (paramType.contains("List"))
5239 // Get the right type for a callback object
5240 private String checkAndGetParamClass(String paramType) {
5242 // Check if this is generics
5243 if(getParamCategory(paramType) == ParamCategory.USERDEFINED) {
5244 return exchangeParamType(paramType);
5250 // Returns the other interface for type-checking purposes for USERDEFINED
5251 // classes based on the information provided in multiple policy files
5252 // e.g. return CameraWithXXX instead of Camera
5253 private String exchangeParamType(String intface) {
5255 // Param type that's passed is the interface name we need to look for
5256 // in the map of interfaces, based on available policy files.
5257 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
5258 if (decHandler != null) {
5259 // We've found the required interface policy files
5260 RequiresDecl reqDecl = (RequiresDecl) decHandler.getRequiresDecl(intface);
5261 Set<String> setExchInt = reqDecl.getInterfaces();
5262 if (setExchInt.size() == 1) {
5263 Iterator iter = setExchInt.iterator();
5264 return (String) iter.next();
5266 throw new Error("IoTCompiler: Ambiguous stub interfaces: " + setExchInt.toString() +
5267 ". Only one new interface can be declared if the object " + intface +
5268 " needs to be passed in as an input parameter!\n");
5271 // NULL value - this means policy files missing
5272 throw new Error("IoTCompiler: Parameter type lookup failed for " + intface +
5273 "... Please provide the necessary policy files for user-defined types." +
5274 " If this is an array please type the brackets after the variable name," +
5275 " e.g. \"String str[]\", not \"String[] str\"." +
5276 " If this is a Collections (Java) / STL (C++) type, this compiler only" +
5277 " supports List/ArrayList (Java) or list (C++).\n");
5282 public static void main(String[] args) throws Exception {
5284 // If there is no argument or just "--help" or "-h", then invoke printUsage()
5285 if ((args[0].equals("-help") ||
5286 args[0].equals("--help")||
5287 args[0].equals("-h")) ||
5288 (args.length == 0)) {
5290 IoTCompiler.printUsage();
5292 } else if (args.length > 1) {
5294 IoTCompiler comp = new IoTCompiler();
5297 // Parse main policy file
5298 ParseNode pnPol = IoTCompiler.parseFile(args[i]);
5299 // Parse "requires" policy file
5300 ParseNode pnReq = IoTCompiler.parseFile(args[i+1]);
5301 // Get interface name
5302 String intface = ParseTreeHandler.getOrigIntface(pnPol);
5303 comp.setDataStructures(intface, pnPol, pnReq);
5304 comp.getMethodsForIntface(intface);
5306 // 1) Check if this is the last option before "-java" or "-cplus"
5307 // 2) Check if this is really the last option (no "-java" or "-cplus")
5308 } while(!args[i].equals("-java") &&
5309 !args[i].equals("-cplus") &&
5312 // Generate everything if we don't see "-java" or "-cplus"
5313 if (i == args.length) {
5314 comp.generateEnumJava();
5315 comp.generateStructJava();
5316 comp.generateJavaLocalInterfaces();
5317 comp.generateJavaInterfaces();
5318 comp.generateJavaStubClasses();
5319 comp.generateJavaCallbackStubClasses();
5320 comp.generateJavaSkeletonClass();
5321 comp.generateJavaCallbackSkeletonClass();
5322 comp.generateEnumCplus();
5323 comp.generateStructCplus();
5324 comp.generateCplusLocalInterfaces();
5325 comp.generateCPlusInterfaces();
5326 comp.generateCPlusStubClasses();
5327 comp.generateCPlusCallbackStubClasses();
5328 comp.generateCplusSkeletonClass();
5329 comp.generateCplusCallbackSkeletonClass();
5331 // Check other options
5332 while(i < args.length) {
5334 if (!args[i].equals("-java") &&
5335 !args[i].equals("-cplus")) {
5336 throw new Error("IoTCompiler: ERROR - unrecognized command line option: " + args[i] + "\n");
5338 if (i + 1 < args.length) {
5339 comp.setDirectory(args[i+1]);
5341 throw new Error("IoTCompiler: ERROR - please provide <directory> after option: " + args[i] + "\n");
5343 if (args[i].equals("-java")) {
5344 comp.generateEnumJava();
5345 comp.generateStructJava();
5346 comp.generateJavaLocalInterfaces();
5347 comp.generateJavaInterfaces();
5348 comp.generateJavaStubClasses();
5349 comp.generateJavaCallbackStubClasses();
5350 comp.generateJavaSkeletonClass();
5351 comp.generateJavaCallbackSkeletonClass();
5353 comp.generateEnumCplus();
5354 comp.generateStructCplus();
5355 comp.generateCplusLocalInterfaces();
5356 comp.generateCPlusInterfaces();
5357 comp.generateCPlusStubClasses();
5358 comp.generateCPlusCallbackStubClasses();
5359 comp.generateCplusSkeletonClass();
5360 comp.generateCplusCallbackSkeletonClass();
5367 // Need to at least have exactly 2 parameters, i.e. main policy file and requires file
5368 IoTCompiler.printUsage();
5369 throw new Error("IoTCompiler: At least two arguments (main and requires policy files) have to be provided!\n");