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 = getSimpleType(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 = getSimpleType(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 = param + ".length";
686 print(members + "*" + structLen);
687 } else if (isList(paramType)) { // A list
688 String structLen = 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 < " + param + ".length; i++) {");
712 } else if (isList(paramType)) { // A list
713 println("for(int i = 0; i < " + param + ".size(); i++) {");
715 if (isArrayOrList(param, paramType)) { // An array or list
716 for (int i = 0; i < members.size(); i++) {
717 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
718 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
719 print("paramObj[pos++] = " + param + "[i].");
720 print(getSimpleIdentifier(members.get(i)));
724 } else { // Just one struct element
725 for (int i = 0; i < members.size(); i++) {
726 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
727 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
728 print("paramObj[pos++] = " + param + ".");
729 print(getSimpleIdentifier(members.get(i)));
737 * HELPER: writeStructParamClassJavaStub() writes parameters if struct is present
739 private void writeStructParamClassJavaStub(List<String> methParams, List<String> methPrmTypes) {
741 print("int paramLen = ");
742 writeLengthStructParamClassJavaStub(methParams, methPrmTypes);
744 println("Object[] paramObj = new Object[paramLen];");
745 println("Class<?>[] paramCls = new Class<?>[paramLen];");
746 println("int pos = 0;");
747 // Iterate again over the parameters
748 for (int i = 0; i < methParams.size(); i++) {
749 String paramType = methPrmTypes.get(i);
750 String param = methParams.get(i);
751 String simpleType = getGenericType(paramType);
752 if (isStructClass(simpleType)) {
753 writeStructMembersJavaStub(simpleType, paramType, param);
755 String prmType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
756 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
757 print("paramObj[pos++] = ");
758 print(getEnumParam(methPrmTypes.get(i), getSimpleIdentifier(methParams.get(i)), i));
767 * HELPER: writeStructRetMembersJavaStub() writes parameters of struct for return statement
769 private void writeStructRetMembersJavaStub(String simpleType, String retType) {
771 // Get the struct declaration for this struct and generate initialization code
772 StructDecl structDecl = getStructDecl(simpleType);
773 List<String> memTypes = structDecl.getMemberTypes(simpleType);
774 List<String> members = structDecl.getMembers(simpleType);
775 if (isArrayOrList(retType, retType)) { // An array or list
776 println("for(int i = 0; i < retLen; i++) {");
778 if (isArray(retType)) { // An array
779 for (int i = 0; i < members.size(); i++) {
780 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
781 print("structRet[i]." + getSimpleIdentifier(members.get(i)));
782 println(" = (" + getSimpleType(getEnumType(prmType)) + ") retObj[retObjPos++];");
785 } else if (isList(retType)) { // A list
786 println(simpleType + " structRetMem = new " + simpleType + "();");
787 for (int i = 0; i < members.size(); i++) {
788 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
789 print("structRetMem." + getSimpleIdentifier(members.get(i)));
790 println(" = (" + getSimpleType(getEnumType(prmType)) + ") retObj[retObjPos++];");
792 println("structRet.add(structRetMem);");
794 } else { // Just one struct element
795 for (int i = 0; i < members.size(); i++) {
796 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
797 print("structRet." + getSimpleIdentifier(members.get(i)));
798 println(" = (" + getSimpleType(getEnumType(prmType)) + ") retObj[retObjPos++];");
801 println("return structRet;");
806 * HELPER: writeStructReturnJavaStub() writes parameters if struct is present for return statement
808 private void writeStructReturnJavaStub(String simpleType, String retType) {
810 // Handle the returned struct!!!
811 println("Object retLenObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
812 // Minimum retLen is 1 if this is a single struct object
813 println("int retLen = (int) retLenObj;");
814 int numMem = getNumOfMembers(simpleType);
815 println("Class<?>[] retCls = new Class<?>[" + numMem + "*retLen];");
816 println("Class<?>[] retClsVal = new Class<?>[" + numMem + "*retLen];");
817 println("int retPos = 0;");
818 // Get the struct declaration for this struct and generate initialization code
819 StructDecl structDecl = getStructDecl(simpleType);
820 List<String> memTypes = structDecl.getMemberTypes(simpleType);
821 List<String> members = structDecl.getMembers(simpleType);
822 if (isArrayOrList(retType, retType)) { // An array or list
823 println("for(int i = 0; i < retLen; i++) {");
824 for (int i = 0; i < members.size(); i++) {
825 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
826 println("retCls[retPos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
827 println("retClsVal[retPos++] = null;");
830 } else { // Just one struct element
831 for (int i = 0; i < members.size(); i++) {
832 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
833 println("retCls[retPos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
834 println("retClsVal[retPos++] = null;");
837 println("Object[] retObj = rmiCall.getStructObjects(retCls, retClsVal);");
838 if (isArray(retType)) { // An array
839 println(simpleType + "[] structRet = new " + simpleType + "[retLen];");
840 println("for(int i = 0; i < retLen; i++) {");
841 println("structRet[i] = new " + simpleType + "();");
843 } else if (isList(retType)) { // A list
844 println("List<" + simpleType + "> structRet = new ArrayList<" + simpleType + ">();");
846 println(simpleType + " structRet = new " + simpleType + "();");
847 println("int retObjPos = 0;");
848 writeStructRetMembersJavaStub(simpleType, retType);
853 * HELPER: writeStdMethodBodyJavaStub() writes the standard method body in the stub class
855 private void writeStdMethodBodyJavaStub(InterfaceDecl intDecl, List<String> methParams,
856 List<String> methPrmTypes, String method) {
858 checkAndWriteStructSetupJavaStub(methParams, methPrmTypes, intDecl, method);
859 println("int methodId = " + intDecl.getMethodNumId(method) + ";");
860 String retType = intDecl.getMethodType(method);
861 println("Class<?> retType = " + getSimpleType(getStructType(getEnumType(retType))) + ".class;");
862 checkAndWriteEnumTypeJavaStub(methParams, methPrmTypes);
863 // Generate array of parameter types
864 if (isStructPresent(methParams, methPrmTypes)) {
865 writeStructParamClassJavaStub(methParams, methPrmTypes);
867 print("Class<?>[] paramCls = new Class<?>[] { ");
868 for (int i = 0; i < methParams.size(); i++) {
869 String paramType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
870 print(getSimpleType(getEnumType(paramType)) + ".class");
871 // Check if this is the last element (don't print a comma)
872 if (i != methParams.size() - 1) {
877 // Generate array of parameter objects
878 print("Object[] paramObj = new Object[] { ");
879 for (int i = 0; i < methParams.size(); i++) {
880 print(getEnumParam(methPrmTypes.get(i), getSimpleIdentifier(methParams.get(i)), i));
881 // Check if this is the last element (don't print a comma)
882 if (i != methParams.size() - 1) {
888 // Check if this is "void"
889 if (retType.equals("void")) {
890 println("rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
891 } else { // We do have a return value
892 // Generate array of parameter types
893 if (isStructClass(getGenericType(getSimpleArrayType(retType)))) {
894 writeStructReturnJavaStub(getGenericType(getSimpleArrayType(retType)), retType);
896 // This is an enum type
897 if (getParamCategory(getGenericType(getSimpleArrayType(retType))) == ParamCategory.ENUM) {
898 println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
899 checkAndWriteEnumRetTypeJavaStub(retType);
900 } else if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES) {
901 // Check if the return value NONPRIMITIVES
902 String retGenValType = getGenericType(retType);
903 println("Class<?> retGenValType = " + retGenValType + ".class;");
904 println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, retGenValType, paramCls, paramObj);");
905 println("return (" + retType + ")retObj;");
907 println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
908 println("return (" + retType + ")retObj;");
916 * HELPER: returnGenericCallbackType() returns the callback type
918 private String returnGenericCallbackType(String paramType) {
920 if (getParamCategory(paramType) == ParamCategory.NONPRIMITIVES)
921 return getTypeOfGeneric(paramType)[0];
928 * HELPER: checkCallbackType() checks the callback type
930 private boolean checkCallbackType(String paramType, String callbackType) {
932 String prmType = returnGenericCallbackType(paramType);
933 return callbackType.equals(prmType);
938 * HELPER: writeCallbackMethodBodyJavaStub() writes the callback method of the stub class
940 private void writeCallbackMethodBodyJavaStub(InterfaceDecl intDecl, List<String> methParams,
941 List<String> methPrmTypes, String method, String callbackType) {
944 // Check if this is single object, array, or list of objects
945 for (int i = 0; i < methParams.size(); i++) {
946 String paramType = methPrmTypes.get(i);
947 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
948 String param = methParams.get(i);
949 if (isArrayOrList(paramType, param)) { // Generate loop
950 println("for (" + paramType + " cb : " + getSimpleIdentifier(param) + ") {");
951 println(callbackType + "_CallbackSkeleton skel = new " + callbackType + "_CallbackSkeleton(cb, objIdCnt++);");
953 println(callbackType + "_CallbackSkeleton skel = new " + callbackType + "_CallbackSkeleton(" +
954 getSimpleIdentifier(param) + ", objIdCnt++);");
955 println("listCallbackObj.add(skel);");
956 if (isArrayOrList(paramType, param))
961 println(" catch (Exception ex) {");
962 println("ex.printStackTrace();");
963 println("throw new Error(\"Exception when generating skeleton objects!\");");
965 println("int methodId = " + intDecl.getMethodNumId(method) + ";");
966 String retType = intDecl.getMethodType(method);
967 println("Class<?> retType = " + getSimpleType(getEnumType(retType)) + ".class;");
968 // Generate array of parameter types
969 print("Class<?>[] paramCls = new Class<?>[] { ");
970 for (int i = 0; i < methParams.size(); i++) {
971 String paramType = methPrmTypes.get(i);
972 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
974 } else { // Generate normal classes if it's not a callback object
975 String prmType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
976 print(getSimpleType(prmType) + ".class");
978 if (i != methParams.size() - 1) // Check if this is the last element
982 // Generate array of parameter objects
983 print("Object[] paramObj = new Object[] { ");
984 for (int i = 0; i < methParams.size(); i++) {
985 String paramType = methPrmTypes.get(i);
986 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
987 //if (isArray(methPrmTypes.get(i), methParams.get(i)))
988 if (isArray(methParams.get(i)))
989 print(getSimpleIdentifier(methParams.get(i)) + ".length");
990 else if (isList(methPrmTypes.get(i)))
991 print(getSimpleIdentifier(methParams.get(i)) + ".size()");
993 print("new Integer(1)");
995 print(getSimpleIdentifier(methParams.get(i)));
996 if (i != methParams.size() - 1)
1000 // Check if this is "void"
1001 if (retType.equals("void")) {
1002 println("rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
1003 } else { // We do have a return value
1004 // Check if the return value NONPRIMITIVES
1005 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES) {
1006 String[] retGenValType = getTypeOfGeneric(retType);
1007 println("Class<?> retGenValType = " + retGenValType[0] + ".class;");
1008 println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, retGenValType, paramCls, paramObj);");
1009 println("return (" + retType + ")retObj;");
1011 println("Object retObj = rmiCall.remoteCall(objectId, methodId, retType, null, paramCls, paramObj);");
1012 println("return (" + retType + ")retObj;");
1019 * HELPER: writeMethodJavaStub() writes the methods of the stub class
1021 private void writeMethodJavaStub(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
1023 for (String method : methods) {
1025 List<String> methParams = intDecl.getMethodParams(method);
1026 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1027 print("public " + intDecl.getMethodType(method) + " " +
1028 intDecl.getMethodId(method) + "(");
1029 boolean isCallbackMethod = false;
1030 String callbackType = null;
1031 for (int i = 0; i < methParams.size(); i++) {
1033 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
1034 // Check if this has callback object
1035 if (callbackClasses.contains(paramType)) {
1036 isCallbackMethod = true;
1037 callbackType = paramType;
1038 // Even if there're 2 callback arguments, we expect them to be of the same interface
1040 print(methPrmTypes.get(i) + " " + methParams.get(i));
1041 // Check if this is the last element (don't print a comma)
1042 if (i != methParams.size() - 1) {
1047 // Now, write the body of stub!
1048 if (isCallbackMethod)
1049 writeCallbackMethodBodyJavaStub(intDecl, methParams, methPrmTypes, method, callbackType);
1051 writeStdMethodBodyJavaStub(intDecl, methParams, methPrmTypes, method);
1053 // Write the init callback helper method
1054 if (isCallbackMethod)
1055 writeInitCallbackJavaStub(callbackType, intDecl);
1061 * generateJavaStubClasses() generate stubs based on the methods list in Java
1063 public void generateJavaStubClasses() throws IOException {
1065 // Create a new directory
1066 String path = createDirectories(dir, subdir);
1067 for (String intface : mapIntfacePTH.keySet()) {
1069 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
1070 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
1072 // Open a new file to write into
1073 String newIntface = intMeth.getKey();
1074 String newStubClass = newIntface + "_Stub";
1075 FileWriter fw = new FileWriter(path + "/" + newStubClass + ".java");
1076 pw = new PrintWriter(new BufferedWriter(fw));
1077 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
1078 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
1079 // Pass in set of methods and get import classes
1080 Set<String> methods = intMeth.getValue();
1081 Set<String> importClasses = getImportClasses(methods, intDecl);
1082 List<String> stdImportClasses = getStandardJavaImportClasses();
1083 List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
1084 printImportStatements(allImportClasses); println("");
1085 // Find out if there are callback objects
1086 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
1087 boolean callbackExist = !callbackClasses.isEmpty();
1088 // Write class header
1089 println("public class " + newStubClass + " implements " + newIntface + " {\n");
1091 writePropertiesJavaStub(intface, newIntface, callbackExist, callbackClasses);
1092 // Write constructor
1093 writeConstructorJavaStub(intface, newStubClass, callbackExist, callbackClasses);
1095 writeMethodJavaStub(intMeth.getValue(), intDecl, callbackClasses);
1098 System.out.println("IoTCompiler: Generated stub class " + newStubClass + ".java...");
1105 * HELPER: writePropertiesJavaCallbackStub() writes the properties of the callback stub class
1107 private void writePropertiesJavaCallbackStub(String intface, String newIntface, boolean callbackExist, Set<String> callbackClasses) {
1109 println("private IoTRMICall rmiCall;");
1110 println("private String address;");
1111 println("private int[] ports;\n");
1112 // Get the object Id
1113 println("private static int objectId = 0;");
1114 if (callbackExist) {
1115 // We assume that each class only has one callback interface for now
1116 Iterator it = callbackClasses.iterator();
1117 String callbackType = (String) it.next();
1118 println("// Callback properties");
1119 println("private IoTRMIObject rmiObj;");
1120 println("List<" + callbackType + "> listCallbackObj;");
1121 println("private static int objIdCnt = 0;");
1122 // Generate permission stuff for callback stubs
1123 DeclarationHandler decHandler = mapIntDeclHand.get(callbackType);
1124 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(callbackType);
1125 writePropertiesJavaPermission(callbackType, intDecl);
1132 * HELPER: writeConstructorJavaCallbackStub() writes the constructor of the callback stub class
1134 private void writeConstructorJavaCallbackStub(String intface, String newStubClass, boolean callbackExist, Set<String> callbackClasses) {
1136 // TODO: If we want callback in callback, then we need to add address and port initializations
1137 println("public " + newStubClass + "(IoTRMICall _rmiCall, int _objectId) throws Exception {");
1138 println("objectId = _objectId;");
1139 println("rmiCall = _rmiCall;");
1140 if (callbackExist) {
1141 Iterator it = callbackClasses.iterator();
1142 String callbackType = (String) it.next();
1143 writeConstructorJavaPermission(intface);
1144 println("listCallbackObj = new ArrayList<" + callbackType + ">();");
1145 println("___initCallBack();");
1146 println("// TODO: Add address and port initialization here if we want callback in callback!");
1153 * generateJavaCallbackStubClasses() generate callback stubs based on the methods list in Java
1155 * Callback stubs gets the IoTRMICall objects from outside of the class as contructor input
1156 * because all these stubs are populated by the class that takes in this object as a callback
1157 * object. In such a class, we only use one socket, hence one IoTRMICall, for all callback objects.
1159 public void generateJavaCallbackStubClasses() throws IOException {
1161 // Create a new directory
1162 String path = createDirectories(dir, subdir);
1163 for (String intface : mapIntfacePTH.keySet()) {
1165 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
1166 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
1168 // Open a new file to write into
1169 String newIntface = intMeth.getKey();
1170 String newStubClass = newIntface + "_CallbackStub";
1171 FileWriter fw = new FileWriter(path + "/" + newStubClass + ".java");
1172 pw = new PrintWriter(new BufferedWriter(fw));
1173 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
1174 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
1175 // Pass in set of methods and get import classes
1176 Set<String> methods = intMeth.getValue();
1177 Set<String> importClasses = getImportClasses(methods, intDecl);
1178 List<String> stdImportClasses = getStandardJavaImportClasses();
1179 List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
1180 printImportStatements(allImportClasses); println("");
1181 // Find out if there are callback objects
1182 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
1183 boolean callbackExist = !callbackClasses.isEmpty();
1184 // Write class header
1185 println("public class " + newStubClass + " implements " + newIntface + " {\n");
1187 writePropertiesJavaCallbackStub(intface, newIntface, callbackExist, callbackClasses);
1188 // Write constructor
1189 writeConstructorJavaCallbackStub(intface, newStubClass, callbackExist, callbackClasses);
1191 // TODO: perhaps need to generate callback for callback
1192 writeMethodJavaStub(intMeth.getValue(), intDecl, callbackClasses);
1195 System.out.println("IoTCompiler: Generated callback stub class " + newStubClass + ".java...");
1202 * HELPER: writePropertiesJavaSkeleton() writes the properties of the skeleton class
1204 private void writePropertiesJavaSkeleton(String intface, boolean callbackExist, InterfaceDecl intDecl) {
1206 println("private " + intface + " mainObj;");
1207 //println("private int ports;");
1208 println("private IoTRMIObject rmiObj;\n");
1210 if (callbackExist) {
1211 println("private static int objIdCnt = 0;");
1212 println("private IoTRMICall rmiCall;");
1214 writePropertiesJavaPermission(intface, intDecl);
1220 * HELPER: writeStructPermissionJavaSkeleton() writes permission for struct helper
1222 private void writeStructPermissionJavaSkeleton(Collection<String> methods, InterfaceDecl intDecl, String intface) {
1224 // Use this set to handle two same methodIds
1225 for (String method : methods) {
1226 List<String> methParams = intDecl.getMethodParams(method);
1227 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1228 // Check for params with structs
1229 for (int i = 0; i < methParams.size(); i++) {
1230 String paramType = methPrmTypes.get(i);
1231 String param = methParams.get(i);
1232 String simpleType = getSimpleType(paramType);
1233 if (isStructClass(simpleType)) {
1234 int methodNumId = intDecl.getMethodNumId(method);
1235 String helperMethod = methodNumId + "struct" + i;
1236 int methodHelperNumId = intDecl.getHelperMethodNumId(helperMethod);
1237 // Iterate over interfaces to give permissions to
1238 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
1239 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
1240 String newIntface = intMeth.getKey();
1241 int newObjectId = getNewIntfaceObjectId(newIntface);
1242 println("set" + newObjectId + "Allowed.add(" + methodHelperNumId + ");");
1251 * HELPER: writeConstructorJavaSkeleton() writes the constructor of the skeleton class
1253 private void writeConstructorJavaSkeleton(String newSkelClass, String intface, InterfaceDecl intDecl, Collection<String> methods, boolean callbackExist) {
1255 println("public " + newSkelClass + "(" + intface + " _mainObj, int _port) throws Exception {");
1256 println("mainObj = _mainObj;");
1257 println("rmiObj = new IoTRMIObject(_port);");
1258 // Generate permission control initialization
1259 writeConstructorJavaPermission(intface);
1260 writeJavaInitCallbackPermission(intface, intDecl, callbackExist);
1261 writeStructPermissionJavaSkeleton(methods, intDecl, intface);
1262 println("___waitRequestInvokeMethod();");
1268 * HELPER: writeStdMethodBodyJavaSkeleton() writes the standard method body in the skeleton class
1270 private void writeStdMethodBodyJavaSkeleton(List<String> methParams, String methodId, String methodType) {
1272 if (methodType.equals("void"))
1273 print("mainObj." + methodId + "(");
1275 print("return mainObj." + methodId + "(");
1276 for (int i = 0; i < methParams.size(); i++) {
1278 print(getSimpleIdentifier(methParams.get(i)));
1279 // Check if this is the last element (don't print a comma)
1280 if (i != methParams.size() - 1) {
1289 * HELPER: writeInitCallbackJavaSkeleton() writes the init callback method for skeleton class
1291 private void writeInitCallbackJavaSkeleton(boolean callbackSkeleton) {
1293 // This is a callback skeleton generation
1294 if (callbackSkeleton)
1295 println("public void ___regCB(IoTRMIObject rmiObj) throws IOException {");
1297 println("public void ___regCB() throws IOException {");
1298 println("Object[] paramObj = rmiObj.getMethodParams(new Class<?>[] { int.class, String.class, int.class },");
1299 println("\tnew Class<?>[] { null, null, null });");
1300 println("rmiCall = new IoTRMICall((int) paramObj[0], (String) paramObj[1], (int) paramObj[2]);");
1306 * HELPER: writeMethodJavaSkeleton() writes the method of the skeleton class
1308 private void writeMethodJavaSkeleton(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses,
1309 boolean callbackSkeleton) {
1311 for (String method : methods) {
1313 List<String> methParams = intDecl.getMethodParams(method);
1314 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1315 String methodId = intDecl.getMethodId(method);
1316 print("public " + intDecl.getMethodType(method) + " " + methodId + "(");
1317 boolean isCallbackMethod = false;
1318 String callbackType = null;
1319 for (int i = 0; i < methParams.size(); i++) {
1321 String origParamType = methPrmTypes.get(i);
1322 String paramType = checkAndGetParamClass(origParamType);
1323 if (callbackClasses.contains(origParamType)) { // Check if this has callback object
1324 isCallbackMethod = true;
1325 callbackType = origParamType;
1327 print(paramType + " " + methParams.get(i));
1328 // Check if this is the last element (don't print a comma)
1329 if (i != methParams.size() - 1) {
1334 // Now, write the body of skeleton!
1335 writeStdMethodBodyJavaSkeleton(methParams, methodId, intDecl.getMethodType(method));
1337 if (isCallbackMethod)
1338 writeInitCallbackJavaSkeleton(callbackSkeleton);
1344 * HELPER: writeCallbackJavaStubGeneration() writes the callback stub generation part
1346 private Map<Integer,String> writeCallbackJavaStubGeneration(List<String> methParams, List<String> methPrmTypes,
1347 String callbackType) {
1349 Map<Integer,String> mapStubParam = new HashMap<Integer,String>();
1350 // Iterate over callback objects
1351 for (int i = 0; i < methParams.size(); i++) {
1352 String paramType = methPrmTypes.get(i);
1353 String param = methParams.get(i);
1354 //if (callbackType.equals(paramType)) {
1355 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
1357 String exchParamType = checkAndGetParamClass(paramType);
1358 // Print array if this is array or list if this is a list of callback objects
1359 if (isArray(param)) {
1360 println("int numStubs" + i + " = (int) paramObj[" + i + "];");
1361 println(exchParamType + "[] stub" + i + " = new " + exchParamType + "[numStubs" + i + "];");
1362 } else if (isList(paramType)) {
1363 println("int numStubs" + i + " = (int) paramObj[" + i + "];");
1364 println("List<" + exchParamType + "> stub" + i + " = new ArrayList<" + exchParamType + ">();");
1366 println(exchParamType + " stub" + i + " = new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt);");
1367 println("objIdCnt++;");
1370 // Generate a loop if needed
1371 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
1372 String exchParamType = checkAndGetParamClass(paramType);
1373 if (isArray(param)) {
1374 println("for (int objId = 0; objId < numStubs" + i + "; objId++) {");
1375 println("stub" + i + "[objId] = new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt);");
1376 println("objIdCnt++;");
1378 } else if (isList(paramType)) {
1379 println("for (int objId = 0; objId < numStubs" + i + "; objId++) {");
1380 println("stub" + i + ".add(new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt));");
1381 println("objIdCnt++;");
1384 mapStubParam.put(i, "stub" + i); // List of all stub parameters
1387 return mapStubParam;
1392 * HELPER: checkAndWriteEnumTypeJavaSkeleton() writes the enum type (convert from enum to int)
1394 private void checkAndWriteEnumTypeJavaSkeleton(List<String> methParams, List<String> methPrmTypes) {
1396 // Iterate and find enum declarations
1397 for (int i = 0; i < methParams.size(); i++) {
1398 String paramType = methPrmTypes.get(i);
1399 String param = methParams.get(i);
1400 String simpleType = getGenericType(paramType);
1401 if (isEnumClass(simpleType)) {
1402 // Check if this is enum type
1403 println("int paramInt" + i + "[] = (int[]) paramObj[" + i + "];");
1404 println(simpleType + "[] enumVals = " + simpleType + ".values();");
1405 if (isArray(param)) { // An array
1406 println("int len" + i + " = paramInt" + i + ".length;");
1407 println(simpleType + "[] paramEnum" + i + " = new " + simpleType + "[len" + i + "];");
1408 println("for (int i = 0; i < len" + i + "; i++) {");
1409 println("paramEnum" + i + "[i] = enumVals[paramInt" + i + "[i]];");
1411 } else if (isList(paramType)) { // A list
1412 println("int len" + i + " = paramInt" + i + ".length;");
1413 println("List<" + simpleType + "> paramEnum" + i + " = new ArrayList<" + simpleType + ">();");
1414 println("for (int i = 0; i < len" + i + "; i++) {");
1415 println("paramEnum" + i + ".add(enumVals[paramInt" + i + "[i]]);");
1417 } else { // Just one element
1418 println(simpleType + " paramEnum" + i + " = enumVals[paramInt" + i + "[0]];");
1426 * HELPER: checkAndWriteEnumRetTypeJavaSkeleton() writes the enum return type (convert from enum to int)
1428 private void checkAndWriteEnumRetTypeJavaSkeleton(String retType, String methodId) {
1430 // Strips off array "[]" for return type
1431 String pureType = getSimpleArrayType(getGenericType(retType));
1432 // Take the inner type of generic
1433 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
1434 pureType = getGenericType(retType);
1435 if (isEnumClass(pureType)) {
1436 // Check if this is enum type
1438 if (isArray(retType)) { // An array
1439 print(pureType + "[] retEnum = " + methodId + "(");
1440 } else if (isList(retType)) { // A list
1441 print("List<" + pureType + "> retEnum = " + methodId + "(");
1442 } else { // Just one element
1443 print(pureType + " retEnum = " + methodId + "(");
1450 * HELPER: checkAndWriteEnumRetConvJavaSkeleton() writes the enum return type (convert from enum to int)
1452 private void checkAndWriteEnumRetConvJavaSkeleton(String retType) {
1454 // Strips off array "[]" for return type
1455 String pureType = getSimpleArrayType(getGenericType(retType));
1456 // Take the inner type of generic
1457 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
1458 pureType = getGenericType(retType);
1459 if (isEnumClass(pureType)) {
1460 // Check if this is enum type
1461 if (isArray(retType)) { // An array
1462 println("int retLen = retEnum.length;");
1463 println("int[] retEnumVal = new int[retLen];");
1464 println("for (int i = 0; i < retLen; i++) {");
1465 println("retEnumVal[i] = retEnum[i].ordinal();");
1467 } else if (isList(retType)) { // A list
1468 println("int retLen = retEnum.size();");
1469 println("int[] retEnumVal = new int[retLen];");
1470 println("for (int i = 0; i < retLen; i++) {");
1471 println("retEnumVal[i] = retEnum.get(i).ordinal();");
1473 } else { // Just one element
1474 println("int[] retEnumVal = new int[1];");
1475 println("retEnumVal[0] = retEnum.ordinal();");
1477 println("Object retObj = retEnumVal;");
1483 * HELPER: writeLengthStructParamClassSkeleton() writes lengths of params
1485 private void writeLengthStructParamClassSkeleton(List<String> methParams, List<String> methPrmTypes,
1486 String method, InterfaceDecl intDecl) {
1488 // Iterate and find struct declarations - count number of params
1489 for (int i = 0; i < methParams.size(); i++) {
1490 String paramType = methPrmTypes.get(i);
1491 String param = methParams.get(i);
1492 String simpleType = getGenericType(paramType);
1493 if (isStructClass(simpleType)) {
1494 int members = getNumOfMembers(simpleType);
1495 print(Integer.toString(members) + "*");
1496 int methodNumId = intDecl.getMethodNumId(method);
1497 print("struct" + methodNumId + "Size" + i);
1500 if (i != methParams.size() - 1) {
1508 * HELPER: writeStructMembersJavaSkeleton() writes member parameters of struct
1510 private void writeStructMembersJavaSkeleton(String simpleType, String paramType,
1511 String param, String method, InterfaceDecl intDecl, int iVar) {
1513 // Get the struct declaration for this struct and generate initialization code
1514 StructDecl structDecl = getStructDecl(simpleType);
1515 List<String> memTypes = structDecl.getMemberTypes(simpleType);
1516 List<String> members = structDecl.getMembers(simpleType);
1517 if (isArrayOrList(param, paramType)) { // An array or list
1518 int methodNumId = intDecl.getMethodNumId(method);
1519 String counter = "struct" + methodNumId + "Size" + iVar;
1520 println("for(int i = 0; i < " + counter + "; i++) {");
1522 println("int pos = 0;");
1523 if (isArrayOrList(param, paramType)) { // An array or list
1524 println("for(int i = 0; i < retLen; i++) {");
1525 for (int i = 0; i < members.size(); i++) {
1526 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
1527 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
1528 println("paramClsGen[pos++] = null;");
1531 } else { // Just one struct element
1532 for (int i = 0; i < members.size(); i++) {
1533 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
1534 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
1535 println("paramClsGen[pos++] = null;");
1542 * HELPER: writeStructMembersInitJavaSkeleton() writes member parameters initialization of struct
1544 private void writeStructMembersInitJavaSkeleton(InterfaceDecl intDecl, List<String> methParams,
1545 List<String> methPrmTypes, String method) {
1547 for (int i = 0; i < methParams.size(); i++) {
1548 String paramType = methPrmTypes.get(i);
1549 String param = methParams.get(i);
1550 String simpleType = getGenericType(paramType);
1551 if (isStructClass(simpleType)) {
1552 int methodNumId = intDecl.getMethodNumId(method);
1553 String counter = "struct" + methodNumId + "Size" + i;
1555 if (isArray(param)) { // An array
1556 println(simpleType + "[] paramStruct" + i + " = new " + simpleType + "[" + counter + "];");
1557 println("for(int i = 0; i < " + counter + "; i++) {");
1558 println("paramStruct" + i + "[i] = new " + simpleType + "();");
1560 } else if (isList(paramType)) { // A list
1561 println("List<" + simpleType + "> paramStruct" + i + " = new ArrayList<" + simpleType + ">();");
1563 println(simpleType + " paramStruct" + i + " = new " + simpleType + "();");
1564 println("int objPos = 0;");
1565 // Initialize members
1566 StructDecl structDecl = getStructDecl(simpleType);
1567 List<String> members = structDecl.getMembers(simpleType);
1568 List<String> memTypes = structDecl.getMemberTypes(simpleType);
1569 if (isArrayOrList(param, paramType)) { // An array or list
1570 println("for(int i = 0; i < " + counter + "; i++) {");
1572 if (isArray(param)) { // An array
1573 for (int j = 0; j < members.size(); j++) {
1574 String prmType = checkAndGetArray(memTypes.get(j), members.get(j));
1575 print("paramStruct" + i + "[i]." + getSimpleIdentifier(members.get(j)));
1576 println(" = (" + getSimpleType(getEnumType(prmType)) + ") paramObj[objPos++];");
1579 } else if (isList(paramType)) { // A list
1580 println(simpleType + " paramStructMem = new " + simpleType + "();");
1581 for (int j = 0; j < members.size(); j++) {
1582 String prmType = checkAndGetArray(memTypes.get(j), members.get(j));
1583 print("paramStructMem." + getSimpleIdentifier(members.get(j)));
1584 println(" = (" + getSimpleType(getEnumType(prmType)) + ") paramObj[objPos++];");
1586 println("paramStruct" + i + ".add(paramStructMem);");
1588 } else { // Just one struct element
1589 for (int j = 0; j < members.size(); j++) {
1590 String prmType = checkAndGetArray(memTypes.get(j), members.get(j));
1591 print("paramStruct" + i + "." + getSimpleIdentifier(members.get(j)));
1592 println(" = (" + getSimpleType(getEnumType(prmType)) + ") paramObj[objPos++];");
1596 // Take offsets of parameters
1597 println("int offset" + i +" = objPos;");
1604 * HELPER: writeStructReturnJavaSkeleton() writes struct for return statement
1606 private void writeStructReturnJavaSkeleton(String simpleType, String retType) {
1608 // Minimum retLen is 1 if this is a single struct object
1609 if (isArray(retType))
1610 println("int retLen = retStruct.length;");
1611 else if (isList(retType))
1612 println("int retLen = retStruct.size();");
1613 else // Just single struct object
1614 println("int retLen = 1;");
1615 println("Object retLenObj = retLen;");
1616 println("rmiObj.sendReturnObj(retLenObj);");
1617 int numMem = getNumOfMembers(simpleType);
1618 println("Class<?>[] retCls = new Class<?>[" + numMem + "*retLen];");
1619 println("Object[] retObj = new Object[" + numMem + "*retLen];");
1620 println("int retPos = 0;");
1621 // Get the struct declaration for this struct and generate initialization code
1622 StructDecl structDecl = getStructDecl(simpleType);
1623 List<String> memTypes = structDecl.getMemberTypes(simpleType);
1624 List<String> members = structDecl.getMembers(simpleType);
1625 if (isArrayOrList(retType, retType)) { // An array or list
1626 println("for(int i = 0; i < retLen; i++) {");
1627 for (int i = 0; i < members.size(); i++) {
1628 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
1629 println("retCls[retPos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
1630 print("retObj[retPos++] = retStruct[i].");
1631 print(getEnumParam(memTypes.get(i), getSimpleIdentifier(members.get(i)), i));
1635 } else { // Just one struct element
1636 for (int i = 0; i < members.size(); i++) {
1637 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
1638 println("retCls[retPos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
1639 print("retObj[retPos++] = retStruct.");
1640 print(getEnumParam(memTypes.get(i), getSimpleIdentifier(members.get(i)), i));
1649 * HELPER: writeMethodHelperReturnJavaSkeleton() writes return statement part in skeleton
1651 private void writeMethodHelperReturnJavaSkeleton(InterfaceDecl intDecl, List<String> methParams,
1652 List<String> methPrmTypes, String method, boolean isCallbackMethod, String callbackType,
1653 boolean isStructMethod) {
1655 checkAndWriteEnumTypeJavaSkeleton(methParams, methPrmTypes);
1656 Map<Integer,String> mapStubParam = null;
1657 if (isCallbackMethod)
1658 mapStubParam = writeCallbackJavaStubGeneration(methParams, methPrmTypes, callbackType);
1659 // Check if this is "void"
1660 String retType = intDecl.getMethodType(method);
1661 if (retType.equals("void")) {
1662 print(intDecl.getMethodId(method) + "(");
1663 } else if (isEnumClass(getSimpleArrayType(getGenericType(retType)))) { // Enum type
1664 checkAndWriteEnumRetTypeJavaSkeleton(retType, intDecl.getMethodId(method));
1665 } else if (isStructClass(getSimpleArrayType(getGenericType(retType)))) { // Struct type
1666 print(retType + " retStruct = " + intDecl.getMethodId(method) + "(");
1667 } else { // We do have a return value
1668 print("Object retObj = " + intDecl.getMethodId(method) + "(");
1670 for (int i = 0; i < methParams.size(); i++) {
1672 if (isCallbackMethod) {
1673 print(mapStubParam.get(i)); // Get the callback parameter
1674 } else if (isEnumClass(getGenericType(methPrmTypes.get(i)))) { // Enum class
1675 print(getEnumParam(methPrmTypes.get(i), methParams.get(i), i));
1676 } else if (isStructClass(getGenericType(methPrmTypes.get(i)))) {
1677 print("paramStruct" + i);
1679 String prmType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
1681 print("(" + prmType + ") paramObj[offset" + i + "]");
1683 print("(" + prmType + ") paramObj[" + i + "]");
1685 if (i != methParams.size() - 1)
1689 if (!retType.equals("void")) {
1690 if (isEnumClass(getSimpleArrayType(getGenericType(retType)))) { // Enum type
1691 checkAndWriteEnumRetConvJavaSkeleton(retType);
1692 println("rmiObj.sendReturnObj(retObj);");
1693 } else if (isStructClass(getSimpleArrayType(getGenericType(retType)))) { // Struct type
1694 writeStructReturnJavaSkeleton(getSimpleArrayType(getGenericType(retType)), retType);
1695 println("rmiObj.sendReturnObj(retCls, retObj);");
1697 println("rmiObj.sendReturnObj(retObj);");
1699 if (isCallbackMethod) { // Catch exception if this is callback
1701 println(" catch(Exception ex) {");
1702 println("ex.printStackTrace();");
1703 println("throw new Error(\"Exception from callback object instantiation!\");");
1710 * HELPER: writeMethodHelperStructJavaSkeleton() writes the struct in skeleton
1712 private void writeMethodHelperStructJavaSkeleton(InterfaceDecl intDecl, List<String> methParams,
1713 List<String> methPrmTypes, String method, Set<String> callbackClasses) {
1715 // Generate array of parameter objects
1716 boolean isCallbackMethod = false;
1717 String callbackType = null;
1718 print("int paramLen = ");
1719 writeLengthStructParamClassSkeleton(methParams, methPrmTypes, method, intDecl);
1721 println("Class<?>[] paramCls = new Class<?>[paramLen];");
1722 println("Class<?>[] paramClsGen = new Class<?>[paramLen];");
1723 // Iterate again over the parameters
1724 for (int i = 0; i < methParams.size(); i++) {
1725 String paramType = methPrmTypes.get(i);
1726 String param = methParams.get(i);
1727 String simpleType = getGenericType(paramType);
1728 if (isStructClass(simpleType)) {
1729 writeStructMembersJavaSkeleton(simpleType, paramType, param, method, intDecl, i);
1731 String prmType = returnGenericCallbackType(methPrmTypes.get(i));
1732 if (callbackClasses.contains(prmType)) {
1733 isCallbackMethod = true;
1734 callbackType = prmType;
1735 println("paramCls[pos] = int.class;");
1736 println("paramClsGen[pos++] = null;");
1737 } else { // Generate normal classes if it's not a callback object
1738 String paramTypeOth = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
1739 println("paramCls[pos] = " + getSimpleType(getEnumType(paramTypeOth)) + ".class;");
1740 print("paramClsGen[pos++] = ");
1741 String prmTypeOth = methPrmTypes.get(i);
1742 if (getParamCategory(prmTypeOth) == ParamCategory.NONPRIMITIVES)
1743 println(getTypeOfGeneric(prmType)[0] + ".class;");
1749 println("Object[] paramObj = rmiObj.getMethodParams(paramCls, paramClsGen);");
1750 writeStructMembersInitJavaSkeleton(intDecl, methParams, methPrmTypes, method);
1751 // Write the return value part
1752 writeMethodHelperReturnJavaSkeleton(intDecl, methParams, methPrmTypes, method, isCallbackMethod, callbackType, true);
1757 * HELPER: writeStdMethodHelperBodyJavaSkeleton() writes the standard method body helper in the skeleton class
1759 private void writeStdMethodHelperBodyJavaSkeleton(InterfaceDecl intDecl, List<String> methParams,
1760 List<String> methPrmTypes, String method, Set<String> callbackClasses) {
1762 // Generate array of parameter objects
1763 boolean isCallbackMethod = false;
1764 String callbackType = null;
1765 print("Object[] paramObj = rmiObj.getMethodParams(new Class<?>[] { ");
1766 for (int i = 0; i < methParams.size(); i++) {
1768 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
1769 if (callbackClasses.contains(paramType)) {
1770 isCallbackMethod = true;
1771 callbackType = paramType;
1773 } else { // Generate normal classes if it's not a callback object
1774 String prmType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
1775 print(getSimpleType(getEnumType(prmType)) + ".class");
1777 if (i != methParams.size() - 1)
1781 // Generate generic class if it's a generic type.. null otherwise
1782 print("new Class<?>[] { ");
1783 for (int i = 0; i < methParams.size(); i++) {
1784 String prmType = methPrmTypes.get(i);
1785 if ((getParamCategory(prmType) == ParamCategory.NONPRIMITIVES) &&
1786 !isEnumClass(getGenericType(prmType)))
1787 print(getGenericType(prmType) + ".class");
1790 if (i != methParams.size() - 1)
1794 // Write the return value part
1795 writeMethodHelperReturnJavaSkeleton(intDecl, methParams, methPrmTypes, method, isCallbackMethod, callbackType, false);
1800 * HELPER: writeMethodHelperJavaSkeleton() writes the method helper of the skeleton class
1802 private void writeMethodHelperJavaSkeleton(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
1804 // Use this set to handle two same methodIds
1805 Set<String> uniqueMethodIds = new HashSet<String>();
1806 for (String method : methods) {
1808 List<String> methParams = intDecl.getMethodParams(method);
1809 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1810 if (isStructPresent(methParams, methPrmTypes)) { // Treat struct differently
1811 String methodId = intDecl.getMethodId(method);
1812 print("public void ___");
1813 String helperMethod = methodId;
1814 if (uniqueMethodIds.contains(methodId))
1815 helperMethod = helperMethod + intDecl.getMethodNumId(method);
1817 uniqueMethodIds.add(methodId);
1818 String retType = intDecl.getMethodType(method);
1819 print(helperMethod + "(");
1820 boolean begin = true;
1821 for (int i = 0; i < methParams.size(); i++) { // Print size variables
1822 String paramType = methPrmTypes.get(i);
1823 String param = methParams.get(i);
1824 String simpleType = getSimpleType(paramType);
1825 if (isStructClass(simpleType)) {
1826 if (!begin) { // Generate comma for not the beginning variable
1827 print(", "); begin = false;
1829 int methodNumId = intDecl.getMethodNumId(method);
1830 print("int struct" + methodNumId + "Size" + i);
1833 // Check if this is "void"
1834 if (retType.equals("void"))
1837 println(") throws IOException {");
1838 writeMethodHelperStructJavaSkeleton(intDecl, methParams, methPrmTypes, method, callbackClasses);
1841 String methodId = intDecl.getMethodId(method);
1842 print("public void ___");
1843 String helperMethod = methodId;
1844 if (uniqueMethodIds.contains(methodId))
1845 helperMethod = helperMethod + intDecl.getMethodNumId(method);
1847 uniqueMethodIds.add(methodId);
1848 // Check if this is "void"
1849 String retType = intDecl.getMethodType(method);
1850 if (retType.equals("void"))
1851 println(helperMethod + "() {");
1853 println(helperMethod + "() throws IOException {");
1854 // Now, write the helper body of skeleton!
1855 writeStdMethodHelperBodyJavaSkeleton(intDecl, methParams, methPrmTypes, method, callbackClasses);
1859 // Write method helper for structs
1860 writeMethodHelperStructSetupJavaSkeleton(methods, intDecl);
1865 * HELPER: writeMethodHelperStructSetupJavaSkeleton() writes the method helper of struct setup in skeleton class
1867 private void writeMethodHelperStructSetupJavaSkeleton(Collection<String> methods,
1868 InterfaceDecl intDecl) {
1870 // Use this set to handle two same methodIds
1871 for (String method : methods) {
1873 List<String> methParams = intDecl.getMethodParams(method);
1874 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1875 // Check for params with structs
1876 for (int i = 0; i < methParams.size(); i++) {
1877 String paramType = methPrmTypes.get(i);
1878 String param = methParams.get(i);
1879 String simpleType = getSimpleType(paramType);
1880 if (isStructClass(simpleType)) {
1881 int methodNumId = intDecl.getMethodNumId(method);
1882 print("public int ___");
1883 String helperMethod = methodNumId + "struct" + i;
1884 println(helperMethod + "() {");
1885 // Now, write the helper body of skeleton!
1886 println("Object[] paramObj = rmiObj.getMethodParams(new Class<?>[] { int.class }, new Class<?>[] { null });");
1887 println("return (int) paramObj[0];");
1896 * HELPER: writeMethodHelperStructSetupJavaCallbackSkeleton() writes the method helper of struct setup in callback skeleton class
1898 private void writeMethodHelperStructSetupJavaCallbackSkeleton(Collection<String> methods,
1899 InterfaceDecl intDecl) {
1901 // Use this set to handle two same methodIds
1902 for (String method : methods) {
1904 List<String> methParams = intDecl.getMethodParams(method);
1905 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1906 // Check for params with structs
1907 for (int i = 0; i < methParams.size(); i++) {
1908 String paramType = methPrmTypes.get(i);
1909 String param = methParams.get(i);
1910 String simpleType = getSimpleType(paramType);
1911 if (isStructClass(simpleType)) {
1912 int methodNumId = intDecl.getMethodNumId(method);
1913 print("public int ___");
1914 String helperMethod = methodNumId + "struct" + i;
1915 println(helperMethod + "(IoTRMIObject rmiObj) {");
1916 // Now, write the helper body of skeleton!
1917 println("Object[] paramObj = rmiObj.getMethodParams(new Class<?>[] { int.class }, new Class<?>[] { null });");
1918 println("return (int) paramObj[0];");
1927 * HELPER: writeCountVarStructSkeleton() writes counter variable of struct for skeleton
1929 private void writeCountVarStructSkeleton(Collection<String> methods, InterfaceDecl intDecl) {
1931 // Use this set to handle two same methodIds
1932 for (String method : methods) {
1934 List<String> methParams = intDecl.getMethodParams(method);
1935 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1936 // Check for params with structs
1937 for (int i = 0; i < methParams.size(); i++) {
1938 String paramType = methPrmTypes.get(i);
1939 String param = methParams.get(i);
1940 String simpleType = getSimpleType(paramType);
1941 if (isStructClass(simpleType)) {
1942 int methodNumId = intDecl.getMethodNumId(method);
1943 println("int struct" + methodNumId + "Size" + i + " = 0;");
1951 * HELPER: writeInputCountVarStructSkeleton() writes input counter variable of struct for skeleton
1953 private boolean writeInputCountVarStructSkeleton(String method, InterfaceDecl intDecl) {
1955 List<String> methParams = intDecl.getMethodParams(method);
1956 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1957 boolean structExist = false;
1958 // Check for params with structs
1959 for (int i = 0; i < methParams.size(); i++) {
1960 String paramType = methPrmTypes.get(i);
1961 String param = methParams.get(i);
1962 String simpleType = getSimpleType(paramType);
1963 boolean begin = true;
1964 if (isStructClass(simpleType)) {
1967 print(", "); begin = false;
1969 int methodNumId = intDecl.getMethodNumId(method);
1970 print("struct" + methodNumId + "Size" + i);
1978 * HELPER: writeMethodCallStructSkeleton() writes method call for wait invoke in skeleton
1980 private void writeMethodCallStructSkeleton(Collection<String> methods, InterfaceDecl intDecl) {
1982 // Use this set to handle two same methodIds
1983 for (String method : methods) {
1985 List<String> methParams = intDecl.getMethodParams(method);
1986 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1987 // Check for params with structs
1988 for (int i = 0; i < methParams.size(); i++) {
1989 String paramType = methPrmTypes.get(i);
1990 String param = methParams.get(i);
1991 String simpleType = getSimpleType(paramType);
1992 if (isStructClass(simpleType)) {
1993 int methodNumId = intDecl.getMethodNumId(method);
1995 String helperMethod = methodNumId + "struct" + i;
1996 String tempVar = "struct" + methodNumId + "Size" + i;
1997 print(intDecl.getHelperMethodNumId(helperMethod) + ": ");
1998 print(tempVar + " = ___");
1999 println(helperMethod + "(); break;");
2007 * HELPER: writeMethodCallStructCallbackSkeleton() writes method call for wait invoke in skeleton
2009 private void writeMethodCallStructCallbackSkeleton(Collection<String> methods, InterfaceDecl intDecl) {
2011 // Use this set to handle two same methodIds
2012 for (String method : methods) {
2014 List<String> methParams = intDecl.getMethodParams(method);
2015 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2016 // Check for params with structs
2017 for (int i = 0; i < methParams.size(); i++) {
2018 String paramType = methPrmTypes.get(i);
2019 String param = methParams.get(i);
2020 String simpleType = getSimpleType(paramType);
2021 if (isStructClass(simpleType)) {
2022 int methodNumId = intDecl.getMethodNumId(method);
2024 String helperMethod = methodNumId + "struct" + i;
2025 String tempVar = "struct" + methodNumId + "Size" + i;
2026 print(intDecl.getHelperMethodNumId(helperMethod) + ": ");
2027 print(tempVar + " = ___");
2028 println(helperMethod + "(rmiObj); break;");
2036 * HELPER: writeJavaMethodPermission() writes permission checks in skeleton
2038 private void writeJavaMethodPermission(String intface) {
2040 // Get all the different stubs
2041 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
2042 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
2043 String newIntface = intMeth.getKey();
2044 int newObjectId = getNewIntfaceObjectId(newIntface);
2045 println("if (_objectId == object" + newObjectId + "Id) {");
2046 println("if (!set" + newObjectId + "Allowed.contains(methodId)) {");
2047 println("throw new Error(\"Object with object Id: \" + _objectId + \" is not allowed to access method: \" + methodId);");
2051 println("throw new Error(\"Object Id: \" + _objectId + \" not recognized!\");");
2058 * HELPER: writeJavaWaitRequestInvokeMethod() writes the main loop of the skeleton class
2060 private void writeJavaWaitRequestInvokeMethod(Collection<String> methods, InterfaceDecl intDecl, boolean callbackExist, String intface) {
2062 // Use this set to handle two same methodIds
2063 Set<String> uniqueMethodIds = new HashSet<String>();
2064 println("private void ___waitRequestInvokeMethod() throws IOException {");
2065 // Write variables here if we have callbacks or enums or structs
2066 writeCountVarStructSkeleton(methods, intDecl);
2067 println("while (true) {");
2068 println("rmiObj.getMethodBytes();");
2069 println("int _objectId = rmiObj.getObjectId();");
2070 println("int methodId = rmiObj.getMethodId();");
2071 // Generate permission check
2072 writeJavaMethodPermission(intface);
2073 println("switch (methodId) {");
2074 // Print methods and method Ids
2075 for (String method : methods) {
2076 String methodId = intDecl.getMethodId(method);
2077 int methodNumId = intDecl.getMethodNumId(method);
2078 print("case " + methodNumId + ": ___");
2079 String helperMethod = methodId;
2080 if (uniqueMethodIds.contains(methodId))
2081 helperMethod = helperMethod + methodNumId;
2083 uniqueMethodIds.add(methodId);
2084 print(helperMethod + "(");
2085 writeInputCountVarStructSkeleton(method, intDecl);
2086 println("); break;");
2088 String method = "___initCallBack()";
2089 // Print case -9999 (callback handler) if callback exists
2090 if (callbackExist) {
2091 int methodId = intDecl.getHelperMethodNumId(method);
2092 println("case " + methodId + ": ___regCB(); break;");
2094 writeMethodCallStructSkeleton(methods, intDecl);
2095 println("default: ");
2096 println("throw new Error(\"Method Id \" + methodId + \" not recognized!\");");
2104 * generateJavaSkeletonClass() generate skeletons based on the methods list in Java
2106 public void generateJavaSkeletonClass() throws IOException {
2108 // Create a new directory
2109 String path = createDirectories(dir, subdir);
2110 for (String intface : mapIntfacePTH.keySet()) {
2111 // Open a new file to write into
2112 String newSkelClass = intface + "_Skeleton";
2113 FileWriter fw = new FileWriter(path + "/" + newSkelClass + ".java");
2114 pw = new PrintWriter(new BufferedWriter(fw));
2115 // Pass in set of methods and get import classes
2116 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2117 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
2118 List<String> methods = intDecl.getMethods();
2119 Set<String> importClasses = getImportClasses(methods, intDecl);
2120 List<String> stdImportClasses = getStandardJavaImportClasses();
2121 List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
2122 printImportStatements(allImportClasses);
2123 // Find out if there are callback objects
2124 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
2125 boolean callbackExist = !callbackClasses.isEmpty();
2126 // Write class header
2128 println("public class " + newSkelClass + " implements " + intface + " {\n");
2130 writePropertiesJavaSkeleton(intface, callbackExist, intDecl);
2131 // Write constructor
2132 writeConstructorJavaSkeleton(newSkelClass, intface, intDecl, methods, callbackExist);
2134 writeMethodJavaSkeleton(methods, intDecl, callbackClasses, false);
2135 // Write method helper
2136 writeMethodHelperJavaSkeleton(methods, intDecl, callbackClasses);
2137 // Write waitRequestInvokeMethod() - main loop
2138 writeJavaWaitRequestInvokeMethod(methods, intDecl, callbackExist, intface);
2141 System.out.println("IoTCompiler: Generated skeleton class " + newSkelClass + ".java...");
2147 * HELPER: writePropertiesJavaCallbackSkeleton() writes the properties of the callback skeleton class
2149 private void writePropertiesJavaCallbackSkeleton(String intface, boolean callbackExist) {
2151 println("private " + intface + " mainObj;");
2152 // For callback skeletons, this is its own object Id
2153 println("private static int objectId = 0;");
2155 if (callbackExist) {
2156 println("private static int objIdCnt = 0;");
2157 println("private IoTRMICall rmiCall;");
2164 * HELPER: writeConstructorJavaCallbackSkeleton() writes the constructor of the skeleton class
2166 private void writeConstructorJavaCallbackSkeleton(String newSkelClass, String intface, InterfaceDecl intDecl, Collection<String> methods) {
2168 println("public " + newSkelClass + "(" + intface + " _mainObj, int _objectId) throws Exception {");
2169 println("mainObj = _mainObj;");
2170 println("objectId = _objectId;");
2176 * HELPER: writeMethodHelperJavaCallbackSkeleton() writes the method helper of the callback skeleton class
2178 private void writeMethodHelperJavaCallbackSkeleton(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
2180 // Use this set to handle two same methodIds
2181 Set<String> uniqueMethodIds = new HashSet<String>();
2182 for (String method : methods) {
2184 List<String> methParams = intDecl.getMethodParams(method);
2185 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2186 if (isStructPresent(methParams, methPrmTypes)) { // Treat struct differently
2187 String methodId = intDecl.getMethodId(method);
2188 print("public void ___");
2189 String helperMethod = methodId;
2190 if (uniqueMethodIds.contains(methodId))
2191 helperMethod = helperMethod + intDecl.getMethodNumId(method);
2193 uniqueMethodIds.add(methodId);
2194 String retType = intDecl.getMethodType(method);
2195 print(helperMethod + "(");
2196 boolean begin = true;
2197 for (int i = 0; i < methParams.size(); i++) { // Print size variables
2198 String paramType = methPrmTypes.get(i);
2199 String param = methParams.get(i);
2200 String simpleType = getSimpleType(paramType);
2201 if (isStructClass(simpleType)) {
2202 if (!begin) { // Generate comma for not the beginning variable
2203 print(", "); begin = false;
2205 int methodNumId = intDecl.getMethodNumId(method);
2206 print("int struct" + methodNumId + "Size" + i);
2209 // Check if this is "void"
2210 if (retType.equals("void"))
2211 println(", IoTRMIObject rmiObj) {");
2213 println(", IoTRMIObject rmiObj) throws IOException {");
2214 writeMethodHelperStructJavaSkeleton(intDecl, methParams, methPrmTypes, method, callbackClasses);
2217 String methodId = intDecl.getMethodId(method);
2218 print("public void ___");
2219 String helperMethod = methodId;
2220 if (uniqueMethodIds.contains(methodId))
2221 helperMethod = helperMethod + intDecl.getMethodNumId(method);
2223 uniqueMethodIds.add(methodId);
2224 // Check if this is "void"
2225 String retType = intDecl.getMethodType(method);
2226 if (retType.equals("void"))
2227 println(helperMethod + "(IoTRMIObject rmiObj) {");
2229 println(helperMethod + "(IoTRMIObject rmiObj) throws IOException {");
2230 // Now, write the helper body of skeleton!
2231 writeStdMethodHelperBodyJavaSkeleton(intDecl, methParams, methPrmTypes, method, callbackClasses);
2235 // Write method helper for structs
2236 writeMethodHelperStructSetupJavaCallbackSkeleton(methods, intDecl);
2241 * HELPER: writeJavaCallbackWaitRequestInvokeMethod() writes the request invoke method of the callback skeleton class
2243 private void writeJavaCallbackWaitRequestInvokeMethod(Collection<String> methods, InterfaceDecl intDecl, boolean callbackExist) {
2245 // Use this set to handle two same methodIds
2246 Set<String> uniqueMethodIds = new HashSet<String>();
2247 println("public void invokeMethod(IoTRMIObject rmiObj) throws IOException {");
2248 // Write variables here if we have callbacks or enums or structs
2249 writeCountVarStructSkeleton(methods, intDecl);
2250 // Write variables here if we have callbacks or enums or structs
2251 println("int methodId = rmiObj.getMethodId();");
2252 // TODO: code the permission check here!
2253 println("switch (methodId) {");
2254 // Print methods and method Ids
2255 for (String method : methods) {
2256 String methodId = intDecl.getMethodId(method);
2257 int methodNumId = intDecl.getMethodNumId(method);
2258 print("case " + methodNumId + ": ___");
2259 String helperMethod = methodId;
2260 if (uniqueMethodIds.contains(methodId))
2261 helperMethod = helperMethod + methodNumId;
2263 uniqueMethodIds.add(methodId);
2264 print(helperMethod + "(");
2265 if (writeInputCountVarStructSkeleton(method, intDecl))
2266 println(", rmiObj); break;");
2268 println("rmiObj); break;");
2270 String method = "___initCallBack()";
2271 // Print case -9999 (callback handler) if callback exists
2272 if (callbackExist) {
2273 int methodId = intDecl.getHelperMethodNumId(method);
2274 println("case " + methodId + ": ___regCB(rmiObj); break;");
2276 writeMethodCallStructCallbackSkeleton(methods, intDecl);
2277 println("default: ");
2278 println("throw new Error(\"Method Id \" + methodId + \" not recognized!\");");
2285 * generateJavaCallbackSkeletonClass() generate callback skeletons based on the methods list in Java
2287 public void generateJavaCallbackSkeletonClass() throws IOException {
2289 // Create a new directory
2290 String path = createDirectories(dir, subdir);
2291 for (String intface : mapIntfacePTH.keySet()) {
2292 // Open a new file to write into
2293 String newSkelClass = intface + "_CallbackSkeleton";
2294 FileWriter fw = new FileWriter(path + "/" + newSkelClass + ".java");
2295 pw = new PrintWriter(new BufferedWriter(fw));
2296 // Pass in set of methods and get import classes
2297 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2298 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
2299 List<String> methods = intDecl.getMethods();
2300 Set<String> importClasses = getImportClasses(methods, intDecl);
2301 List<String> stdImportClasses = getStandardJavaImportClasses();
2302 List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
2303 printImportStatements(allImportClasses);
2304 // Find out if there are callback objects
2305 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
2306 boolean callbackExist = !callbackClasses.isEmpty();
2307 // Write class header
2309 println("public class " + newSkelClass + " implements " + intface + " {\n");
2311 writePropertiesJavaCallbackSkeleton(intface, callbackExist);
2312 // Write constructor
2313 writeConstructorJavaCallbackSkeleton(newSkelClass, intface, intDecl, methods);
2315 writeMethodJavaSkeleton(methods, intDecl, callbackClasses, true);
2316 // Write method helper
2317 writeMethodHelperJavaCallbackSkeleton(methods, intDecl, callbackClasses);
2318 // Write waitRequestInvokeMethod() - main loop
2319 writeJavaCallbackWaitRequestInvokeMethod(methods, intDecl, callbackExist);
2322 System.out.println("IoTCompiler: Generated callback skeleton class " + newSkelClass + ".java...");
2328 * HELPER: writeMethodCplusLocalInterface() writes the method of the local interface
2330 private void writeMethodCplusLocalInterface(Collection<String> methods, InterfaceDecl intDecl) {
2332 for (String method : methods) {
2334 List<String> methParams = intDecl.getMethodParams(method);
2335 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2336 print("virtual " + checkAndGetCplusType(intDecl.getMethodType(method)) + " " +
2337 intDecl.getMethodId(method) + "(");
2338 for (int i = 0; i < methParams.size(); i++) {
2339 // Check for params with driver class types and exchange it
2340 // with its remote interface
2341 String paramType = checkAndGetParamClass(methPrmTypes.get(i));
2342 paramType = checkAndGetCplusType(paramType);
2343 // Check for arrays - translate into vector in C++
2344 String paramComplete = checkAndGetCplusArray(paramType, methParams.get(i));
2345 print(paramComplete);
2346 // Check if this is the last element (don't print a comma)
2347 if (i != methParams.size() - 1) {
2357 * HELPER: writeMethodCplusInterface() writes the method of the interface
2359 private void writeMethodCplusInterface(Collection<String> methods, InterfaceDecl intDecl) {
2361 for (String method : methods) {
2363 List<String> methParams = intDecl.getMethodParams(method);
2364 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2365 print("virtual " + checkAndGetCplusType(intDecl.getMethodType(method)) + " " +
2366 intDecl.getMethodId(method) + "(");
2367 for (int i = 0; i < methParams.size(); i++) {
2368 // Check for params with driver class types and exchange it
2369 // with its remote interface
2370 String paramType = methPrmTypes.get(i);
2371 paramType = checkAndGetCplusType(paramType);
2372 // Check for arrays - translate into vector in C++
2373 String paramComplete = checkAndGetCplusArray(paramType, methParams.get(i));
2374 print(paramComplete);
2375 // Check if this is the last element (don't print a comma)
2376 if (i != methParams.size() - 1) {
2386 * HELPER: generateEnumCplus() writes the enumeration declaration
2388 public void generateEnumCplus() throws IOException {
2390 // Create a new directory
2391 createDirectory(dir);
2392 for (String intface : mapIntfacePTH.keySet()) {
2393 // Get the right StructDecl
2394 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2395 EnumDecl enumDecl = (EnumDecl) decHandler.getEnumDecl(intface);
2396 Set<String> enumTypes = enumDecl.getEnumDeclarations();
2397 // Iterate over enum declarations
2398 for (String enType : enumTypes) {
2399 // Open a new file to write into
2400 FileWriter fw = new FileWriter(dir + "/" + enType + ".hpp");
2401 pw = new PrintWriter(new BufferedWriter(fw));
2402 // Write file headers
2403 println("#ifndef _" + enType.toUpperCase() + "_HPP__");
2404 println("#define _" + enType.toUpperCase() + "_HPP__");
2405 println("enum " + enType + " {");
2406 List<String> enumMembers = enumDecl.getMembers(enType);
2407 for (int i = 0; i < enumMembers.size(); i++) {
2409 String member = enumMembers.get(i);
2411 // Check if this is the last element (don't print a comma)
2412 if (i != enumMembers.size() - 1)
2420 System.out.println("IoTCompiler: Generated enum " + enType + ".hpp...");
2427 * HELPER: generateStructCplus() writes the struct declaration
2429 public void generateStructCplus() throws IOException {
2431 // Create a new directory
2432 createDirectory(dir);
2433 for (String intface : mapIntfacePTH.keySet()) {
2434 // Get the right StructDecl
2435 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2436 StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
2437 List<String> structTypes = structDecl.getStructTypes();
2438 // Iterate over enum declarations
2439 for (String stType : structTypes) {
2440 // Open a new file to write into
2441 FileWriter fw = new FileWriter(dir + "/" + stType + ".hpp");
2442 pw = new PrintWriter(new BufferedWriter(fw));
2443 // Write file headers
2444 println("#ifndef _" + stType.toUpperCase() + "_HPP__");
2445 println("#define _" + stType.toUpperCase() + "_HPP__");
2446 println("using namespace std;");
2447 println("struct " + stType + " {");
2448 List<String> structMemberTypes = structDecl.getMemberTypes(stType);
2449 List<String> structMembers = structDecl.getMembers(stType);
2450 for (int i = 0; i < structMembers.size(); i++) {
2452 String memberType = structMemberTypes.get(i);
2453 String member = structMembers.get(i);
2454 String structTypeC = checkAndGetCplusType(memberType);
2455 String structComplete = checkAndGetCplusArray(structTypeC, member);
2456 println(structComplete + ";");
2461 System.out.println("IoTCompiler: Generated struct " + stType + ".hpp...");
2468 * generateCplusLocalInterfaces() writes the local interfaces and provides type-checking.
2470 * It needs to rewrite and exchange USERDEFINED types in input parameters of stub
2471 * and original interfaces, e.g. exchange Camera and CameraWithVideoAndRecording.
2472 * The local interface has to be the input parameter for the stub and the stub
2473 * interface has to be the input parameter for the local class.
2475 public void generateCplusLocalInterfaces() throws IOException {
2477 // Create a new directory
2478 createDirectory(dir);
2479 for (String intface : mapIntfacePTH.keySet()) {
2480 // Open a new file to write into
2481 FileWriter fw = new FileWriter(dir + "/" + intface + ".hpp");
2482 pw = new PrintWriter(new BufferedWriter(fw));
2483 // Write file headers
2484 println("#ifndef _" + intface.toUpperCase() + "_HPP__");
2485 println("#define _" + intface.toUpperCase() + "_HPP__");
2486 println("#include <iostream>");
2487 // Pass in set of methods and get include classes
2488 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2489 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
2490 List<String> methods = intDecl.getMethods();
2491 Set<String> includeClasses = getIncludeClasses(methods, intDecl, intface, true);
2492 printIncludeStatements(includeClasses); println("");
2493 println("using namespace std;\n");
2494 //writeStructCplus(structDecl);
2495 println("class " + intface); println("{");
2498 writeMethodCplusLocalInterface(methods, intDecl);
2502 System.out.println("IoTCompiler: Generated local interface " + intface + ".hpp...");
2508 * generateCPlusInterfaces() generate stub interfaces based on the methods list in C++
2510 * For C++ we use virtual classe as interface
2512 public void generateCPlusInterfaces() throws IOException {
2514 // Create a new directory
2515 String path = createDirectories(dir, subdir);
2516 for (String intface : mapIntfacePTH.keySet()) {
2518 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
2519 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
2521 // Open a new file to write into
2522 String newIntface = intMeth.getKey();
2523 FileWriter fw = new FileWriter(path + "/" + newIntface + ".hpp");
2524 pw = new PrintWriter(new BufferedWriter(fw));
2525 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2526 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
2527 // Write file headers
2528 println("#ifndef _" + newIntface.toUpperCase() + "_HPP__");
2529 println("#define _" + newIntface.toUpperCase() + "_HPP__");
2530 println("#include <iostream>");
2531 // Pass in set of methods and get import classes
2532 Set<String> includeClasses = getIncludeClasses(intMeth.getValue(), intDecl, intface, false);
2533 List<String> stdIncludeClasses = getStandardCplusIncludeClasses();
2534 List<String> allIncludeClasses = getAllLibClasses(stdIncludeClasses, includeClasses);
2535 printIncludeStatements(allIncludeClasses); println("");
2536 println("using namespace std;\n");
2537 println("class " + newIntface);
2541 writeMethodCplusInterface(intMeth.getValue(), intDecl);
2545 System.out.println("IoTCompiler: Generated interface " + newIntface + ".hpp...");
2552 * HELPER: writeMethodCplusStub() writes the methods of the stub
2554 private void writeMethodCplusStub(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
2556 for (String method : methods) {
2558 List<String> methParams = intDecl.getMethodParams(method);
2559 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2560 print(checkAndGetCplusType(intDecl.getMethodType(method)) + " " +
2561 intDecl.getMethodId(method) + "(");
2562 boolean isCallbackMethod = false;
2563 String callbackType = null;
2564 for (int i = 0; i < methParams.size(); i++) {
2566 String paramType = methPrmTypes.get(i);
2567 // Check if this has callback object
2568 if (callbackClasses.contains(paramType)) {
2569 isCallbackMethod = true;
2570 callbackType = paramType;
2571 // Even if there're 2 callback arguments, we expect them to be of the same interface
2573 String methPrmType = checkAndGetCplusType(methPrmTypes.get(i));
2574 String methParamComplete = checkAndGetCplusArray(methPrmType, methParams.get(i));
2575 print(methParamComplete);
2576 // Check if this is the last element (don't print a comma)
2577 if (i != methParams.size() - 1) {
2582 if (isCallbackMethod)
2583 writeCallbackMethodBodyCplusStub(intDecl, methParams, methPrmTypes, method, callbackType);
2585 writeStdMethodBodyCplusStub(intDecl, methParams, methPrmTypes, method);
2587 // Write the init callback helper method
2588 if (isCallbackMethod) {
2589 writeInitCallbackCplusStub(callbackType, intDecl);
2590 writeInitCallbackSendInfoCplusStub(intDecl);
2597 * HELPER: writeCallbackMethodBodyCplusStub() writes the callback method of the stub class
2599 private void writeCallbackMethodBodyCplusStub(InterfaceDecl intDecl, List<String> methParams,
2600 List<String> methPrmTypes, String method, String callbackType) {
2602 // Check if this is single object, array, or list of objects
2603 boolean isArrayOrList = false;
2604 String callbackParam = null;
2605 for (int i = 0; i < methParams.size(); i++) {
2607 String paramType = methPrmTypes.get(i);
2608 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
2609 String param = methParams.get(i);
2610 if (isArrayOrList(paramType, param)) { // Generate loop
2611 println("for (" + paramType + "* cb : " + getSimpleIdentifier(param) + ") {");
2612 println(callbackType + "_CallbackSkeleton* skel = new " + callbackType + "_CallbackSkeleton(cb, objIdCnt++);");
2613 isArrayOrList = true;
2614 callbackParam = getSimpleIdentifier(param);
2616 println(callbackType + "_CallbackSkeleton* skel = new " + callbackType + "_CallbackSkeleton(" +
2617 getSimpleIdentifier(param) + ", objIdCnt++);");
2618 println("vecCallbackObj.push_back(skel);");
2619 if (isArrayOrList(paramType, param))
2623 println("int numParam = " + methParams.size() + ";");
2624 println("int methodId = " + intDecl.getMethodNumId(method) + ";");
2625 String retType = intDecl.getMethodType(method);
2626 //String retTypeC = checkAndGetCplusType(retType);
2627 //println("string retType = \"" + checkAndGetCplusArrayType(getStructType(getEnumType(retTypeC))) + "\";");
2628 println("string retType = \"" + checkAndGetCplusRetClsType(getStructType(getEnumType(retType))) + "\";");
2629 // Generate array of parameter types
2630 print("string paramCls[] = { ");
2631 for (int i = 0; i < methParams.size(); i++) {
2632 String paramType = methPrmTypes.get(i);
2633 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
2635 } else { // Generate normal classes if it's not a callback object
2636 String paramTypeC = checkAndGetCplusArgClsType(methPrmTypes.get(i), methParams.get(i));
2637 print("\"" + paramTypeC + "\"");
2639 if (i != methParams.size() - 1) // Check if this is the last element
2643 print("int ___paramCB = ");
2645 println(callbackParam + ".size();");
2648 // Generate array of parameter objects
2649 print("void* paramObj[] = { ");
2650 for (int i = 0; i < methParams.size(); i++) {
2651 String paramType = methPrmTypes.get(i);
2652 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
2653 print("&___paramCB");
2655 print(getSimpleIdentifier(methParams.get(i)));
2656 if (i != methParams.size() - 1)
2660 // Check if this is "void"
2661 if (retType.equals("void")) {
2662 println("void* retObj = NULL;");
2663 println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
2664 } else { // We do have a return value
2665 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
2666 println(checkAndGetCplusType(retType) + " retVal;");
2668 println(checkAndGetCplusType(retType) + " retVal = " + generateCplusInitializer(retType) + ";");
2669 println("void* retObj = &retVal;");
2670 println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
2671 println("return retVal;");
2677 * HELPER: checkAndWriteEnumTypeCplusStub() writes the enum type (convert from enum to int)
2679 private void checkAndWriteEnumTypeCplusStub(List<String> methParams, List<String> methPrmTypes) {
2681 // Iterate and find enum declarations
2682 for (int i = 0; i < methParams.size(); i++) {
2683 String paramType = methPrmTypes.get(i);
2684 String param = methParams.get(i);
2685 if (isEnumClass(getGenericType(paramType))) {
2686 // Check if this is enum type
2687 if (isArrayOrList(paramType, param)) { // An array or vector
2688 println("int len" + i + " = " + getSimpleIdentifier(param) + ".size();");
2689 println("vector<int> paramEnum" + i + "(len" + i + ");");
2690 println("for (int i = 0; i < len" + i + "; i++) {");
2691 println("paramEnum" + i + "[i] = (int) " + getSimpleIdentifier(param) + "[i];");
2693 } else { // Just one element
2694 println("vector<int> paramEnum" + i + "(1);");
2695 println("paramEnum" + i + "[0] = (int) " + param + ";");
2703 * HELPER: checkAndWriteEnumRetTypeCplusStub() writes the enum return type (convert from enum to int)
2705 private void checkAndWriteEnumRetTypeCplusStub(String retType) {
2707 // Strips off array "[]" for return type
2708 String pureType = getSimpleArrayType(getGenericType(retType));
2709 // Take the inner type of generic
2710 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
2711 pureType = getGenericType(retType);
2712 if (isEnumClass(pureType)) {
2713 // Check if this is enum type
2714 println("vector<int> retEnumInt;");
2715 println("void* retObj = &retEnumInt;");
2716 println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
2717 if (isArrayOrList(retType, retType)) { // An array or vector
2718 println("int retLen = retEnumInt.size();");
2719 println("vector<" + pureType + "> retVal(retLen);");
2720 println("for (int i = 0; i < retLen; i++) {");
2721 println("retVal[i] = (" + pureType + ") retEnumInt[i];");
2723 } else { // Just one element
2724 println(pureType + " retVal = (" + pureType + ") retEnumInt[0];");
2726 println("return retVal;");
2732 * HELPER: checkAndWriteStructSetupCplusStub() writes the struct type setup
2734 private void checkAndWriteStructSetupCplusStub(List<String> methParams, List<String> methPrmTypes,
2735 InterfaceDecl intDecl, String method) {
2737 // Iterate and find struct declarations
2738 for (int i = 0; i < methParams.size(); i++) {
2739 String paramType = methPrmTypes.get(i);
2740 String param = methParams.get(i);
2741 String simpleType = getSimpleType(paramType);
2742 if (isStructClass(simpleType)) {
2743 // Check if this is enum type
2744 println("int numParam" + i + " = 1;");
2745 int methodNumId = intDecl.getMethodNumId(method);
2746 String helperMethod = methodNumId + "struct" + i;
2747 println("int methodIdStruct" + i + " = " + intDecl.getHelperMethodNumId(helperMethod) + ";");
2748 println("string retTypeStruct" + i + " = \"void\";");
2749 println("string paramClsStruct" + i + "[] = { \"int\" };");
2750 print("int structLen" + i + " = ");
2751 if (isArrayOrList(param, paramType)) { // An array
2752 println(getSimpleArrayType(param) + ".size();");
2753 } else { // Just one element
2756 println("void* paramObjStruct" + i + "[] = { &structLen" + i + " };");
2757 println("void* retStructLen" + i + " = NULL;");
2758 println("rmiCall->remoteCall(objectId, methodIdStruct" + i +
2759 ", retTypeStruct" + i + ", paramClsStruct" + i + ", paramObjStruct" + i +
2760 ", numParam" + i + ", retStructLen" + i + ");\n");
2767 * HELPER: writeLengthStructParamClassCplusStub() writes lengths of params
2769 private void writeLengthStructParamClassCplusStub(List<String> methParams, List<String> methPrmTypes) {
2771 // Iterate and find struct declarations - count number of params
2772 for (int i = 0; i < methParams.size(); i++) {
2773 String paramType = methPrmTypes.get(i);
2774 String param = methParams.get(i);
2775 String simpleType = getGenericType(paramType);
2776 if (isStructClass(simpleType)) {
2777 int members = getNumOfMembers(simpleType);
2778 if (isArrayOrList(param, paramType)) { // An array
2779 String structLen = param + ".size()";
2780 print(members + "*" + structLen);
2782 print(Integer.toString(members));
2785 if (i != methParams.size() - 1) {
2793 * HELPER: writeStructMembersCplusStub() writes member parameters of struct
2795 private void writeStructMembersCplusStub(String simpleType, String paramType, String param) {
2797 // Get the struct declaration for this struct and generate initialization code
2798 StructDecl structDecl = getStructDecl(simpleType);
2799 List<String> memTypes = structDecl.getMemberTypes(simpleType);
2800 List<String> members = structDecl.getMembers(simpleType);
2801 if (isArrayOrList(param, paramType)) { // An array or list
2802 println("for(int i = 0; i < " + param + ".size(); i++) {");
2804 if (isArrayOrList(param, paramType)) { // An array or list
2805 for (int i = 0; i < members.size(); i++) {
2806 String prmTypeC = checkAndGetCplusArgClsType(memTypes.get(i), members.get(i));
2807 println("paramCls[pos] = \"" + prmTypeC + "\";");
2808 print("paramObj[pos++] = &" + param + "[i].");
2809 print(getSimpleIdentifier(members.get(i)));
2813 } else { // Just one struct element
2814 for (int i = 0; i < members.size(); i++) {
2815 String prmTypeC = checkAndGetCplusArgClsType(memTypes.get(i), members.get(i));
2816 println("paramCls[pos] = \"" + prmTypeC + "\";");
2817 print("paramObj[pos++] = &" + param + ".");
2818 print(getSimpleIdentifier(members.get(i)));
2826 * HELPER: writeStructParamClassCplusStub() writes member parameters of struct
2828 private void writeStructParamClassCplusStub(List<String> methParams, List<String> methPrmTypes) {
2830 print("int numParam = ");
2831 writeLengthStructParamClassCplusStub(methParams, methPrmTypes);
2833 println("void* paramObj[numParam];");
2834 println("string paramCls[numParam];");
2835 println("int pos = 0;");
2836 // Iterate again over the parameters
2837 for (int i = 0; i < methParams.size(); i++) {
2838 String paramType = methPrmTypes.get(i);
2839 String param = methParams.get(i);
2840 String simpleType = getGenericType(paramType);
2841 if (isStructClass(simpleType)) {
2842 writeStructMembersCplusStub(simpleType, paramType, param);
2844 String prmTypeC = checkAndGetCplusArgClsType(methPrmTypes.get(i), methParams.get(i));
2845 println("paramCls[pos] = \"" + prmTypeC + "\";");
2846 print("paramObj[pos++] = &");
2847 print(getEnumParam(methPrmTypes.get(i), getSimpleIdentifier(methParams.get(i)), i));
2856 * HELPER: writeStructRetMembersCplusStub() writes member parameters of struct for return statement
2858 private void writeStructRetMembersCplusStub(String simpleType, String retType) {
2860 // Get the struct declaration for this struct and generate initialization code
2861 StructDecl structDecl = getStructDecl(simpleType);
2862 List<String> memTypes = structDecl.getMemberTypes(simpleType);
2863 List<String> members = structDecl.getMembers(simpleType);
2864 if (isArrayOrList(retType, retType)) { // An array or list
2865 println("for(int i = 0; i < retLen; i++) {");
2867 if (isArrayOrList(retType, retType)) { // An array or list
2868 for (int i = 0; i < members.size(); i++) {
2869 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
2870 print("structRet[i]." + getSimpleIdentifier(members.get(i)));
2871 println(" = retParam" + i + "[i];");
2874 } else { // Just one struct element
2875 for (int i = 0; i < members.size(); i++) {
2876 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
2877 print("structRet." + getSimpleIdentifier(members.get(i)));
2878 println(" = retParam" + i + ";");
2881 println("return structRet;");
2886 * HELPER: writeStructReturnCplusStub() writes member parameters of struct for return statement
2888 private void writeStructReturnCplusStub(String simpleType, String retType) {
2890 // Minimum retLen is 1 if this is a single struct object
2891 println("int retLen = 0;");
2892 println("void* retLenObj = { &retLen };");
2893 // Handle the returned struct!!!
2894 println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retLenObj);");
2895 int numMem = getNumOfMembers(simpleType);
2896 println("int numRet = " + numMem + "*retLen;");
2897 println("string retCls[numRet];");
2898 println("void* retObj[numRet];");
2899 StructDecl structDecl = getStructDecl(simpleType);
2900 List<String> memTypes = structDecl.getMemberTypes(simpleType);
2901 List<String> members = structDecl.getMembers(simpleType);
2903 if (isArrayOrList(retType, retType)) { // An array or list
2904 for (int i = 0; i < members.size(); i++) {
2905 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
2906 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
2907 println(getSimpleType(getEnumType(prmType)) + " retParam" + i + "[retLen];");
2909 } else { // Just one struct element
2910 for (int i = 0; i < members.size(); i++) {
2911 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
2912 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
2913 println(getSimpleType(getEnumType(prmType)) + " retParam" + i + ";");
2916 println("int retPos = 0;");
2917 // Get the struct declaration for this struct and generate initialization code
2918 if (isArrayOrList(retType, retType)) { // An array or list
2919 println("for(int i = 0; i < retLen; i++) {");
2920 for (int i = 0; i < members.size(); i++) {
2921 String prmTypeC = checkAndGetCplusArgClsType(memTypes.get(i), members.get(i));
2922 println("retCls[retPos] = \"" + prmTypeC + "\";");
2923 println("retObj[retPos++] = &retParam" + i + "[i];");
2926 } else { // Just one struct element
2927 for (int i = 0; i < members.size(); i++) {
2928 String prmTypeC = checkAndGetCplusArgClsType(memTypes.get(i), members.get(i));
2929 println("retCls[retPos] = \"" + prmTypeC + "\";");
2930 println("retObj[retPos++] = &retParam" + i + ";");
2933 println("rmiCall->getStructObjects(retCls, numRet, retObj);");
2934 if (isArrayOrList(retType, retType)) { // An array or list
2935 println("vector<" + simpleType + "> structRet(retLen);");
2937 println(simpleType + " structRet;");
2938 writeStructRetMembersCplusStub(simpleType, retType);
2943 * HELPER: writeStdMethodBodyCplusStub() writes the standard method body in the stub class
2945 private void writeStdMethodBodyCplusStub(InterfaceDecl intDecl, List<String> methParams,
2946 List<String> methPrmTypes, String method) {
2948 checkAndWriteStructSetupCplusStub(methParams, methPrmTypes, intDecl, method);
2949 println("int methodId = " + intDecl.getMethodNumId(method) + ";");
2950 String retType = intDecl.getMethodType(method);
2951 println("string retType = \"" + checkAndGetCplusRetClsType(getStructType(getEnumType(retType))) + "\";");
2952 // Generate array of parameter types
2953 if (isStructPresent(methParams, methPrmTypes)) {
2954 writeStructParamClassCplusStub(methParams, methPrmTypes);
2956 println("int numParam = " + methParams.size() + ";");
2957 print("string paramCls[] = { ");
2958 for (int i = 0; i < methParams.size(); i++) {
2959 String paramTypeC = checkAndGetCplusArgClsType(methPrmTypes.get(i), methParams.get(i));
2960 print("\"" + paramTypeC + "\"");
2961 // Check if this is the last element (don't print a comma)
2962 if (i != methParams.size() - 1) {
2967 checkAndWriteEnumTypeCplusStub(methParams, methPrmTypes);
2968 // Generate array of parameter objects
2969 print("void* paramObj[] = { ");
2970 for (int i = 0; i < methParams.size(); i++) {
2971 print("&" + getEnumParam(methPrmTypes.get(i), getSimpleIdentifier(methParams.get(i)), i));
2972 // Check if this is the last element (don't print a comma)
2973 if (i != methParams.size() - 1) {
2979 // Check if this is "void"
2980 if (retType.equals("void")) {
2981 println("void* retObj = NULL;");
2982 println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
2983 } else { // We do have a return value
2984 // Generate array of parameter types
2985 if (isStructClass(getGenericType(getSimpleArrayType(retType)))) {
2986 writeStructReturnCplusStub(getGenericType(getSimpleArrayType(retType)), retType);
2988 // Check if the return value NONPRIMITIVES
2989 if (isEnumClass(getSimpleArrayType(getGenericType(retType)))) {
2990 checkAndWriteEnumRetTypeCplusStub(retType);
2992 //if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
2993 if (isArrayOrList(retType,retType))
2994 println(checkAndGetCplusType(retType) + " retVal;");
2996 println(checkAndGetCplusType(retType) + " retVal = " + generateCplusInitializer(retType) + ";");
2998 println("void* retObj = &retVal;");
2999 println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
3000 println("return retVal;");
3008 * HELPER: writePropertiesCplusStub() writes the properties of the stub class
3010 private void writePropertiesCplusPermission(String intface) {
3012 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3013 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3014 String newIntface = intMeth.getKey();
3015 int newObjectId = getNewIntfaceObjectId(newIntface);
3016 println("const static int object" + newObjectId + "Id = " + newObjectId + ";\t//" + newIntface);
3017 println("static set<int> set" + newObjectId + "Allowed;");
3022 * HELPER: writePropertiesCplusStub() writes the properties of the stub class
3024 private void writePropertiesCplusStub(String intface, String newIntface, boolean callbackExist, Set<String> callbackClasses) {
3026 println("IoTRMICall *rmiCall;");
3027 //println("IoTRMIObject\t\t\t*rmiObj;");
3028 println("string address;");
3029 println("vector<int> ports;\n");
3030 // Get the object Id
3031 Integer objId = mapIntfaceObjId.get(intface);
3032 println("const static int objectId = " + objId + ";");
3033 mapNewIntfaceObjId.put(newIntface, objId);
3034 mapIntfaceObjId.put(intface, objId++);
3035 if (callbackExist) {
3036 // We assume that each class only has one callback interface for now
3037 Iterator it = callbackClasses.iterator();
3038 String callbackType = (String) it.next();
3039 println("// Callback properties");
3040 println("IoTRMIObject *rmiObj;");
3041 println("vector<" + callbackType + "*> vecCallbackObj;");
3042 println("static int objIdCnt;");
3043 // Generate permission stuff for callback stubs
3044 writePropertiesCplusPermission(callbackType);
3051 * HELPER: writeConstructorCplusStub() writes the constructor of the stub class
3053 private void writeConstructorCplusStub(String newStubClass, boolean callbackExist, Set<String> callbackClasses) {
3055 println(newStubClass +
3056 "(int _port, const char* _address, int _rev, bool* _bResult, vector<int> _ports) {");
3057 println("address = _address;");
3058 println("ports = _ports;");
3059 println("rmiCall = new IoTRMICall(_port, _address, _rev, _bResult);");
3060 if (callbackExist) {
3061 Iterator it = callbackClasses.iterator();
3062 String callbackType = (String) it.next();
3063 println("thread th1 (&" + newStubClass + "::___initCallBack, this);");
3064 println("th1.detach();");
3065 println("___regCB();");
3072 * HELPER: writeDeconstructorCplusStub() writes the deconstructor of the stub class
3074 private void writeDeconstructorCplusStub(String newStubClass, boolean callbackExist, Set<String> callbackClasses) {
3076 println("~" + newStubClass + "() {");
3077 println("if (rmiCall != NULL) {");
3078 println("delete rmiCall;");
3079 println("rmiCall = NULL;");
3081 if (callbackExist) {
3082 // We assume that each class only has one callback interface for now
3083 println("if (rmiObj != NULL) {");
3084 println("delete rmiObj;");
3085 println("rmiObj = NULL;");
3087 Iterator it = callbackClasses.iterator();
3088 String callbackType = (String) it.next();
3089 println("for(" + callbackType + "* cb : vecCallbackObj) {");
3090 println("delete cb;");
3091 println("cb = NULL;");
3100 * HELPER: writeCplusMethodCallbackPermission() writes permission checks in stub for callbacks
3102 private void writeCplusMethodCallbackPermission(String intface) {
3104 println("int methodId = IoTRMIObject::getMethodId(method);");
3105 // Get all the different stubs
3106 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3107 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3108 String newIntface = intMeth.getKey();
3109 int newObjectId = getNewIntfaceObjectId(newIntface);
3110 println("if (set" + newObjectId + "Allowed.find(methodId) == set" + newObjectId + "Allowed.end()) {");
3111 println("cerr << \"Callback object for " + intface + " is not allowed to access method: \" << methodId;");
3112 println("exit(-1);");
3119 * HELPER: writeInitCallbackCplusStub() writes the initialization of callback
3121 private void writeInitCallbackCplusStub(String intface, InterfaceDecl intDecl) {
3123 println("void ___initCallBack() {");
3124 println("bool bResult = false;");
3125 println("rmiObj = new IoTRMIObject(ports[0], &bResult);");
3126 println("while (true) {");
3127 println("char* method = rmiObj->getMethodBytes();");
3128 writeCplusMethodCallbackPermission(intface);
3129 println("int objId = IoTRMIObject::getObjectId(method);");
3130 println("if (objId < vecCallbackObj.size()) { // Check if still within range");
3131 println(intface + "_CallbackSkeleton* skel = dynamic_cast<" + intface +
3132 "_CallbackSkeleton*> (vecCallbackObj.at(objId));");
3133 println("skel->invokeMethod(rmiObj);");
3136 println("cerr << \"Illegal object Id: \" << to_string(objId);");
3137 // TODO: perhaps need to change this into "throw" to make it cleaner (allow stack unfolding)
3138 println("exit(-1);");
3146 * HELPER: writeCplusInitCallbackPermission() writes the permission for callback
3148 private void writeCplusInitCallbackPermission(String intface, InterfaceDecl intDecl, boolean callbackExist) {
3150 if (callbackExist) {
3151 String method = "___initCallBack()";
3152 int methodNumId = intDecl.getHelperMethodNumId(method);
3153 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3154 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3155 String newIntface = intMeth.getKey();
3156 int newObjectId = getNewIntfaceObjectId(newIntface);
3157 println("set" + newObjectId + "Allowed.insert(" + methodNumId + ");");
3164 * HELPER: writeInitCallbackSendInfoCplusStub() writes the initialization (send info part) of callback
3166 private void writeInitCallbackSendInfoCplusStub(InterfaceDecl intDecl) {
3168 // Generate info sending part
3169 println("void ___regCB() {");
3170 println("int numParam = 3;");
3171 String method = "___initCallBack()";
3172 int methodNumId = intDecl.getHelperMethodNumId(method);
3173 println("int methodId = " + methodNumId + ";");
3174 //writeCplusCallbackPermission(intface, methodNumId);
3175 println("string retType = \"void\";");
3176 println("string paramCls[] = { \"int\", \"string\", \"int\" };");
3177 println("int rev = 0;");
3178 println("void* paramObj[] = { &ports[0], &address, &rev };");
3179 println("void* retObj = NULL;");
3180 println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
3186 * generateCPlusStubClasses() generate stubs based on the methods list in C++
3188 public void generateCPlusStubClasses() throws IOException {
3190 // Create a new directory
3191 String path = createDirectories(dir, subdir);
3192 for (String intface : mapIntfacePTH.keySet()) {
3194 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3195 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3196 // Open a new file to write into
3197 String newIntface = intMeth.getKey();
3198 String newStubClass = newIntface + "_Stub";
3199 FileWriter fw = new FileWriter(path + "/" + newStubClass + ".hpp");
3200 pw = new PrintWriter(new BufferedWriter(fw));
3201 // Write file headers
3202 println("#ifndef _" + newStubClass.toUpperCase() + "_HPP__");
3203 println("#define _" + newStubClass.toUpperCase() + "_HPP__");
3204 println("#include <iostream>");
3205 // Find out if there are callback objects
3206 Set<String> methods = intMeth.getValue();
3207 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
3208 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
3209 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
3210 boolean callbackExist = !callbackClasses.isEmpty();
3211 if (callbackExist) // Need thread library if this has callback
3212 println("#include <thread>");
3213 println("#include \"" + newIntface + ".hpp\""); println("");
3214 println("using namespace std;"); println("");
3215 println("class " + newStubClass + " : public " + newIntface); println("{");
3216 println("private:\n");
3217 writePropertiesCplusStub(intface, newIntface, callbackExist, callbackClasses);
3218 println("public:\n");
3219 // Add default constructor and destructor
3220 println(newStubClass + "() { }"); println("");
3221 writeConstructorCplusStub(newStubClass, callbackExist, callbackClasses);
3222 writeDeconstructorCplusStub(newStubClass, callbackExist, callbackClasses);
3224 writeMethodCplusStub(methods, intDecl, callbackClasses);
3225 print("}"); println(";");
3227 writePermissionInitializationCplus(intface, newStubClass, intDecl);
3228 writeObjectIdCountInitializationCplus(newStubClass, callbackExist);
3231 System.out.println("IoTCompiler: Generated stub class " + newStubClass + ".hpp...");
3238 * HELPER: writePropertiesCplusCallbackStub() writes the properties of the stub class
3240 private void writePropertiesCplusCallbackStub(String intface, String newIntface, boolean callbackExist, Set<String> callbackClasses) {
3242 println("IoTRMICall *rmiCall;");
3243 // Get the object Id
3244 println("int objectId;");
3245 if (callbackExist) {
3246 // We assume that each class only has one callback interface for now
3247 Iterator it = callbackClasses.iterator();
3248 String callbackType = (String) it.next();
3249 println("// Callback properties");
3250 println("IoTRMIObject *rmiObj;");
3251 println("vector<" + callbackType + "*> vecCallbackObj;");
3252 println("static int objIdCnt;");
3253 // TODO: Need to initialize address and ports if we want to have callback-in-callback
3254 println("string address;");
3255 println("vector<int> ports;\n");
3256 writePropertiesCplusPermission(callbackType);
3263 * HELPER: writeConstructorCplusCallbackStub() writes the constructor of the stub class
3265 private void writeConstructorCplusCallbackStub(String newStubClass, boolean callbackExist, Set<String> callbackClasses) {
3267 println(newStubClass + "(IoTRMICall* _rmiCall, int _objectId) {");
3268 println("objectId = _objectId;");
3269 println("rmiCall = _rmiCall;");
3270 if (callbackExist) {
3271 Iterator it = callbackClasses.iterator();
3272 String callbackType = (String) it.next();
3273 println("thread th1 (&" + newStubClass + "::___initCallBack, this);");
3274 println("th1.detach();");
3275 println("___regCB();");
3282 * generateCPlusCallbackStubClasses() generate callback stubs based on the methods list in C++
3284 public void generateCPlusCallbackStubClasses() throws IOException {
3286 // Create a new directory
3287 String path = createDirectories(dir, subdir);
3288 for (String intface : mapIntfacePTH.keySet()) {
3290 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3291 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3292 // Open a new file to write into
3293 String newIntface = intMeth.getKey();
3294 String newStubClass = newIntface + "_CallbackStub";
3295 FileWriter fw = new FileWriter(path + "/" + newStubClass + ".hpp");
3296 pw = new PrintWriter(new BufferedWriter(fw));
3297 // Find out if there are callback objects
3298 Set<String> methods = intMeth.getValue();
3299 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
3300 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
3301 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
3302 boolean callbackExist = !callbackClasses.isEmpty();
3303 // Write file headers
3304 println("#ifndef _" + newStubClass.toUpperCase() + "_HPP__");
3305 println("#define _" + newStubClass.toUpperCase() + "_HPP__");
3306 println("#include <iostream>");
3308 println("#include <thread>");
3309 println("#include \"" + newIntface + ".hpp\""); println("");
3310 println("using namespace std;"); println("");
3311 println("class " + newStubClass + " : public " + newIntface); println("{");
3312 println("private:\n");
3313 writePropertiesCplusCallbackStub(intface, newIntface, callbackExist, callbackClasses);
3314 println("public:\n");
3315 // Add default constructor and destructor
3316 println(newStubClass + "() { }"); println("");
3317 writeConstructorCplusCallbackStub(newStubClass, callbackExist, callbackClasses);
3318 writeDeconstructorCplusStub(newStubClass, callbackExist, callbackClasses);
3320 writeMethodCplusStub(methods, intDecl, callbackClasses);
3323 writePermissionInitializationCplus(intface, newStubClass, intDecl);
3324 writeObjectIdCountInitializationCplus(newStubClass, callbackExist);
3327 System.out.println("IoTCompiler: Generated callback stub class " + newIntface + ".hpp...");
3334 * HELPER: writePropertiesCplusSkeleton() writes the properties of the skeleton class
3336 private void writePropertiesCplusSkeleton(String intface, boolean callbackExist, Set<String> callbackClasses) {
3338 println(intface + " *mainObj;");
3340 if (callbackExist) {
3341 Iterator it = callbackClasses.iterator();
3342 String callbackType = (String) it.next();
3343 String exchangeType = checkAndGetParamClass(callbackType);
3344 println("// Callback properties");
3345 println("static int objIdCnt;");
3346 println("vector<" + exchangeType + "*> vecCallbackObj;");
3347 println("IoTRMICall *rmiCall;");
3349 println("IoTRMIObject *rmiObj;\n");
3350 // Keep track of object Ids of all stubs registered to this interface
3351 writePropertiesCplusPermission(intface);
3357 * HELPER: writeObjectIdCountInitializationCplus() writes the initialization of objIdCnt variable
3359 private void writeObjectIdCountInitializationCplus(String newSkelClass, boolean callbackExist) {
3362 println("int " + newSkelClass + "::objIdCnt = 0;");
3367 * HELPER: writePermissionInitializationCplus() writes the initialization of permission set
3369 private void writePermissionInitializationCplus(String intface, String newSkelClass, InterfaceDecl intDecl) {
3371 // Keep track of object Ids of all stubs registered to this interface
3372 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3373 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3374 String newIntface = intMeth.getKey();
3375 int newObjectId = getNewIntfaceObjectId(newIntface);
3376 print("set<int> " + newSkelClass + "::set" + newObjectId + "Allowed {");
3377 Set<String> methodIds = intMeth.getValue();
3379 for (String methodId : methodIds) {
3380 int methodNumId = intDecl.getMethodNumId(methodId);
3381 print(Integer.toString(methodNumId));
3382 // Check if this is the last element (don't print a comma)
3383 if (i != methodIds.size() - 1) {
3394 * HELPER: writeStructPermissionCplusSkeleton() writes permission for struct helper
3396 private void writeStructPermissionCplusSkeleton(Collection<String> methods, InterfaceDecl intDecl, String intface) {
3398 // Use this set to handle two same methodIds
3399 for (String method : methods) {
3400 List<String> methParams = intDecl.getMethodParams(method);
3401 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
3402 // Check for params with structs
3403 for (int i = 0; i < methParams.size(); i++) {
3404 String paramType = methPrmTypes.get(i);
3405 String param = methParams.get(i);
3406 String simpleType = getSimpleType(paramType);
3407 if (isStructClass(simpleType)) {
3408 int methodNumId = intDecl.getMethodNumId(method);
3409 String helperMethod = methodNumId + "struct" + i;
3410 int helperMethodNumId = intDecl.getHelperMethodNumId(helperMethod);
3411 // Iterate over interfaces to give permissions to
3412 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3413 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3414 String newIntface = intMeth.getKey();
3415 int newObjectId = getNewIntfaceObjectId(newIntface);
3416 println("set" + newObjectId + "Allowed.insert(" + helperMethodNumId + ");");
3425 * HELPER: writeConstructorCplusSkeleton() writes the constructor of the skeleton class
3427 private void writeConstructorCplusSkeleton(String newSkelClass, String intface, boolean callbackExist, InterfaceDecl intDecl, Collection<String> methods) {
3429 println(newSkelClass + "(" + intface + " *_mainObj, int _port) {");
3430 println("bool _bResult = false;");
3431 println("mainObj = _mainObj;");
3432 println("rmiObj = new IoTRMIObject(_port, &_bResult);");
3433 writeCplusInitCallbackPermission(intface, intDecl, callbackExist);
3434 writeStructPermissionCplusSkeleton(methods, intDecl, intface);
3435 println("___waitRequestInvokeMethod();");
3441 * HELPER: writeDeconstructorCplusSkeleton() writes the deconstructor of the skeleton class
3443 private void writeDeconstructorCplusSkeleton(String newSkelClass, boolean callbackExist, Set<String> callbackClasses) {
3445 println("~" + newSkelClass + "() {");
3446 println("if (rmiObj != NULL) {");
3447 println("delete rmiObj;");
3448 println("rmiObj = NULL;");
3450 if (callbackExist) {
3451 // We assume that each class only has one callback interface for now
3452 println("if (rmiCall != NULL) {");
3453 println("delete rmiCall;");
3454 println("rmiCall = NULL;");
3456 Iterator it = callbackClasses.iterator();
3457 String callbackType = (String) it.next();
3458 String exchangeType = checkAndGetParamClass(callbackType);
3459 println("for(" + exchangeType + "* cb : vecCallbackObj) {");
3460 println("delete cb;");
3461 println("cb = NULL;");
3470 * HELPER: writeStdMethodBodyCplusSkeleton() writes the standard method body in the skeleton class
3472 private void writeStdMethodBodyCplusSkeleton(List<String> methParams, String methodId, String methodType) {
3474 if (methodType.equals("void"))
3475 print("mainObj->" + methodId + "(");
3477 print("return mainObj->" + methodId + "(");
3478 for (int i = 0; i < methParams.size(); i++) {
3480 print(getSimpleIdentifier(methParams.get(i)));
3481 // Check if this is the last element (don't print a comma)
3482 if (i != methParams.size() - 1) {
3491 * HELPER: writeInitCallbackCplusSkeleton() writes the init callback method for skeleton class
3493 private void writeInitCallbackCplusSkeleton(boolean callbackSkeleton) {
3495 // This is a callback skeleton generation
3496 if (callbackSkeleton)
3497 println("void ___regCB(IoTRMIObject* rmiObj) {");
3499 println("void ___regCB() {");
3500 println("int numParam = 3;");
3501 println("int param1 = 0;");
3502 println("string param2 = \"\";");
3503 println("int param3 = 0;");
3504 println("string paramCls[] = { \"int\", \"string\", \"int\" };");
3505 println("void* paramObj[] = { ¶m1, ¶m2, ¶m3 };");
3506 println("rmiObj->getMethodParams(paramCls, numParam, paramObj);");
3507 println("bool bResult = false;");
3508 println("rmiCall = new IoTRMICall(param1, param2.c_str(), param3, &bResult);");
3514 * HELPER: writeMethodCplusSkeleton() writes the method of the skeleton class
3516 private void writeMethodCplusSkeleton(Collection<String> methods, InterfaceDecl intDecl,
3517 Set<String> callbackClasses, boolean callbackSkeleton) {
3519 for (String method : methods) {
3521 List<String> methParams = intDecl.getMethodParams(method);
3522 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
3523 String methodId = intDecl.getMethodId(method);
3524 String methodType = checkAndGetCplusType(intDecl.getMethodType(method));
3525 print(methodType + " " + methodId + "(");
3526 boolean isCallbackMethod = false;
3527 String callbackType = null;
3528 for (int i = 0; i < methParams.size(); i++) {
3530 String origParamType = methPrmTypes.get(i);
3531 if (callbackClasses.contains(origParamType)) { // Check if this has callback object
3532 isCallbackMethod = true;
3533 callbackType = origParamType;
3535 String paramType = checkAndGetParamClass(methPrmTypes.get(i));
3536 String methPrmType = checkAndGetCplusType(paramType);
3537 String methParamComplete = checkAndGetCplusArray(methPrmType, methParams.get(i));
3538 print(methParamComplete);
3539 // Check if this is the last element (don't print a comma)
3540 if (i != methParams.size() - 1) {
3545 // Now, write the body of skeleton!
3546 writeStdMethodBodyCplusSkeleton(methParams, methodId, intDecl.getMethodType(method));
3548 if (isCallbackMethod)
3549 writeInitCallbackCplusSkeleton(callbackSkeleton);
3555 * HELPER: writeCallbackCplusNumStubs() writes the numStubs variable
3557 private void writeCallbackCplusNumStubs(List<String> methParams, List<String> methPrmTypes, String callbackType) {
3559 for (int i = 0; i < methParams.size(); i++) {
3560 String paramType = methPrmTypes.get(i);
3561 String param = methParams.get(i);
3562 //if (callbackType.equals(paramType)) {
3563 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
3564 String exchParamType = checkAndGetParamClass(paramType);
3565 // Print array if this is array or list if this is a list of callback objects
3566 println("int numStubs" + i + " = 0;");
3573 * HELPER: writeCallbackCplusStubGeneration() writes the callback stub generation part
3575 private void writeCallbackCplusStubGeneration(List<String> methParams, List<String> methPrmTypes, String callbackType) {
3577 // Iterate over callback objects
3578 for (int i = 0; i < methParams.size(); i++) {
3579 String paramType = methPrmTypes.get(i);
3580 String param = methParams.get(i);
3581 // Generate a loop if needed
3582 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
3583 String exchParamType = checkAndGetParamClass(paramType);
3584 if (isArrayOrList(paramType, param)) {
3585 println("vector<" + exchParamType + "> stub;");
3586 println("for (int objId = 0; objId < numStubs" + i + "; objId++) {");
3587 println(exchParamType + "* cb" + i + " = new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt);");
3588 println("stub" + i + ".push_back(cb);");
3589 println("vecCallbackObj.push_back(cb);");
3590 println("objIdCnt++;");
3593 println(exchParamType + "* stub" + i + " = new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt);");
3594 println("vecCallbackObj.push_back(stub" + i + ");");
3595 println("objIdCnt++;");
3603 * HELPER: checkAndWriteEnumTypeCplusSkeleton() writes the enum type (convert from enum to int)
3605 private void checkAndWriteEnumTypeCplusSkeleton(List<String> methParams, List<String> methPrmTypes) {
3607 // Iterate and find enum declarations
3608 for (int i = 0; i < methParams.size(); i++) {
3609 String paramType = methPrmTypes.get(i);
3610 String param = methParams.get(i);
3611 String simpleType = getGenericType(paramType);
3612 if (isEnumClass(simpleType)) {
3613 // Check if this is enum type
3614 if (isArrayOrList(paramType, param)) { // An array
3615 println("int len" + i + " = paramEnumInt" + i + ".size();");
3616 println("vector<" + simpleType + "> paramEnum" + i + "(len" + i + ");");
3617 println("for (int i=0; i < len" + i + "; i++) {");
3618 println("paramEnum" + i + "[i] = (" + simpleType + ") paramEnumInt" + i + "[i];");
3620 } else { // Just one element
3621 println(simpleType + " paramEnum" + i + ";");
3622 println("paramEnum" + i + " = (" + simpleType + ") paramEnumInt" + i + "[0];");
3630 * HELPER: checkAndWriteEnumRetTypeCplusSkeleton() writes the enum return type (convert from enum to int)
3632 private void checkAndWriteEnumRetTypeCplusSkeleton(String retType) {
3634 // Strips off array "[]" for return type
3635 String pureType = getSimpleArrayType(getGenericType(retType));
3636 // Take the inner type of generic
3637 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
3638 pureType = getGenericType(retType);
3639 if (isEnumClass(pureType)) {
3640 // Check if this is enum type
3642 if (isArrayOrList(retType, retType)) { // An array
3643 println("int retLen = retEnum.size();");
3644 println("vector<int> retEnumInt(retLen);");
3645 println("for (int i=0; i < retLen; i++) {");
3646 println("retEnumInt[i] = (int) retEnum[i];");
3648 } else { // Just one element
3649 println("vector<int> retEnumInt(1);");
3650 println("retEnumInt[0] = (int) retEnum;");
3657 * HELPER: writeMethodHelperReturnCplusSkeleton() writes the return statement part in skeleton
3659 private void writeMethodInputParameters(List<String> methParams, List<String> methPrmTypes,
3660 Set<String> callbackClasses, String methodId) {
3662 print(methodId + "(");
3663 for (int i = 0; i < methParams.size(); i++) {
3664 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
3665 if (callbackClasses.contains(paramType))
3667 else if (isEnumClass(getGenericType(paramType))) // Check if this is enum type
3668 print("paramEnum" + i);
3669 else if (isStructClass(getGenericType(paramType))) // Struct type
3670 print("paramStruct" + i);
3672 print(getSimpleIdentifier(methParams.get(i)));
3673 if (i != methParams.size() - 1) {
3682 * HELPER: writeMethodHelperReturnCplusSkeleton() writes the return statement part in skeleton
3684 private void writeMethodHelperReturnCplusSkeleton(InterfaceDecl intDecl, List<String> methParams,
3685 List<String> methPrmTypes, String method, boolean isCallbackMethod, String callbackType,
3686 String methodId, Set<String> callbackClasses) {
3688 println("rmiObj->getMethodParams(paramCls, numParam, paramObj);");
3689 if (isCallbackMethod)
3690 writeCallbackCplusStubGeneration(methParams, methPrmTypes, callbackType);
3691 checkAndWriteEnumTypeCplusSkeleton(methParams, methPrmTypes);
3692 writeStructMembersInitCplusSkeleton(intDecl, methParams, methPrmTypes, method);
3693 // Check if this is "void"
3694 String retType = intDecl.getMethodType(method);
3695 // Check if this is "void"
3696 if (retType.equals("void")) {
3697 writeMethodInputParameters(methParams, methPrmTypes, callbackClasses, methodId);
3698 } else { // We do have a return value
3699 if (isEnumClass(getSimpleArrayType(getGenericType(retType)))) // Enum type
3700 print(checkAndGetCplusType(retType) + " retEnum = ");
3701 else if (isStructClass(getSimpleArrayType(getGenericType(retType)))) // Struct type
3702 print(checkAndGetCplusType(retType) + " retStruct = ");
3704 print(checkAndGetCplusType(retType) + " retVal = ");
3705 writeMethodInputParameters(methParams, methPrmTypes, callbackClasses, methodId);
3706 checkAndWriteEnumRetTypeCplusSkeleton(retType);
3707 if (isStructClass(getSimpleArrayType(getGenericType(retType)))) // Struct type
3708 writeStructReturnCplusSkeleton(getSimpleArrayType(getGenericType(retType)), retType);
3709 if (isEnumClass(getSimpleArrayType(getGenericType(retType)))) // Enum type
3710 println("void* retObj = &retEnumInt;");
3712 if (!isStructClass(getSimpleArrayType(getGenericType(retType)))) // Struct type
3713 println("void* retObj = &retVal;");
3714 String retTypeC = checkAndGetCplusType(retType);
3715 if (isStructClass(getSimpleArrayType(getGenericType(retType)))) // Struct type
3716 println("rmiObj->sendReturnObj(retObj, retCls, numRetObj);");
3718 println("rmiObj->sendReturnObj(retObj, \"" + checkAndGetCplusRetClsType(getEnumType(retType)) + "\");");
3724 * HELPER: writeStdMethodHelperBodyCplusSkeleton() writes the standard method body helper in the skeleton class
3726 private void writeStdMethodHelperBodyCplusSkeleton(InterfaceDecl intDecl, List<String> methParams,
3727 List<String> methPrmTypes, String method, String methodId, Set<String> callbackClasses) {
3729 // Generate array of parameter types
3730 boolean isCallbackMethod = false;
3731 String callbackType = null;
3732 print("string paramCls[] = { ");
3733 for (int i = 0; i < methParams.size(); i++) {
3734 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
3735 if (callbackClasses.contains(paramType)) {
3736 isCallbackMethod = true;
3737 callbackType = paramType;
3739 } else { // Generate normal classes if it's not a callback object
3740 String paramTypeC = checkAndGetCplusArgClsType(methPrmTypes.get(i), methParams.get(i));
3741 print("\"" + paramTypeC + "\"");
3743 if (i != methParams.size() - 1) {
3748 println("int numParam = " + methParams.size() + ";");
3749 if (isCallbackMethod)
3750 writeCallbackCplusNumStubs(methParams, methPrmTypes, callbackType);
3751 // Generate parameters
3752 for (int i = 0; i < methParams.size(); i++) {
3753 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
3754 if (!callbackClasses.contains(paramType)) {
3755 String methParamType = methPrmTypes.get(i);
3756 if (isEnumClass(getSimpleArrayType(getGenericType(methParamType)))) {
3757 // Check if this is enum type
3758 println("vector<int> paramEnumInt" + i + ";");
3760 String methPrmType = checkAndGetCplusType(methParamType);
3761 String methParamComplete = checkAndGetCplusArray(methPrmType, methParams.get(i));
3762 println(methParamComplete + ";");
3766 // Generate array of parameter objects
3767 print("void* paramObj[] = { ");
3768 for (int i = 0; i < methParams.size(); i++) {
3769 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
3770 if (callbackClasses.contains(paramType))
3771 print("&numStubs" + i);
3772 else if (isEnumClass(getGenericType(paramType))) // Check if this is enum type
3773 print("¶mEnumInt" + i);
3775 print("&" + getSimpleIdentifier(methParams.get(i)));
3776 if (i != methParams.size() - 1) {
3781 // Write the return value part
3782 writeMethodHelperReturnCplusSkeleton(intDecl, methParams, methPrmTypes, method, isCallbackMethod,
3783 callbackType, methodId, callbackClasses);
3788 * HELPER: writeStructMembersCplusSkeleton() writes member parameters of struct
3790 private void writeStructMembersCplusSkeleton(String simpleType, String paramType,
3791 String param, String method, InterfaceDecl intDecl, int iVar) {
3793 // Get the struct declaration for this struct and generate initialization code
3794 StructDecl structDecl = getStructDecl(simpleType);
3795 List<String> memTypes = structDecl.getMemberTypes(simpleType);
3796 List<String> members = structDecl.getMembers(simpleType);
3797 int methodNumId = intDecl.getMethodNumId(method);
3798 String counter = "struct" + methodNumId + "Size" + iVar;
3799 if (isArrayOrList(param, paramType)) { // An array or list
3800 println("for(int i = 0; i < " + counter + "; i++) {");
3803 if (isArrayOrList(param, paramType)) { // An array or list
3804 for (int i = 0; i < members.size(); i++) {
3805 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
3806 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
3807 println(getSimpleType(getEnumType(prmType)) + " param" + i + "[" + counter + "];");
3809 } else { // Just one struct element
3810 for (int i = 0; i < members.size(); i++) {
3811 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
3812 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
3813 println(getSimpleType(getEnumType(prmType)) + " param" + i + ";");
3816 println("int pos = 0;");
3817 if (isArrayOrList(param, paramType)) { // An array or list
3818 println("for(int i = 0; i < retLen; i++) {");
3819 for (int i = 0; i < members.size(); i++) {
3820 String prmTypeC = checkAndGetCplusArgClsType(memTypes.get(i), members.get(i));
3821 println("paramCls[pos] = \"" + prmTypeC + "\";");
3822 println("paramObj[pos++] = ¶m" + i + "[i];");
3825 } else { // Just one struct element
3826 for (int i = 0; i < members.size(); i++) {
3827 String prmTypeC = checkAndGetCplusArgClsType(memTypes.get(i), members.get(i));
3828 println("paramCls[pos] = \"" + prmTypeC + "\";");
3829 println("paramObj[pos++] = ¶m" + i + ";");
3836 * HELPER: writeStructMembersInitCplusSkeleton() writes member parameters initialization of struct
3838 private void writeStructMembersInitCplusSkeleton(InterfaceDecl intDecl, List<String> methParams,
3839 List<String> methPrmTypes, String method) {
3841 for (int i = 0; i < methParams.size(); i++) {
3842 String paramType = methPrmTypes.get(i);
3843 String param = methParams.get(i);
3844 String simpleType = getGenericType(paramType);
3845 if (isStructClass(simpleType)) {
3846 int methodNumId = intDecl.getMethodNumId(method);
3847 String counter = "struct" + methodNumId + "Size" + i;
3849 if (isArrayOrList(param, paramType)) { // An array or list
3850 println("vector<" + simpleType + "> paramStruct" + i + ";");
3852 println(simpleType + " paramStruct" + i + ";");
3853 // Initialize members
3854 StructDecl structDecl = getStructDecl(simpleType);
3855 List<String> members = structDecl.getMembers(simpleType);
3856 List<String> memTypes = structDecl.getMemberTypes(simpleType);
3857 if (isArrayOrList(param, paramType)) { // An array or list
3858 println("for(int i = 0; i < " + counter + "; i++) {");
3859 for (int j = 0; j < members.size(); j++) {
3860 print("paramStruct" + i + "[i]." + getSimpleIdentifier(members.get(j)));
3861 println(" = param" + j + "[i];");
3864 } else { // Just one struct element
3865 for (int j = 0; j < members.size(); j++) {
3866 print("paramStruct" + i + "." + getSimpleIdentifier(members.get(j)));
3867 println(" = param" + j + ";");
3876 * HELPER: writeStructReturnCplusSkeleton() writes parameters of struct for return statement
3878 private void writeStructReturnCplusSkeleton(String simpleType, String retType) {
3880 // Minimum retLen is 1 if this is a single struct object
3881 if (isArrayOrList(retType, retType))
3882 println("int retLen = retStruct.size();");
3883 else // Just single struct object
3884 println("int retLen = 1;");
3885 println("void* retLenObj = &retLen;");
3886 println("rmiObj->sendReturnObj(retLenObj, \"int\");");
3887 int numMem = getNumOfMembers(simpleType);
3888 println("int numRetObj = " + numMem + "*retLen;");
3889 println("string retCls[numRetObj];");
3890 println("void* retObj[numRetObj];");
3891 println("int retPos = 0;");
3892 // Get the struct declaration for this struct and generate initialization code
3893 StructDecl structDecl = getStructDecl(simpleType);
3894 List<String> memTypes = structDecl.getMemberTypes(simpleType);
3895 List<String> members = structDecl.getMembers(simpleType);
3896 if (isArrayOrList(retType, retType)) { // An array or list
3897 println("for(int i = 0; i < retLen; i++) {");
3898 for (int i = 0; i < members.size(); i++) {
3899 String prmTypeC = checkAndGetCplusArgClsType(memTypes.get(i), members.get(i));
3900 println("retCls[retPos] = \"" + prmTypeC + "\";");
3901 print("retObj[retPos++] = &retStruct[i].");
3902 print(getEnumParam(memTypes.get(i), getSimpleIdentifier(members.get(i)), i));
3906 } else { // Just one struct element
3907 for (int i = 0; i < members.size(); i++) {
3908 String prmTypeC = checkAndGetCplusArgClsType(memTypes.get(i), members.get(i));
3909 println("retCls[retPos] = \"" + prmTypeC + "\";");
3910 print("retObj[retPos++] = &retStruct.");
3911 print(getEnumParam(memTypes.get(i), getSimpleIdentifier(members.get(i)), i));
3920 * HELPER: writeMethodHelperStructCplusSkeleton() writes the struct in skeleton
3922 private void writeMethodHelperStructCplusSkeleton(InterfaceDecl intDecl, List<String> methParams,
3923 List<String> methPrmTypes, String method, String methodId, Set<String> callbackClasses) {
3925 // Generate array of parameter objects
3926 boolean isCallbackMethod = false;
3927 String callbackType = null;
3928 print("int numParam = ");
3929 writeLengthStructParamClassSkeleton(methParams, methPrmTypes, method, intDecl);
3931 println("string paramCls[numParam];");
3932 println("void* paramObj[numParam];");
3933 // Iterate again over the parameters
3934 for (int i = 0; i < methParams.size(); i++) {
3935 String paramType = methPrmTypes.get(i);
3936 String param = methParams.get(i);
3937 String simpleType = getGenericType(paramType);
3938 if (isStructClass(simpleType)) {
3939 writeStructMembersCplusSkeleton(simpleType, paramType, param, method, intDecl, i);
3941 String prmType = returnGenericCallbackType(methPrmTypes.get(i));
3942 if (callbackClasses.contains(prmType)) {
3943 isCallbackMethod = true;
3944 callbackType = paramType;
3945 writeCallbackCplusNumStubs(methParams, methPrmTypes, callbackType);
3946 println("paramCls[pos] = \"int\";");
3947 println("paramObj[pos++] = &numStubs" + i + ";");
3948 } else { // Generate normal classes if it's not a callback object
3949 String paramTypeC = checkAndGetCplusType(methPrmTypes.get(i));
3950 if (isEnumClass(getGenericType(paramTypeC))) { // Check if this is enum type
3951 println("vector<int> paramEnumInt" + i + ";");
3953 String methParamComplete = checkAndGetCplusArray(paramTypeC, methParams.get(i));
3954 println(methParamComplete + ";");
3956 String prmTypeC = checkAndGetCplusArgClsType(methPrmTypes.get(i), methParams.get(i));
3957 println("paramCls[pos] = \"" + prmTypeC + "\";");
3958 if (isEnumClass(getGenericType(paramType))) // Check if this is enum type
3959 println("paramObj[pos++] = ¶mEnumInt" + i);
3961 println("paramObj[pos++] = &" + getSimpleIdentifier(methParams.get(i)) + ";");
3965 // Write the return value part
3966 writeMethodHelperReturnCplusSkeleton(intDecl, methParams, methPrmTypes, method, isCallbackMethod,
3967 callbackType, methodId, callbackClasses);
3972 * HELPER: writeMethodHelperCplusSkeleton() writes the method helper of the skeleton class
3974 private void writeMethodHelperCplusSkeleton(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
3976 // Use this set to handle two same methodIds
3977 Set<String> uniqueMethodIds = new HashSet<String>();
3978 for (String method : methods) {
3980 List<String> methParams = intDecl.getMethodParams(method);
3981 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
3982 if (isStructPresent(methParams, methPrmTypes)) { // Treat struct differently
3983 String methodId = intDecl.getMethodId(method);
3985 String helperMethod = methodId;
3986 if (uniqueMethodIds.contains(methodId))
3987 helperMethod = helperMethod + intDecl.getMethodNumId(method);
3989 uniqueMethodIds.add(methodId);
3990 String retType = intDecl.getMethodType(method);
3991 print(helperMethod + "(");
3992 boolean begin = true;
3993 for (int i = 0; i < methParams.size(); i++) { // Print size variables
3994 String paramType = methPrmTypes.get(i);
3995 String param = methParams.get(i);
3996 String simpleType = getSimpleType(paramType);
3997 if (isStructClass(simpleType)) {
3998 if (!begin) { // Generate comma for not the beginning variable
3999 print(", "); begin = false;
4001 int methodNumId = intDecl.getMethodNumId(method);
4002 print("int struct" + methodNumId + "Size" + i);
4006 writeMethodHelperStructCplusSkeleton(intDecl, methParams, methPrmTypes, method, methodId, callbackClasses);
4009 String methodId = intDecl.getMethodId(method);
4011 String helperMethod = methodId;
4012 if (uniqueMethodIds.contains(methodId))
4013 helperMethod = helperMethod + intDecl.getMethodNumId(method);
4015 uniqueMethodIds.add(methodId);
4016 // Check if this is "void"
4017 String retType = intDecl.getMethodType(method);
4018 println(helperMethod + "() {");
4019 // Now, write the helper body of skeleton!
4020 writeStdMethodHelperBodyCplusSkeleton(intDecl, methParams, methPrmTypes, method, methodId, callbackClasses);
4024 // Write method helper for structs
4025 writeMethodHelperStructSetupCplusSkeleton(methods, intDecl);
4030 * HELPER: writeMethodHelperStructSetupCplusSkeleton() writes the method helper of struct in skeleton class
4032 private void writeMethodHelperStructSetupCplusSkeleton(Collection<String> methods,
4033 InterfaceDecl intDecl) {
4035 // Use this set to handle two same methodIds
4036 for (String method : methods) {
4038 List<String> methParams = intDecl.getMethodParams(method);
4039 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4040 // Check for params with structs
4041 for (int i = 0; i < methParams.size(); i++) {
4042 String paramType = methPrmTypes.get(i);
4043 String param = methParams.get(i);
4044 String simpleType = getSimpleType(paramType);
4045 if (isStructClass(simpleType)) {
4046 int methodNumId = intDecl.getMethodNumId(method);
4048 String helperMethod = methodNumId + "struct" + i;
4049 println(helperMethod + "() {");
4050 // Now, write the helper body of skeleton!
4051 println("string paramCls[] = { \"int\" };");
4052 println("int numParam = 1;");
4053 println("int param0 = 0;");
4054 println("void* paramObj[] = { ¶m0 };");
4055 println("rmiObj->getMethodParams(paramCls, numParam, paramObj);");
4056 println("return param0;");
4065 * HELPER: writeMethodHelperStructSetupCplusCallbackSkeleton() writes the method helper of struct in skeleton class
4067 private void writeMethodHelperStructSetupCplusCallbackSkeleton(Collection<String> methods,
4068 InterfaceDecl intDecl) {
4070 // Use this set to handle two same methodIds
4071 for (String method : methods) {
4073 List<String> methParams = intDecl.getMethodParams(method);
4074 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4075 // Check for params with structs
4076 for (int i = 0; i < methParams.size(); i++) {
4077 String paramType = methPrmTypes.get(i);
4078 String param = methParams.get(i);
4079 String simpleType = getSimpleType(paramType);
4080 if (isStructClass(simpleType)) {
4081 int methodNumId = intDecl.getMethodNumId(method);
4083 String helperMethod = methodNumId + "struct" + i;
4084 println(helperMethod + "(IoTRMIObject* rmiObj) {");
4085 // Now, write the helper body of skeleton!
4086 println("string paramCls[] = { \"int\" };");
4087 println("int numParam = 1;");
4088 println("int param0 = 0;");
4089 println("void* paramObj[] = { ¶m0 };");
4090 println("rmiObj->getMethodParams(paramCls, numParam, paramObj);");
4091 println("return param0;");
4100 * HELPER: writeCplusMethodPermission() writes permission checks in skeleton
4102 private void writeCplusMethodPermission(String intface) {
4104 // Get all the different stubs
4105 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
4106 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
4107 String newIntface = intMeth.getKey();
4108 int newObjectId = getNewIntfaceObjectId(newIntface);
4109 println("if (_objectId == object" + newObjectId + "Id) {");
4110 println("if (set" + newObjectId + "Allowed.find(methodId) == set" + newObjectId + "Allowed.end()) {");
4111 println("cerr << \"Object with object Id: \" << _objectId << \" is not allowed to access method: \" << methodId << endl;");
4112 println("exit(-1);");
4116 println("cerr << \"Object Id: \" << _objectId << \" not recognized!\" << endl;");
4117 println("exit(-1);");
4124 * HELPER: writeCplusWaitRequestInvokeMethod() writes the main loop of the skeleton class
4126 private void writeCplusWaitRequestInvokeMethod(Collection<String> methods, InterfaceDecl intDecl, boolean callbackExist, String intface) {
4128 // Use this set to handle two same methodIds
4129 Set<String> uniqueMethodIds = new HashSet<String>();
4130 println("void ___waitRequestInvokeMethod() {");
4131 // Write variables here if we have callbacks or enums or structs
4132 writeCountVarStructSkeleton(methods, intDecl);
4133 println("while (true) {");
4134 println("rmiObj->getMethodBytes();");
4135 println("int _objectId = rmiObj->getObjectId();");
4136 println("int methodId = rmiObj->getMethodId();");
4137 // Generate permission check
4138 writeCplusMethodPermission(intface);
4139 println("switch (methodId) {");
4140 // Print methods and method Ids
4141 for (String method : methods) {
4142 String methodId = intDecl.getMethodId(method);
4143 int methodNumId = intDecl.getMethodNumId(method);
4144 print("case " + methodNumId + ": ___");
4145 String helperMethod = methodId;
4146 if (uniqueMethodIds.contains(methodId))
4147 helperMethod = helperMethod + methodNumId;
4149 uniqueMethodIds.add(methodId);
4150 print(helperMethod + "(");
4151 writeInputCountVarStructSkeleton(method, intDecl);
4152 println("); break;");
4154 String method = "___initCallBack()";
4155 // Print case -9999 (callback handler) if callback exists
4156 if (callbackExist) {
4157 int methodId = intDecl.getHelperMethodNumId(method);
4158 println("case " + methodId + ": ___regCB(); break;");
4160 writeMethodCallStructSkeleton(methods, intDecl);
4161 println("default: ");
4162 println("cerr << \"Method Id \" << methodId << \" not recognized!\" << endl;");
4163 println("throw exception();");
4171 * generateCplusSkeletonClass() generate skeletons based on the methods list in C++
4173 public void generateCplusSkeletonClass() throws IOException {
4175 // Create a new directory
4176 String path = createDirectories(dir, subdir);
4177 for (String intface : mapIntfacePTH.keySet()) {
4178 // Open a new file to write into
4179 String newSkelClass = intface + "_Skeleton";
4180 FileWriter fw = new FileWriter(path + "/" + newSkelClass + ".hpp");
4181 pw = new PrintWriter(new BufferedWriter(fw));
4182 // Write file headers
4183 println("#ifndef _" + newSkelClass.toUpperCase() + "_HPP__");
4184 println("#define _" + newSkelClass.toUpperCase() + "_HPP__");
4185 println("#include <iostream>");
4186 println("#include \"" + intface + ".hpp\"\n");
4187 // Pass in set of methods and get import classes
4188 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4189 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
4190 List<String> methods = intDecl.getMethods();
4191 Set<String> includeClasses = getIncludeClasses(methods, intDecl, intface, true);
4192 List<String> stdIncludeClasses = getStandardCplusIncludeClasses();
4193 List<String> allIncludeClasses = getAllLibClasses(stdIncludeClasses, includeClasses);
4194 printIncludeStatements(allIncludeClasses); println("");
4195 println("using namespace std;\n");
4196 // Find out if there are callback objects
4197 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
4198 boolean callbackExist = !callbackClasses.isEmpty();
4199 // Write class header
4200 println("class " + newSkelClass + " : public " + intface); println("{");
4201 println("private:\n");
4203 writePropertiesCplusSkeleton(intface, callbackExist, callbackClasses);
4204 println("public:\n");
4205 // Write constructor
4206 writeConstructorCplusSkeleton(newSkelClass, intface, callbackExist, intDecl, methods);
4207 // Write deconstructor
4208 writeDeconstructorCplusSkeleton(newSkelClass, callbackExist, callbackClasses);
4210 writeMethodCplusSkeleton(methods, intDecl, callbackClasses, false);
4211 // Write method helper
4212 writeMethodHelperCplusSkeleton(methods, intDecl, callbackClasses);
4213 // Write waitRequestInvokeMethod() - main loop
4214 writeCplusWaitRequestInvokeMethod(methods, intDecl, callbackExist, intface);
4216 writePermissionInitializationCplus(intface, newSkelClass, intDecl);
4217 writeObjectIdCountInitializationCplus(newSkelClass, callbackExist);
4220 System.out.println("IoTCompiler: Generated skeleton class " + newSkelClass + ".hpp...");
4226 * HELPER: writePropertiesCplusCallbackSkeleton() writes the properties of the callback skeleton class
4228 private void writePropertiesCplusCallbackSkeleton(String intface, boolean callbackExist, Set<String> callbackClasses) {
4230 println(intface + " *mainObj;");
4231 // Keep track of object Ids of all stubs registered to this interface
4232 println("int objectId;");
4234 if (callbackExist) {
4235 Iterator it = callbackClasses.iterator();
4236 String callbackType = (String) it.next();
4237 String exchangeType = checkAndGetParamClass(callbackType);
4238 println("// Callback properties");
4239 println("IoTRMICall* rmiCall;");
4240 println("vector<" + exchangeType + "*> vecCallbackObj;");
4241 println("static int objIdCnt;");
4248 * HELPER: writeConstructorCplusCallbackSkeleton() writes the constructor of the skeleton class
4250 private void writeConstructorCplusCallbackSkeleton(String newSkelClass, String intface, boolean callbackExist, InterfaceDecl intDecl, Collection<String> methods) {
4252 println(newSkelClass + "(" + intface + " *_mainObj, int _objectId) {");
4253 println("mainObj = _mainObj;");
4254 println("objectId = _objectId;");
4260 * HELPER: writeDeconstructorCplusStub() writes the deconstructor of the stub class
4262 private void writeDeconstructorCplusCallbackSkeleton(String newStubClass, boolean callbackExist,
4263 Set<String> callbackClasses) {
4265 println("~" + newStubClass + "() {");
4266 if (callbackExist) {
4267 // We assume that each class only has one callback interface for now
4268 println("if (rmiCall != NULL) {");
4269 println("delete rmiCall;");
4270 println("rmiCall = NULL;");
4272 Iterator it = callbackClasses.iterator();
4273 String callbackType = (String) it.next();
4274 String exchangeType = checkAndGetParamClass(callbackType);
4275 println("for(" + exchangeType + "* cb : vecCallbackObj) {");
4276 println("delete cb;");
4277 println("cb = NULL;");
4286 * HELPER: writeMethodHelperCplusCallbackSkeleton() writes the method helper of callback skeleton class
4288 private void writeMethodHelperCplusCallbackSkeleton(Collection<String> methods, InterfaceDecl intDecl,
4289 Set<String> callbackClasses) {
4291 // Use this set to handle two same methodIds
4292 Set<String> uniqueMethodIds = new HashSet<String>();
4293 for (String method : methods) {
4295 List<String> methParams = intDecl.getMethodParams(method);
4296 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4297 if (isStructPresent(methParams, methPrmTypes)) { // Treat struct differently
4298 String methodId = intDecl.getMethodId(method);
4300 String helperMethod = methodId;
4301 if (uniqueMethodIds.contains(methodId))
4302 helperMethod = helperMethod + intDecl.getMethodNumId(method);
4304 uniqueMethodIds.add(methodId);
4305 String retType = intDecl.getMethodType(method);
4306 print(helperMethod + "(");
4307 boolean begin = true;
4308 for (int i = 0; i < methParams.size(); i++) { // Print size variables
4309 String paramType = methPrmTypes.get(i);
4310 String param = methParams.get(i);
4311 String simpleType = getSimpleType(paramType);
4312 if (isStructClass(simpleType)) {
4313 if (!begin) { // Generate comma for not the beginning variable
4314 print(", "); begin = false;
4316 int methodNumId = intDecl.getMethodNumId(method);
4317 print("int struct" + methodNumId + "Size" + i);
4320 println(", IoTRMIObject* rmiObj) {");
4321 writeMethodHelperStructCplusSkeleton(intDecl, methParams, methPrmTypes, method, methodId, callbackClasses);
4324 String methodId = intDecl.getMethodId(method);
4326 String helperMethod = methodId;
4327 if (uniqueMethodIds.contains(methodId))
4328 helperMethod = helperMethod + intDecl.getMethodNumId(method);
4330 uniqueMethodIds.add(methodId);
4331 // Check if this is "void"
4332 String retType = intDecl.getMethodType(method);
4333 println(helperMethod + "(IoTRMIObject* rmiObj) {");
4334 // Now, write the helper body of skeleton!
4335 writeStdMethodHelperBodyCplusSkeleton(intDecl, methParams, methPrmTypes, method, methodId, callbackClasses);
4339 // Write method helper for structs
4340 writeMethodHelperStructSetupCplusCallbackSkeleton(methods, intDecl);
4345 * HELPER: writeCplusCallbackWaitRequestInvokeMethod() writes the request invoke method of the skeleton callback class
4347 private void writeCplusCallbackWaitRequestInvokeMethod(Collection<String> methods, InterfaceDecl intDecl,
4348 boolean callbackExist) {
4350 // Use this set to handle two same methodIds
4351 Set<String> uniqueMethodIds = new HashSet<String>();
4352 println("void invokeMethod(IoTRMIObject* rmiObj) {");
4353 // Write variables here if we have callbacks or enums or structs
4354 writeCountVarStructSkeleton(methods, intDecl);
4355 // Write variables here if we have callbacks or enums or structs
4356 println("int methodId = rmiObj->getMethodId();");
4357 // TODO: code the permission check here!
4358 println("switch (methodId) {");
4359 // Print methods and method Ids
4360 for (String method : methods) {
4361 String methodId = intDecl.getMethodId(method);
4362 int methodNumId = intDecl.getMethodNumId(method);
4363 print("case " + methodNumId + ": ___");
4364 String helperMethod = methodId;
4365 if (uniqueMethodIds.contains(methodId))
4366 helperMethod = helperMethod + methodNumId;
4368 uniqueMethodIds.add(methodId);
4369 print(helperMethod + "(");
4370 if (writeInputCountVarStructSkeleton(method, intDecl))
4371 println(", rmiObj); break;");
4373 println("rmiObj); break;");
4375 String method = "___initCallBack()";
4376 // Print case -9999 (callback handler) if callback exists
4377 if (callbackExist) {
4378 int methodId = intDecl.getHelperMethodNumId(method);
4379 println("case " + methodId + ": ___regCB(rmiObj); break;");
4381 writeMethodCallStructCallbackSkeleton(methods, intDecl);
4382 println("default: ");
4383 println("cerr << \"Method Id \" << methodId << \" not recognized!\" << endl;");
4384 println("throw exception();");
4391 * generateCplusCallbackSkeletonClass() generate callback skeletons based on the methods list in C++
4393 public void generateCplusCallbackSkeletonClass() throws IOException {
4395 // Create a new directory
4396 String path = createDirectories(dir, subdir);
4397 for (String intface : mapIntfacePTH.keySet()) {
4398 // Open a new file to write into
4399 String newSkelClass = intface + "_CallbackSkeleton";
4400 FileWriter fw = new FileWriter(path + "/" + newSkelClass + ".hpp");
4401 pw = new PrintWriter(new BufferedWriter(fw));
4402 // Write file headers
4403 println("#ifndef _" + newSkelClass.toUpperCase() + "_HPP__");
4404 println("#define _" + newSkelClass.toUpperCase() + "_HPP__");
4405 println("#include <iostream>");
4406 println("#include \"" + intface + ".hpp\"\n");
4407 // Pass in set of methods and get import classes
4408 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4409 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
4410 List<String> methods = intDecl.getMethods();
4411 Set<String> includeClasses = getIncludeClasses(methods, intDecl, intface, true);
4412 List<String> stdIncludeClasses = getStandardCplusIncludeClasses();
4413 List<String> allIncludeClasses = getAllLibClasses(stdIncludeClasses, includeClasses);
4414 printIncludeStatements(allIncludeClasses); println("");
4415 // Find out if there are callback objects
4416 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
4417 boolean callbackExist = !callbackClasses.isEmpty();
4418 println("using namespace std;\n");
4419 // Write class header
4420 println("class " + newSkelClass + " : public " + intface); println("{");
4421 println("private:\n");
4423 writePropertiesCplusCallbackSkeleton(intface, callbackExist, callbackClasses);
4424 println("public:\n");
4425 // Write constructor
4426 writeConstructorCplusCallbackSkeleton(newSkelClass, intface, callbackExist, intDecl, methods);
4427 // Write deconstructor
4428 writeDeconstructorCplusCallbackSkeleton(newSkelClass, callbackExist, callbackClasses);
4430 writeMethodCplusSkeleton(methods, intDecl, callbackClasses, true);
4431 // Write method helper
4432 writeMethodHelperCplusCallbackSkeleton(methods, intDecl, callbackClasses);
4433 // Write waitRequestInvokeMethod() - main loop
4434 writeCplusCallbackWaitRequestInvokeMethod(methods, intDecl, callbackExist);
4436 writeObjectIdCountInitializationCplus(newSkelClass, callbackExist);
4439 System.out.println("IoTCompiler: Generated callback skeleton class " + newSkelClass + ".hpp...");
4445 * generateInitializer() generate initializer based on type
4447 public String generateCplusInitializer(String type) {
4449 // Generate dummy returns for now
4450 if (type.equals("short")||
4451 type.equals("int") ||
4452 type.equals("long") ||
4453 type.equals("float")||
4454 type.equals("double")) {
4457 } else if ( type.equals("String") ||
4458 type.equals("string")) {
4461 } else if ( type.equals("char") ||
4462 type.equals("byte")) {
4465 } else if ( type.equals("boolean")) {
4475 * setDirectory() sets a new directory for stub files
4477 public void setDirectory(String _subdir) {
4484 * printUsage() prints the usage of this compiler
4486 public static void printUsage() {
4488 System.out.println();
4489 System.out.println("Sentinel interface and stub compiler version 1.0");
4490 System.out.println("Copyright (c) 2015-2016 University of California, Irvine - Programming Language Group.");
4491 System.out.println("All rights reserved.");
4492 System.out.println("Usage:");
4493 System.out.println("\tjava IoTCompiler -help / --help / -h\n");
4494 System.out.println("\t\tDisplay this help texts\n\n");
4495 System.out.println("\tjava IoTCompiler [<main-policy-file> <req-policy-file>]");
4496 System.out.println("\tjava IoTCompiler [<main-policy-file> <req-policy-file>] [options]\n");
4497 System.out.println("\t\tTake one or more pairs of main-req policy files, and generate Java and/or C++ files\n");
4498 System.out.println("Options:");
4499 System.out.println("\t-java\t<directory>\tGenerate Java stub files");
4500 System.out.println("\t-cplus\t<directory>\tGenerate C++ stub files");
4501 System.out.println();
4506 * parseFile() prepares Lexer and Parser objects, then parses the file
4508 public static ParseNode parseFile(String file) {
4510 ParseNode pn = null;
4512 ComplexSymbolFactory csf = new ComplexSymbolFactory();
4513 ScannerBuffer lexer =
4514 new ScannerBuffer(new Lexer(new BufferedReader(new FileReader(file)),csf));
4515 Parser parse = new Parser(lexer,csf);
4516 pn = (ParseNode) parse.parse().value;
4517 } catch (Exception e) {
4518 e.printStackTrace();
4519 throw new Error("IoTCompiler: ERROR parsing policy file or wrong command line option: " + file + "\n");
4527 * Basic helper functions
4530 boolean newline=true;
4533 private void print(String str) {
4536 if (str.equals("}"))
4538 for(int i=0; i<tab; i++)
4548 * This function converts Java to C++ type for compilation
4550 private String convertType(String type) {
4552 if (mapPrimitives.containsKey(type))
4553 return mapPrimitives.get(type);
4560 * A collection of methods with print-to-file functionality
4562 private void println(String str) {
4565 if (str.contains("}") && !str.contains("{"))
4567 for(int i=0; i<tab; i++)
4576 private void updatetabbing(String str) {
4578 tablevel+=count(str,'{')-count(str,'}');
4582 private int count(String str, char key) {
4583 char[] array = str.toCharArray();
4585 for(int i=0; i<array.length; i++) {
4586 if (array[i] == key)
4593 private void createDirectory(String dirName) {
4595 File file = new File(dirName);
4596 if (!file.exists()) {
4598 System.out.println("IoTCompiler: Directory " + dirName + " has been created!");
4600 System.out.println("IoTCompiler: Failed to create directory " + dirName + "!");
4603 System.out.println("IoTCompiler: Directory " + dirName + " exists...");
4608 // Create a directory and possibly a sub directory
4609 private String createDirectories(String dir, String subdir) {
4612 createDirectory(path);
4613 if (subdir != null) {
4614 path = path + "/" + subdir;
4615 createDirectory(path);
4621 // Inserting array members into a Map object
4622 // that maps arrKey to arrVal objects
4623 private void arraysToMap(Map map, Object[] arrKey, Object[] arrVal) {
4625 for(int i = 0; i < arrKey.length; i++) {
4627 map.put(arrKey[i], arrVal[i]);
4632 // Check and find object Id for new interface in mapNewIntfaceObjId (callbacks)
4633 // Throw an error if the new interface is not found!
4634 // Basically the compiler needs to parse the policy (and requires) files for callback class first
4635 private int getNewIntfaceObjectId(String newIntface) {
4637 if (!mapNewIntfaceObjId.containsKey(newIntface)) {
4638 throw new Error("IoTCompiler: Need to parse policy and requires files for callback class first! " +
4639 "Please place the two files for callback class in front...\n");
4641 int retObjId = mapNewIntfaceObjId.get(newIntface);
4647 // Return parameter category, i.e. PRIMITIVES, NONPRIMITIVES, USERDEFINED, ENUM, or STRUCT
4648 private ParamCategory getParamCategory(String paramType) {
4650 if (mapPrimitives.containsKey(paramType)) {
4651 return ParamCategory.PRIMITIVES;
4652 // We can either use mapNonPrimitivesJava or mapNonPrimitivesCplus here
4653 } else if (mapNonPrimitivesJava.containsKey(getSimpleType(paramType))) {
4654 return ParamCategory.NONPRIMITIVES;
4655 } else if (isEnumClass(paramType)) {
4656 return ParamCategory.ENUM;
4657 } else if (isStructClass(paramType)) {
4658 return ParamCategory.STRUCT;
4660 return ParamCategory.USERDEFINED;
4664 // Return full class name for non-primitives to generate Java import statements
4665 // e.g. java.util.Set for Set
4666 private String getNonPrimitiveJavaClass(String paramNonPrimitives) {
4668 return mapNonPrimitivesJava.get(paramNonPrimitives);
4672 // Return full class name for non-primitives to generate Cplus include statements
4673 // e.g. #include <set> for Set
4674 private String getNonPrimitiveCplusClass(String paramNonPrimitives) {
4676 return mapNonPrimitivesCplus.get(paramNonPrimitives);
4680 // Get simple types, e.g. HashSet for HashSet<...>
4681 // Basically strip off the "<...>"
4682 private String getSimpleType(String paramType) {
4684 // Check if this is generics
4685 if(paramType.contains("<")) {
4686 String[] type = paramType.split("<");
4693 // Generate a set of standard classes for import statements
4694 private List<String> getStandardJavaIntfaceImportClasses() {
4696 List<String> importClasses = new ArrayList<String>();
4697 // Add the standard list first
4698 importClasses.add("java.util.List");
4699 importClasses.add("java.util.ArrayList");
4701 return importClasses;
4705 // Generate a set of standard classes for import statements
4706 private List<String> getStandardJavaImportClasses() {
4708 List<String> importClasses = new ArrayList<String>();
4709 // Add the standard list first
4710 importClasses.add("java.io.IOException");
4711 importClasses.add("java.util.List");
4712 importClasses.add("java.util.ArrayList");
4713 importClasses.add("java.util.Arrays");
4714 importClasses.add("iotrmi.Java.IoTRMICall");
4715 importClasses.add("iotrmi.Java.IoTRMIObject");
4717 return importClasses;
4721 // Generate a set of standard classes for import statements
4722 private List<String> getStandardCplusIncludeClasses() {
4724 List<String> importClasses = new ArrayList<String>();
4725 // Add the standard list first
4726 importClasses.add("<vector>");
4727 importClasses.add("<set>");
4728 importClasses.add("\"IoTRMICall.hpp\"");
4729 importClasses.add("\"IoTRMIObject.hpp\"");
4731 return importClasses;
4735 // Combine all classes for import statements
4736 private List<String> getAllLibClasses(Collection<String> stdLibClasses, Collection<String> libClasses) {
4738 List<String> allLibClasses = new ArrayList<String>(stdLibClasses);
4739 // Iterate over the list of import classes
4740 for (String str : libClasses) {
4741 if (!allLibClasses.contains(str)) {
4742 allLibClasses.add(str);
4745 return allLibClasses;
4750 // Generate a set of classes for import statements
4751 private Set<String> getImportClasses(Collection<String> methods, InterfaceDecl intDecl) {
4753 Set<String> importClasses = new HashSet<String>();
4754 for (String method : methods) {
4755 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4756 for (String paramType : methPrmTypes) {
4758 String simpleType = getSimpleType(paramType);
4759 if (getParamCategory(simpleType) == ParamCategory.NONPRIMITIVES) {
4760 importClasses.add(getNonPrimitiveJavaClass(simpleType));
4764 return importClasses;
4768 // Handle and return the correct enum declaration
4769 // In Java, if we declare enum in Camera interface, then it becomes "Camera.<enum>"
4770 private String getEnumParamDecl(String type, InterfaceDecl intDecl) {
4772 // Strips off array "[]" for return type
4773 String pureType = getSimpleArrayType(type);
4774 // Take the inner type of generic
4775 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
4776 pureType = getTypeOfGeneric(type)[0];
4777 if (isEnumClass(pureType)) {
4778 String enumType = intDecl.getInterface() + "." + type;
4785 // Handle and return the correct type
4786 private String getEnumParam(String type, String param, int i) {
4788 // Strips off array "[]" for return type
4789 String pureType = getSimpleArrayType(type);
4790 // Take the inner type of generic
4791 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
4792 pureType = getTypeOfGeneric(type)[0];
4793 if (isEnumClass(pureType)) {
4794 String enumParam = "paramEnum" + i;
4801 // Handle and return the correct enum declaration translate into int[]
4802 private String getEnumType(String type) {
4804 // Strips off array "[]" for return type
4805 String pureType = getSimpleArrayType(type);
4806 // Take the inner type of generic
4807 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
4808 pureType = getGenericType(type);
4809 if (isEnumClass(pureType)) {
4810 String enumType = "int[]";
4816 // Handle and return the correct enum declaration translate into int* for C
4817 private String getEnumCplusClsType(String type) {
4819 // Strips off array "[]" for return type
4820 String pureType = getSimpleArrayType(type);
4821 // Take the inner type of generic
4822 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
4823 pureType = getGenericType(type);
4824 if (isEnumClass(pureType)) {
4825 String enumType = "int*";
4832 // Handle and return the correct struct declaration
4833 private String getStructType(String type) {
4835 // Strips off array "[]" for return type
4836 String pureType = getSimpleArrayType(type);
4837 // Take the inner type of generic
4838 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
4839 pureType = getGenericType(type);
4840 if (isStructClass(pureType)) {
4841 String structType = "int";
4848 // Check if this an enum declaration
4849 private boolean isEnumClass(String type) {
4851 // Just iterate over the set of interfaces
4852 for (String intface : mapIntfacePTH.keySet()) {
4853 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4854 EnumDecl enumDecl = (EnumDecl) decHandler.getEnumDecl(intface);
4855 Set<String> setEnumDecl = enumDecl.getEnumDeclarations();
4856 if (setEnumDecl.contains(type))
4863 // Check if this an struct declaration
4864 private boolean isStructClass(String type) {
4866 // Just iterate over the set of interfaces
4867 for (String intface : mapIntfacePTH.keySet()) {
4868 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4869 StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
4870 List<String> listStructDecl = structDecl.getStructTypes();
4871 if (listStructDecl.contains(type))
4878 // Return a struct declaration
4879 private StructDecl getStructDecl(String type) {
4881 // Just iterate over the set of interfaces
4882 for (String intface : mapIntfacePTH.keySet()) {
4883 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4884 StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
4885 List<String> listStructDecl = structDecl.getStructTypes();
4886 if (listStructDecl.contains(type))
4893 // Return number of members (-1 if not found)
4894 private int getNumOfMembers(String type) {
4896 // Just iterate over the set of interfaces
4897 for (String intface : mapIntfacePTH.keySet()) {
4898 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4899 StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
4900 List<String> listStructDecl = structDecl.getStructTypes();
4901 if (listStructDecl.contains(type))
4902 return structDecl.getNumOfMembers(type);
4908 // Generate a set of classes for include statements
4909 private Set<String> getIncludeClasses(Collection<String> methods, InterfaceDecl intDecl, String intface, boolean needExchange) {
4911 Set<String> includeClasses = new HashSet<String>();
4912 for (String method : methods) {
4914 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4915 List<String> methParams = intDecl.getMethodParams(method);
4916 for (int i = 0; i < methPrmTypes.size(); i++) {
4918 String simpleType = getSimpleType(methPrmTypes.get(i));
4919 String param = methParams.get(i);
4920 if (getParamCategory(simpleType) == ParamCategory.NONPRIMITIVES) {
4921 includeClasses.add("<" + getNonPrimitiveCplusClass(simpleType) + ">");
4922 } else if (getParamCategory(simpleType) == ParamCategory.USERDEFINED) {
4923 // For original interface, we need it exchanged... not for stub interfaces
4925 includeClasses.add("\"" + exchangeParamType(simpleType) + ".hpp\"");
4926 includeClasses.add("\"" + exchangeParamType(simpleType) + "_CallbackStub.hpp\"");
4928 includeClasses.add("\"" + simpleType + ".hpp\"");
4929 includeClasses.add("\"" + simpleType + "_CallbackSkeleton.hpp\"");
4931 } else if (getParamCategory(getSimpleArrayType(simpleType)) == ParamCategory.ENUM) {
4932 includeClasses.add("\"" + simpleType + ".hpp\"");
4933 } else if (getParamCategory(getSimpleArrayType(simpleType)) == ParamCategory.STRUCT) {
4934 includeClasses.add("\"" + simpleType + ".hpp\"");
4935 } else if (param.contains("[]")) {
4936 // Check if this is array for C++; translate into vector
4937 includeClasses.add("<vector>");
4941 return includeClasses;
4945 // Generate a set of callback classes
4946 private Set<String> getCallbackClasses(Collection<String> methods, InterfaceDecl intDecl) {
4948 Set<String> callbackClasses = new HashSet<String>();
4949 for (String method : methods) {
4951 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4952 List<String> methParams = intDecl.getMethodParams(method);
4953 for (int i = 0; i < methPrmTypes.size(); i++) {
4955 String type = methPrmTypes.get(i);
4956 if (getParamCategory(type) == ParamCategory.USERDEFINED) {
4957 callbackClasses.add(type);
4958 } else if (getParamCategory(type) == ParamCategory.NONPRIMITIVES) {
4959 // Can be a List<...> of callback objects ...
4960 String genericType = getTypeOfGeneric(type)[0];
4961 if (getParamCategory(type) == ParamCategory.USERDEFINED) {
4962 callbackClasses.add(type);
4967 return callbackClasses;
4971 // Print import statements into file
4972 private void printImportStatements(Collection<String> importClasses) {
4974 for(String cls : importClasses) {
4975 println("import " + cls + ";");
4980 // Print include statements into file
4981 private void printIncludeStatements(Collection<String> includeClasses) {
4983 for(String cls : includeClasses) {
4984 println("#include " + cls);
4989 // Get the C++ version of a non-primitive type
4990 // e.g. set for Set and map for Map
4991 // Input nonPrimitiveType has to be generics in format
4992 private String[] getTypeOfGeneric(String nonPrimitiveType) {
4994 // Handle <, >, and , for 2-type generic/template
4995 String[] substr = nonPrimitiveType.split("<")[1].split(">")[0].split(",");
5000 // Gets generic type inside "<" and ">"
5001 private String getGenericType(String type) {
5003 // Handle <, >, and , for 2-type generic/template
5004 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES) {
5005 String[] substr = type.split("<")[1].split(">")[0].split(",");
5012 // This helper function strips off array declaration, e.g. int[] becomes int
5013 private String getSimpleArrayType(String type) {
5015 // Handle [ for array declaration
5016 String substr = type;
5017 if (type.contains("[]")) {
5018 substr = type.split("\\[\\]")[0];
5024 // This helper function strips off array declaration, e.g. D[] becomes D
5025 private String getSimpleIdentifier(String ident) {
5027 // Handle [ for array declaration
5028 String substr = ident;
5029 if (ident.contains("[]")) {
5030 substr = ident.split("\\[\\]")[0];
5036 // Checks and gets type in C++
5037 private String checkAndGetCplusType(String paramType) {
5039 if (getParamCategory(paramType) == ParamCategory.PRIMITIVES) {
5040 return convertType(paramType);
5041 } else if (getParamCategory(paramType) == ParamCategory.NONPRIMITIVES) {
5043 // Check for generic/template format
5044 if (paramType.contains("<") && paramType.contains(">")) {
5046 String genericClass = getSimpleType(paramType);
5047 String[] genericType = getTypeOfGeneric(paramType);
5048 String cplusTemplate = null;
5049 if (genericType.length == 1) // Generic/template with one type
5050 cplusTemplate = getNonPrimitiveCplusClass(genericClass) +
5051 "<" + convertType(genericType[0]) + ">";
5052 else // Generic/template with two types
5053 cplusTemplate = getNonPrimitiveCplusClass(genericClass) +
5054 "<" + convertType(genericType[0]) + "," + convertType(genericType[1]) + ">";
5055 return cplusTemplate;
5057 return getNonPrimitiveCplusClass(paramType);
5058 } else if(paramType.contains("[]")) { // Array type (used for return type only)
5059 String cArray = "vector<" + convertType(getSimpleArrayType(paramType)) + ">";
5061 } else if(getParamCategory(paramType) == ParamCategory.USERDEFINED) {
5062 return paramType + "*";
5064 // Just return it as is if it's not non-primitives
5066 //return checkAndGetParamClass(paramType, true);
5070 // Detect array declaration, e.g. int A[],
5071 // then generate "int A[]" in C++ as "vector<int> A"
5072 private String checkAndGetCplusArray(String paramType, String param) {
5074 String paramComplete = null;
5075 // Check for array declaration
5076 if (param.contains("[]")) {
5077 paramComplete = "vector<" + paramType + "> " + param.replace("[]","");
5079 // Just return it as is if it's not an array
5080 paramComplete = paramType + " " + param;
5082 return paramComplete;
5086 // Detect array declaration, e.g. int A[],
5087 // then generate "int A[]" in C++ as "vector<int> A"
5088 // This method just returns the type
5089 private String checkAndGetCplusArrayType(String paramType) {
5091 String paramTypeRet = null;
5092 // Check for array declaration
5093 if (paramType.contains("[]")) {
5094 String type = paramType.split("\\[\\]")[0];
5095 paramTypeRet = checkAndGetCplusType(type) + "[]";
5096 } else if (paramType.contains("vector")) {
5097 // Just return it as is if it's not an array
5098 String type = paramType.split("<")[1].split(">")[0];
5099 paramTypeRet = checkAndGetCplusType(type) + "[]";
5101 paramTypeRet = paramType;
5103 return paramTypeRet;
5107 // Detect array declaration, e.g. int A[],
5108 // then generate "int A[]" in C++ as "vector<int> A"
5109 // This method just returns the type
5110 private String checkAndGetCplusArrayType(String paramType, String param) {
5112 String paramTypeRet = null;
5113 // Check for array declaration
5114 if (param.contains("[]")) {
5115 paramTypeRet = checkAndGetCplusType(paramType) + "[]";
5116 } else if (paramType.contains("vector")) {
5117 // Just return it as is if it's not an array
5118 String type = paramType.split("<")[1].split(">")[0];
5119 paramTypeRet = checkAndGetCplusType(type) + "[]";
5121 paramTypeRet = paramType;
5123 return paramTypeRet;
5127 // Return the class type for class resolution (for return value)
5128 // - Check and return C++ array class, e.g. int A[] into int*
5129 // - Check and return C++ vector class, e.g. List<Integer> A into vector<int>
5130 private String checkAndGetCplusRetClsType(String paramType) {
5132 String paramTypeRet = null;
5133 // Check for array declaration
5134 if (paramType.contains("[]")) {
5135 String type = paramType.split("\\[\\]")[0];
5136 paramTypeRet = getSimpleArrayType(type) + "*";
5137 } else if (paramType.contains("<") && paramType.contains(">")) {
5138 // Just return it as is if it's not an array
5139 String type = paramType.split("<")[1].split(">")[0];
5140 paramTypeRet = "vector<" + getGenericType(type) + ">";
5142 paramTypeRet = paramType;
5144 return paramTypeRet;
5148 // Return the class type for class resolution (for method arguments)
5149 // - Check and return C++ array class, e.g. int A[] into int*
5150 // - Check and return C++ vector class, e.g. List<Integer> A into vector<int>
5151 private String checkAndGetCplusArgClsType(String paramType, String param) {
5153 String paramTypeRet = getEnumCplusClsType(paramType);
5154 if (!paramTypeRet.equals(paramType))
5155 // Just return if it is an enum type
5156 // Type will still be the same if it's not an enum type
5157 return paramTypeRet;
5159 // Check for array declaration
5160 if (param.contains("[]")) {
5161 paramTypeRet = getSimpleArrayType(paramType) + "*";
5162 } else if (paramType.contains("<") && paramType.contains(">")) {
5163 // Just return it as is if it's not an array
5164 String type = paramType.split("<")[1].split(">")[0];
5165 paramTypeRet = "vector<" + getGenericType(type) + ">";
5167 paramTypeRet = paramType;
5169 return paramTypeRet;
5173 // Detect array declaration, e.g. int A[],
5174 // then generate type "int[]"
5175 private String checkAndGetArray(String paramType, String param) {
5177 String paramTypeRet = null;
5178 // Check for array declaration
5179 if (param.contains("[]")) {
5180 paramTypeRet = paramType + "[]";
5182 // Just return it as is if it's not an array
5183 paramTypeRet = paramType;
5185 return paramTypeRet;
5189 // Is array or list?
5190 private boolean isArrayOrList(String paramType, String param) {
5192 // Check for array declaration
5195 else if (isList(paramType))
5203 // For return type we use retType as input parameter
5204 private boolean isArray(String param) {
5206 // Check for array declaration
5207 if (param.contains("[]"))
5215 private boolean isList(String paramType) {
5217 // Check for array declaration
5218 if (paramType.contains("List"))
5225 // Get the right type for a callback object
5226 private String checkAndGetParamClass(String paramType) {
5228 // Check if this is generics
5229 if(getParamCategory(paramType) == ParamCategory.USERDEFINED) {
5230 return exchangeParamType(paramType);
5236 // Returns the other interface for type-checking purposes for USERDEFINED
5237 // classes based on the information provided in multiple policy files
5238 // e.g. return CameraWithXXX instead of Camera
5239 private String exchangeParamType(String intface) {
5241 // Param type that's passed is the interface name we need to look for
5242 // in the map of interfaces, based on available policy files.
5243 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
5244 if (decHandler != null) {
5245 // We've found the required interface policy files
5246 RequiresDecl reqDecl = (RequiresDecl) decHandler.getRequiresDecl(intface);
5247 Set<String> setExchInt = reqDecl.getInterfaces();
5248 if (setExchInt.size() == 1) {
5249 Iterator iter = setExchInt.iterator();
5250 return (String) iter.next();
5252 throw new Error("IoTCompiler: Ambiguous stub interfaces: " + setExchInt.toString() +
5253 ". Only one new interface can be declared if the object " + intface +
5254 " needs to be passed in as an input parameter!\n");
5257 // NULL value - this means policy files missing
5258 throw new Error("IoTCompiler: Parameter type lookup failed for " + intface +
5259 "... Please provide the necessary policy files for user-defined types." +
5260 " If this is an array please type the brackets after the variable name," +
5261 " e.g. \"String str[]\", not \"String[] str\"." +
5262 " If this is a Collections (Java) / STL (C++) type, this compiler only" +
5263 " supports List/ArrayList (Java) or list (C++).\n");
5268 public static void main(String[] args) throws Exception {
5270 // If there is no argument or just "--help" or "-h", then invoke printUsage()
5271 if ((args[0].equals("-help") ||
5272 args[0].equals("--help")||
5273 args[0].equals("-h")) ||
5274 (args.length == 0)) {
5276 IoTCompiler.printUsage();
5278 } else if (args.length > 1) {
5280 IoTCompiler comp = new IoTCompiler();
5283 // Parse main policy file
5284 ParseNode pnPol = IoTCompiler.parseFile(args[i]);
5285 // Parse "requires" policy file
5286 ParseNode pnReq = IoTCompiler.parseFile(args[i+1]);
5287 // Get interface name
5288 String intface = ParseTreeHandler.getOrigIntface(pnPol);
5289 comp.setDataStructures(intface, pnPol, pnReq);
5290 comp.getMethodsForIntface(intface);
5292 // 1) Check if this is the last option before "-java" or "-cplus"
5293 // 2) Check if this is really the last option (no "-java" or "-cplus")
5294 } while(!args[i].equals("-java") &&
5295 !args[i].equals("-cplus") &&
5298 // Generate everything if we don't see "-java" or "-cplus"
5299 if (i == args.length) {
5300 comp.generateEnumJava();
5301 comp.generateStructJava();
5302 comp.generateJavaLocalInterfaces();
5303 comp.generateJavaInterfaces();
5304 comp.generateJavaStubClasses();
5305 comp.generateJavaCallbackStubClasses();
5306 comp.generateJavaSkeletonClass();
5307 comp.generateJavaCallbackSkeletonClass();
5308 comp.generateEnumCplus();
5309 comp.generateStructCplus();
5310 comp.generateCplusLocalInterfaces();
5311 comp.generateCPlusInterfaces();
5312 comp.generateCPlusStubClasses();
5313 comp.generateCPlusCallbackStubClasses();
5314 comp.generateCplusSkeletonClass();
5315 comp.generateCplusCallbackSkeletonClass();
5317 // Check other options
5318 while(i < args.length) {
5320 if (!args[i].equals("-java") &&
5321 !args[i].equals("-cplus")) {
5322 throw new Error("IoTCompiler: ERROR - unrecognized command line option: " + args[i] + "\n");
5324 if (i + 1 < args.length) {
5325 comp.setDirectory(args[i+1]);
5327 throw new Error("IoTCompiler: ERROR - please provide <directory> after option: " + args[i] + "\n");
5329 if (args[i].equals("-java")) {
5330 comp.generateEnumJava();
5331 comp.generateStructJava();
5332 comp.generateJavaLocalInterfaces();
5333 comp.generateJavaInterfaces();
5334 comp.generateJavaStubClasses();
5335 comp.generateJavaCallbackStubClasses();
5336 comp.generateJavaSkeletonClass();
5337 comp.generateJavaCallbackSkeletonClass();
5339 comp.generateEnumCplus();
5340 comp.generateStructCplus();
5341 comp.generateCplusLocalInterfaces();
5342 comp.generateCPlusInterfaces();
5343 comp.generateCPlusStubClasses();
5344 comp.generateCPlusCallbackStubClasses();
5345 comp.generateCplusSkeletonClass();
5346 comp.generateCplusCallbackSkeletonClass();
5353 // Need to at least have exactly 2 parameters, i.e. main policy file and requires file
5354 IoTCompiler.printUsage();
5355 throw new Error("IoTCompiler: At least two arguments (main and requires policy files) have to be provided!\n");