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 // Iterate over interfaces to give permissions to
1236 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
1237 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
1238 String newIntface = intMeth.getKey();
1239 int newObjectId = getNewIntfaceObjectId(newIntface);
1240 println("set" + newObjectId + "Allowed.add(" + methodNumId + ");");
1249 * HELPER: writeConstructorJavaSkeleton() writes the constructor of the skeleton class
1251 private void writeConstructorJavaSkeleton(String newSkelClass, String intface, InterfaceDecl intDecl, Collection<String> methods, boolean callbackExist) {
1253 println("public " + newSkelClass + "(" + intface + " _mainObj, int _port) throws Exception {");
1254 println("mainObj = _mainObj;");
1255 println("rmiObj = new IoTRMIObject(_port);");
1256 // Generate permission control initialization
1257 writeConstructorJavaPermission(intface);
1258 writeJavaInitCallbackPermission(intface, intDecl, callbackExist);
1259 writeStructPermissionJavaSkeleton(methods, intDecl, intface);
1260 println("___waitRequestInvokeMethod();");
1266 * HELPER: writeStdMethodBodyJavaSkeleton() writes the standard method body in the skeleton class
1268 private void writeStdMethodBodyJavaSkeleton(List<String> methParams, String methodId, String methodType) {
1270 if (methodType.equals("void"))
1271 print("mainObj." + methodId + "(");
1273 print("return mainObj." + methodId + "(");
1274 for (int i = 0; i < methParams.size(); i++) {
1276 print(getSimpleIdentifier(methParams.get(i)));
1277 // Check if this is the last element (don't print a comma)
1278 if (i != methParams.size() - 1) {
1287 * HELPER: writeInitCallbackJavaSkeleton() writes the init callback method for skeleton class
1289 private void writeInitCallbackJavaSkeleton(boolean callbackSkeleton) {
1291 // This is a callback skeleton generation
1292 if (callbackSkeleton)
1293 println("public void ___regCB(IoTRMIObject rmiObj) throws IOException {");
1295 println("public void ___regCB() throws IOException {");
1296 println("Object[] paramObj = rmiObj.getMethodParams(new Class<?>[] { int.class, String.class, int.class },");
1297 println("\tnew Class<?>[] { null, null, null });");
1298 println("rmiCall = new IoTRMICall((int) paramObj[0], (String) paramObj[1], (int) paramObj[2]);");
1304 * HELPER: writeMethodJavaSkeleton() writes the method of the skeleton class
1306 private void writeMethodJavaSkeleton(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses,
1307 boolean callbackSkeleton) {
1309 for (String method : methods) {
1311 List<String> methParams = intDecl.getMethodParams(method);
1312 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1313 String methodId = intDecl.getMethodId(method);
1314 print("public " + intDecl.getMethodType(method) + " " + methodId + "(");
1315 boolean isCallbackMethod = false;
1316 String callbackType = null;
1317 for (int i = 0; i < methParams.size(); i++) {
1319 String origParamType = methPrmTypes.get(i);
1320 String paramType = checkAndGetParamClass(origParamType);
1321 if (callbackClasses.contains(origParamType)) { // Check if this has callback object
1322 isCallbackMethod = true;
1323 callbackType = origParamType;
1325 print(paramType + " " + methParams.get(i));
1326 // Check if this is the last element (don't print a comma)
1327 if (i != methParams.size() - 1) {
1332 // Now, write the body of skeleton!
1333 writeStdMethodBodyJavaSkeleton(methParams, methodId, intDecl.getMethodType(method));
1335 if (isCallbackMethod)
1336 writeInitCallbackJavaSkeleton(callbackSkeleton);
1342 * HELPER: writeCallbackJavaStubGeneration() writes the callback stub generation part
1344 private Map<Integer,String> writeCallbackJavaStubGeneration(List<String> methParams, List<String> methPrmTypes,
1345 String callbackType) {
1347 Map<Integer,String> mapStubParam = new HashMap<Integer,String>();
1348 // Iterate over callback objects
1349 for (int i = 0; i < methParams.size(); i++) {
1350 String paramType = methPrmTypes.get(i);
1351 String param = methParams.get(i);
1352 //if (callbackType.equals(paramType)) {
1353 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
1355 String exchParamType = checkAndGetParamClass(paramType);
1356 // Print array if this is array or list if this is a list of callback objects
1357 if (isArray(param)) {
1358 println("int numStubs" + i + " = (int) paramObj[" + i + "];");
1359 println(exchParamType + "[] stub" + i + " = new " + exchParamType + "[numStubs" + i + "];");
1360 } else if (isList(paramType)) {
1361 println("int numStubs" + i + " = (int) paramObj[" + i + "];");
1362 println("List<" + exchParamType + "> stub" + i + " = new ArrayList<" + exchParamType + ">();");
1364 println(exchParamType + " stub" + i + " = new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt);");
1365 println("objIdCnt++;");
1368 // Generate a loop if needed
1369 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
1370 String exchParamType = checkAndGetParamClass(paramType);
1371 if (isArray(param)) {
1372 println("for (int objId = 0; objId < numStubs" + i + "; objId++) {");
1373 println("stub" + i + "[objId] = new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt);");
1374 println("objIdCnt++;");
1376 } else if (isList(paramType)) {
1377 println("for (int objId = 0; objId < numStubs" + i + "; objId++) {");
1378 println("stub" + i + ".add(new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt));");
1379 println("objIdCnt++;");
1382 mapStubParam.put(i, "stub" + i); // List of all stub parameters
1385 return mapStubParam;
1390 * HELPER: checkAndWriteEnumTypeJavaSkeleton() writes the enum type (convert from enum to int)
1392 private void checkAndWriteEnumTypeJavaSkeleton(List<String> methParams, List<String> methPrmTypes) {
1394 // Iterate and find enum declarations
1395 for (int i = 0; i < methParams.size(); i++) {
1396 String paramType = methPrmTypes.get(i);
1397 String param = methParams.get(i);
1398 String simpleType = getGenericType(paramType);
1399 if (isEnumClass(simpleType)) {
1400 // Check if this is enum type
1401 println("int paramInt" + i + "[] = (int[]) paramObj[" + i + "];");
1402 println(simpleType + "[] enumVals = " + simpleType + ".values();");
1403 if (isArray(param)) { // An array
1404 println("int len" + i + " = paramInt" + i + ".length;");
1405 println(simpleType + "[] paramEnum" + i + " = new " + simpleType + "[len" + i + "];");
1406 println("for (int i = 0; i < len" + i + "; i++) {");
1407 println("paramEnum" + i + "[i] = enumVals[paramInt" + i + "[i]];");
1409 } else if (isList(paramType)) { // A list
1410 println("int len" + i + " = paramInt" + i + ".length;");
1411 println("List<" + simpleType + "> paramEnum" + i + " = new ArrayList<" + simpleType + ">();");
1412 println("for (int i = 0; i < len" + i + "; i++) {");
1413 println("paramEnum" + i + ".add(enumVals[paramInt" + i + "[i]]);");
1415 } else { // Just one element
1416 println(simpleType + " paramEnum" + i + " = enumVals[paramInt" + i + "[0]];");
1424 * HELPER: checkAndWriteEnumRetTypeJavaSkeleton() writes the enum return type (convert from enum to int)
1426 private void checkAndWriteEnumRetTypeJavaSkeleton(String retType, String methodId) {
1428 // Strips off array "[]" for return type
1429 String pureType = getSimpleArrayType(getGenericType(retType));
1430 // Take the inner type of generic
1431 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
1432 pureType = getGenericType(retType);
1433 if (isEnumClass(pureType)) {
1434 // Check if this is enum type
1436 if (isArray(retType)) { // An array
1437 print(pureType + "[] retEnum = " + methodId + "(");
1438 } else if (isList(retType)) { // A list
1439 print("List<" + pureType + "> retEnum = " + methodId + "(");
1440 } else { // Just one element
1441 print(pureType + " retEnum = " + methodId + "(");
1448 * HELPER: checkAndWriteEnumRetConvJavaSkeleton() writes the enum return type (convert from enum to int)
1450 private void checkAndWriteEnumRetConvJavaSkeleton(String retType) {
1452 // Strips off array "[]" for return type
1453 String pureType = getSimpleArrayType(getGenericType(retType));
1454 // Take the inner type of generic
1455 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
1456 pureType = getGenericType(retType);
1457 if (isEnumClass(pureType)) {
1458 // Check if this is enum type
1459 if (isArray(retType)) { // An array
1460 println("int retLen = retEnum.length;");
1461 println("int[] retEnumVal = new int[retLen];");
1462 println("for (int i = 0; i < retLen; i++) {");
1463 println("retEnumVal[i] = retEnum[i].ordinal();");
1465 } else if (isList(retType)) { // A list
1466 println("int retLen = retEnum.size();");
1467 println("int[] retEnumVal = new int[retLen];");
1468 println("for (int i = 0; i < retLen; i++) {");
1469 println("retEnumVal[i] = retEnum.get(i).ordinal();");
1471 } else { // Just one element
1472 println("int[] retEnumVal = new int[1];");
1473 println("retEnumVal[0] = retEnum.ordinal();");
1475 println("Object retObj = retEnumVal;");
1481 * HELPER: writeLengthStructParamClassSkeleton() writes lengths of params
1483 private void writeLengthStructParamClassSkeleton(List<String> methParams, List<String> methPrmTypes,
1484 String method, InterfaceDecl intDecl) {
1486 // Iterate and find struct declarations - count number of params
1487 for (int i = 0; i < methParams.size(); i++) {
1488 String paramType = methPrmTypes.get(i);
1489 String param = methParams.get(i);
1490 String simpleType = getGenericType(paramType);
1491 if (isStructClass(simpleType)) {
1492 int members = getNumOfMembers(simpleType);
1493 print(Integer.toString(members) + "*");
1494 int methodNumId = intDecl.getMethodNumId(method);
1495 print("struct" + methodNumId + "Size" + i);
1498 if (i != methParams.size() - 1) {
1506 * HELPER: writeStructMembersJavaSkeleton() writes member parameters of struct
1508 private void writeStructMembersJavaSkeleton(String simpleType, String paramType,
1509 String param, String method, InterfaceDecl intDecl, int iVar) {
1511 // Get the struct declaration for this struct and generate initialization code
1512 StructDecl structDecl = getStructDecl(simpleType);
1513 List<String> memTypes = structDecl.getMemberTypes(simpleType);
1514 List<String> members = structDecl.getMembers(simpleType);
1515 if (isArrayOrList(param, paramType)) { // An array or list
1516 int methodNumId = intDecl.getMethodNumId(method);
1517 String counter = "struct" + methodNumId + "Size" + iVar;
1518 println("for(int i = 0; i < " + counter + "; i++) {");
1520 println("int pos = 0;");
1521 if (isArrayOrList(param, paramType)) { // An array or list
1522 println("for(int i = 0; i < retLen; i++) {");
1523 for (int i = 0; i < members.size(); i++) {
1524 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
1525 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
1526 println("paramClsGen[pos++] = null;");
1529 } else { // Just one struct element
1530 for (int i = 0; i < members.size(); i++) {
1531 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
1532 println("paramCls[pos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
1533 println("paramClsGen[pos++] = null;");
1540 * HELPER: writeStructMembersInitJavaSkeleton() writes member parameters initialization of struct
1542 private void writeStructMembersInitJavaSkeleton(InterfaceDecl intDecl, List<String> methParams,
1543 List<String> methPrmTypes, String method) {
1545 for (int i = 0; i < methParams.size(); i++) {
1546 String paramType = methPrmTypes.get(i);
1547 String param = methParams.get(i);
1548 String simpleType = getGenericType(paramType);
1549 if (isStructClass(simpleType)) {
1550 int methodNumId = intDecl.getMethodNumId(method);
1551 String counter = "struct" + methodNumId + "Size" + i;
1553 if (isArray(param)) { // An array
1554 println(simpleType + "[] paramStruct" + i + " = new " + simpleType + "[" + counter + "];");
1555 println("for(int i = 0; i < " + counter + "; i++) {");
1556 println("paramStruct" + i + "[i] = new " + simpleType + "();");
1558 } else if (isList(paramType)) { // A list
1559 println("List<" + simpleType + "> paramStruct" + i + " = new ArrayList<" + simpleType + ">();");
1561 println(simpleType + " paramStruct" + i + " = new " + simpleType + "();");
1562 println("int objPos = 0;");
1563 // Initialize members
1564 StructDecl structDecl = getStructDecl(simpleType);
1565 List<String> members = structDecl.getMembers(simpleType);
1566 List<String> memTypes = structDecl.getMemberTypes(simpleType);
1567 if (isArrayOrList(param, paramType)) { // An array or list
1568 println("for(int i = 0; i < " + counter + "; i++) {");
1570 if (isArray(param)) { // An array
1571 for (int j = 0; j < members.size(); j++) {
1572 String prmType = checkAndGetArray(memTypes.get(j), members.get(j));
1573 print("paramStruct" + i + "[i]." + getSimpleIdentifier(members.get(j)));
1574 println(" = (" + getSimpleType(getEnumType(prmType)) + ") paramObj[objPos++];");
1577 } else if (isList(paramType)) { // A list
1578 println(simpleType + " paramStructMem = new " + simpleType + "();");
1579 for (int j = 0; j < members.size(); j++) {
1580 String prmType = checkAndGetArray(memTypes.get(j), members.get(j));
1581 print("paramStructMem." + getSimpleIdentifier(members.get(j)));
1582 println(" = (" + getSimpleType(getEnumType(prmType)) + ") paramObj[objPos++];");
1584 println("paramStruct" + i + ".add(paramStructMem);");
1586 } else { // Just one struct element
1587 for (int j = 0; j < members.size(); j++) {
1588 String prmType = checkAndGetArray(memTypes.get(j), members.get(j));
1589 print("paramStruct" + i + "." + getSimpleIdentifier(members.get(j)));
1590 println(" = (" + getSimpleType(getEnumType(prmType)) + ") paramObj[objPos++];");
1594 // Take offsets of parameters
1595 println("int offset" + i +" = objPos;");
1602 * HELPER: writeStructReturnJavaSkeleton() writes struct for return statement
1604 private void writeStructReturnJavaSkeleton(String simpleType, String retType) {
1606 // Minimum retLen is 1 if this is a single struct object
1607 if (isArray(retType))
1608 println("int retLen = retStruct.length;");
1609 else if (isList(retType))
1610 println("int retLen = retStruct.size();");
1611 else // Just single struct object
1612 println("int retLen = 1;");
1613 println("Object retLenObj = retLen;");
1614 println("rmiObj.sendReturnObj(retLenObj);");
1615 int numMem = getNumOfMembers(simpleType);
1616 println("Class<?>[] retCls = new Class<?>[" + numMem + "*retLen];");
1617 println("Object[] retObj = new Object[" + numMem + "*retLen];");
1618 println("int retPos = 0;");
1619 // Get the struct declaration for this struct and generate initialization code
1620 StructDecl structDecl = getStructDecl(simpleType);
1621 List<String> memTypes = structDecl.getMemberTypes(simpleType);
1622 List<String> members = structDecl.getMembers(simpleType);
1623 if (isArrayOrList(retType, retType)) { // An array or list
1624 println("for(int i = 0; i < retLen; i++) {");
1625 for (int i = 0; i < members.size(); i++) {
1626 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
1627 println("retCls[retPos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
1628 print("retObj[retPos++] = retStruct[i].");
1629 print(getEnumParam(memTypes.get(i), getSimpleIdentifier(members.get(i)), i));
1633 } else { // Just one struct element
1634 for (int i = 0; i < members.size(); i++) {
1635 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
1636 println("retCls[retPos] = " + getSimpleType(getEnumType(prmType)) + ".class;");
1637 print("retObj[retPos++] = retStruct.");
1638 print(getEnumParam(memTypes.get(i), getSimpleIdentifier(members.get(i)), i));
1647 * HELPER: writeMethodHelperReturnJavaSkeleton() writes return statement part in skeleton
1649 private void writeMethodHelperReturnJavaSkeleton(InterfaceDecl intDecl, List<String> methParams,
1650 List<String> methPrmTypes, String method, boolean isCallbackMethod, String callbackType,
1651 boolean isStructMethod) {
1653 checkAndWriteEnumTypeJavaSkeleton(methParams, methPrmTypes);
1654 Map<Integer,String> mapStubParam = null;
1655 if (isCallbackMethod)
1656 mapStubParam = writeCallbackJavaStubGeneration(methParams, methPrmTypes, callbackType);
1657 // Check if this is "void"
1658 String retType = intDecl.getMethodType(method);
1659 if (retType.equals("void")) {
1660 print(intDecl.getMethodId(method) + "(");
1661 } else if (isEnumClass(getSimpleArrayType(getGenericType(retType)))) { // Enum type
1662 checkAndWriteEnumRetTypeJavaSkeleton(retType, intDecl.getMethodId(method));
1663 } else if (isStructClass(getSimpleArrayType(getGenericType(retType)))) { // Struct type
1664 print(retType + " retStruct = " + intDecl.getMethodId(method) + "(");
1665 } else { // We do have a return value
1666 print("Object retObj = " + intDecl.getMethodId(method) + "(");
1668 for (int i = 0; i < methParams.size(); i++) {
1670 if (isCallbackMethod) {
1671 print(mapStubParam.get(i)); // Get the callback parameter
1672 } else if (isEnumClass(getGenericType(methPrmTypes.get(i)))) { // Enum class
1673 print(getEnumParam(methPrmTypes.get(i), methParams.get(i), i));
1674 } else if (isStructClass(getGenericType(methPrmTypes.get(i)))) {
1675 print("paramStruct" + i);
1677 String prmType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
1679 print("(" + prmType + ") paramObj[offset" + i + "]");
1681 print("(" + prmType + ") paramObj[" + i + "]");
1683 if (i != methParams.size() - 1)
1687 if (!retType.equals("void")) {
1688 if (isEnumClass(getSimpleArrayType(getGenericType(retType)))) { // Enum type
1689 checkAndWriteEnumRetConvJavaSkeleton(retType);
1690 println("rmiObj.sendReturnObj(retObj);");
1691 } else if (isStructClass(getSimpleArrayType(getGenericType(retType)))) { // Struct type
1692 writeStructReturnJavaSkeleton(getSimpleArrayType(getGenericType(retType)), retType);
1693 println("rmiObj.sendReturnObj(retCls, retObj);");
1695 println("rmiObj.sendReturnObj(retObj);");
1697 if (isCallbackMethod) { // Catch exception if this is callback
1699 println(" catch(Exception ex) {");
1700 println("ex.printStackTrace();");
1701 println("throw new Error(\"Exception from callback object instantiation!\");");
1708 * HELPER: writeMethodHelperStructJavaSkeleton() writes the struct in skeleton
1710 private void writeMethodHelperStructJavaSkeleton(InterfaceDecl intDecl, List<String> methParams,
1711 List<String> methPrmTypes, String method, Set<String> callbackClasses) {
1713 // Generate array of parameter objects
1714 boolean isCallbackMethod = false;
1715 String callbackType = null;
1716 print("int paramLen = ");
1717 writeLengthStructParamClassSkeleton(methParams, methPrmTypes, method, intDecl);
1719 println("Class<?>[] paramCls = new Class<?>[paramLen];");
1720 println("Class<?>[] paramClsGen = new Class<?>[paramLen];");
1721 // Iterate again over the parameters
1722 for (int i = 0; i < methParams.size(); i++) {
1723 String paramType = methPrmTypes.get(i);
1724 String param = methParams.get(i);
1725 String simpleType = getGenericType(paramType);
1726 if (isStructClass(simpleType)) {
1727 writeStructMembersJavaSkeleton(simpleType, paramType, param, method, intDecl, i);
1729 String prmType = returnGenericCallbackType(methPrmTypes.get(i));
1730 if (callbackClasses.contains(prmType)) {
1731 isCallbackMethod = true;
1732 callbackType = prmType;
1733 println("paramCls[pos] = int.class;");
1734 println("paramClsGen[pos++] = null;");
1735 } else { // Generate normal classes if it's not a callback object
1736 String paramTypeOth = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
1737 println("paramCls[pos] = " + getSimpleType(getEnumType(paramTypeOth)) + ".class;");
1738 print("paramClsGen[pos++] = ");
1739 String prmTypeOth = methPrmTypes.get(i);
1740 if (getParamCategory(prmTypeOth) == ParamCategory.NONPRIMITIVES)
1741 println(getTypeOfGeneric(prmType)[0] + ".class;");
1747 println("Object[] paramObj = rmiObj.getMethodParams(paramCls, paramClsGen);");
1748 writeStructMembersInitJavaSkeleton(intDecl, methParams, methPrmTypes, method);
1749 // Write the return value part
1750 writeMethodHelperReturnJavaSkeleton(intDecl, methParams, methPrmTypes, method, isCallbackMethod, callbackType, true);
1755 * HELPER: writeStdMethodHelperBodyJavaSkeleton() writes the standard method body helper in the skeleton class
1757 private void writeStdMethodHelperBodyJavaSkeleton(InterfaceDecl intDecl, List<String> methParams,
1758 List<String> methPrmTypes, String method, Set<String> callbackClasses) {
1760 // Generate array of parameter objects
1761 boolean isCallbackMethod = false;
1762 String callbackType = null;
1763 print("Object[] paramObj = rmiObj.getMethodParams(new Class<?>[] { ");
1764 for (int i = 0; i < methParams.size(); i++) {
1766 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
1767 if (callbackClasses.contains(paramType)) {
1768 isCallbackMethod = true;
1769 callbackType = paramType;
1771 } else { // Generate normal classes if it's not a callback object
1772 String prmType = checkAndGetArray(methPrmTypes.get(i), methParams.get(i));
1773 print(getSimpleType(getEnumType(prmType)) + ".class");
1775 if (i != methParams.size() - 1)
1779 // Generate generic class if it's a generic type.. null otherwise
1780 print("new Class<?>[] { ");
1781 for (int i = 0; i < methParams.size(); i++) {
1782 String prmType = methPrmTypes.get(i);
1783 if ((getParamCategory(prmType) == ParamCategory.NONPRIMITIVES) &&
1784 !isEnumClass(getGenericType(prmType)))
1785 print(getGenericType(prmType) + ".class");
1788 if (i != methParams.size() - 1)
1792 // Write the return value part
1793 writeMethodHelperReturnJavaSkeleton(intDecl, methParams, methPrmTypes, method, isCallbackMethod, callbackType, false);
1798 * HELPER: writeMethodHelperJavaSkeleton() writes the method helper of the skeleton class
1800 private void writeMethodHelperJavaSkeleton(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
1802 // Use this set to handle two same methodIds
1803 Set<String> uniqueMethodIds = new HashSet<String>();
1804 for (String method : methods) {
1806 List<String> methParams = intDecl.getMethodParams(method);
1807 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1808 if (isStructPresent(methParams, methPrmTypes)) { // Treat struct differently
1809 String methodId = intDecl.getMethodId(method);
1810 print("public void ___");
1811 String helperMethod = methodId;
1812 if (uniqueMethodIds.contains(methodId))
1813 helperMethod = helperMethod + intDecl.getMethodNumId(method);
1815 uniqueMethodIds.add(methodId);
1816 String retType = intDecl.getMethodType(method);
1817 print(helperMethod + "(");
1818 boolean begin = true;
1819 for (int i = 0; i < methParams.size(); i++) { // Print size variables
1820 String paramType = methPrmTypes.get(i);
1821 String param = methParams.get(i);
1822 String simpleType = getSimpleType(paramType);
1823 if (isStructClass(simpleType)) {
1824 if (!begin) { // Generate comma for not the beginning variable
1825 print(", "); begin = false;
1827 int methodNumId = intDecl.getMethodNumId(method);
1828 print("int struct" + methodNumId + "Size" + i);
1831 // Check if this is "void"
1832 if (retType.equals("void"))
1835 println(") throws IOException {");
1836 writeMethodHelperStructJavaSkeleton(intDecl, methParams, methPrmTypes, method, callbackClasses);
1839 String methodId = intDecl.getMethodId(method);
1840 print("public void ___");
1841 String helperMethod = methodId;
1842 if (uniqueMethodIds.contains(methodId))
1843 helperMethod = helperMethod + intDecl.getMethodNumId(method);
1845 uniqueMethodIds.add(methodId);
1846 // Check if this is "void"
1847 String retType = intDecl.getMethodType(method);
1848 if (retType.equals("void"))
1849 println(helperMethod + "() {");
1851 println(helperMethod + "() throws IOException {");
1852 // Now, write the helper body of skeleton!
1853 writeStdMethodHelperBodyJavaSkeleton(intDecl, methParams, methPrmTypes, method, callbackClasses);
1857 // Write method helper for structs
1858 writeMethodHelperStructSetupJavaSkeleton(methods, intDecl);
1863 * HELPER: writeMethodHelperStructSetupJavaSkeleton() writes the method helper of struct setup in skeleton class
1865 private void writeMethodHelperStructSetupJavaSkeleton(Collection<String> methods,
1866 InterfaceDecl intDecl) {
1868 // Use this set to handle two same methodIds
1869 for (String method : methods) {
1871 List<String> methParams = intDecl.getMethodParams(method);
1872 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1873 // Check for params with structs
1874 for (int i = 0; i < methParams.size(); i++) {
1875 String paramType = methPrmTypes.get(i);
1876 String param = methParams.get(i);
1877 String simpleType = getSimpleType(paramType);
1878 if (isStructClass(simpleType)) {
1879 int methodNumId = intDecl.getMethodNumId(method);
1880 print("public int ___");
1881 String helperMethod = methodNumId + "struct" + i;
1882 println(helperMethod + "() {");
1883 // Now, write the helper body of skeleton!
1884 println("Object[] paramObj = rmiObj.getMethodParams(new Class<?>[] { int.class }, new Class<?>[] { null });");
1885 println("return (int) paramObj[0];");
1894 * HELPER: writeMethodHelperStructSetupJavaCallbackSkeleton() writes the method helper of struct setup in callback skeleton class
1896 private void writeMethodHelperStructSetupJavaCallbackSkeleton(Collection<String> methods,
1897 InterfaceDecl intDecl) {
1899 // Use this set to handle two same methodIds
1900 for (String method : methods) {
1902 List<String> methParams = intDecl.getMethodParams(method);
1903 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1904 // Check for params with structs
1905 for (int i = 0; i < methParams.size(); i++) {
1906 String paramType = methPrmTypes.get(i);
1907 String param = methParams.get(i);
1908 String simpleType = getSimpleType(paramType);
1909 if (isStructClass(simpleType)) {
1910 int methodNumId = intDecl.getMethodNumId(method);
1911 print("public int ___");
1912 String helperMethod = methodNumId + "struct" + i;
1913 println(helperMethod + "(IoTRMIObject rmiObj) {");
1914 // Now, write the helper body of skeleton!
1915 println("Object[] paramObj = rmiObj.getMethodParams(new Class<?>[] { int.class }, new Class<?>[] { null });");
1916 println("return (int) paramObj[0];");
1925 * HELPER: writeCountVarStructSkeleton() writes counter variable of struct for skeleton
1927 private void writeCountVarStructSkeleton(Collection<String> methods, InterfaceDecl intDecl) {
1929 // Use this set to handle two same methodIds
1930 for (String method : methods) {
1932 List<String> methParams = intDecl.getMethodParams(method);
1933 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1934 // Check for params with structs
1935 for (int i = 0; i < methParams.size(); i++) {
1936 String paramType = methPrmTypes.get(i);
1937 String param = methParams.get(i);
1938 String simpleType = getSimpleType(paramType);
1939 if (isStructClass(simpleType)) {
1940 int methodNumId = intDecl.getMethodNumId(method);
1941 println("int struct" + methodNumId + "Size" + i + " = 0;");
1949 * HELPER: writeInputCountVarStructSkeleton() writes input counter variable of struct for skeleton
1951 private boolean writeInputCountVarStructSkeleton(String method, InterfaceDecl intDecl) {
1953 List<String> methParams = intDecl.getMethodParams(method);
1954 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1955 boolean structExist = false;
1956 // Check for params with structs
1957 for (int i = 0; i < methParams.size(); i++) {
1958 String paramType = methPrmTypes.get(i);
1959 String param = methParams.get(i);
1960 String simpleType = getSimpleType(paramType);
1961 boolean begin = true;
1962 if (isStructClass(simpleType)) {
1965 print(", "); begin = false;
1967 int methodNumId = intDecl.getMethodNumId(method);
1968 print("struct" + methodNumId + "Size" + i);
1976 * HELPER: writeMethodCallStructSkeleton() writes method call for wait invoke in skeleton
1978 private void writeMethodCallStructSkeleton(Collection<String> methods, InterfaceDecl intDecl) {
1980 // Use this set to handle two same methodIds
1981 for (String method : methods) {
1983 List<String> methParams = intDecl.getMethodParams(method);
1984 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
1985 // Check for params with structs
1986 for (int i = 0; i < methParams.size(); i++) {
1987 String paramType = methPrmTypes.get(i);
1988 String param = methParams.get(i);
1989 String simpleType = getSimpleType(paramType);
1990 if (isStructClass(simpleType)) {
1991 int methodNumId = intDecl.getMethodNumId(method);
1993 String helperMethod = methodNumId + "struct" + i;
1994 String tempVar = "struct" + methodNumId + "Size" + i;
1995 print(intDecl.getHelperMethodNumId(helperMethod) + ": ");
1996 print(tempVar + " = ___");
1997 println(helperMethod + "(); break;");
2005 * HELPER: writeMethodCallStructCallbackSkeleton() writes method call for wait invoke in skeleton
2007 private void writeMethodCallStructCallbackSkeleton(Collection<String> methods, InterfaceDecl intDecl) {
2009 // Use this set to handle two same methodIds
2010 for (String method : methods) {
2012 List<String> methParams = intDecl.getMethodParams(method);
2013 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2014 // Check for params with structs
2015 for (int i = 0; i < methParams.size(); i++) {
2016 String paramType = methPrmTypes.get(i);
2017 String param = methParams.get(i);
2018 String simpleType = getSimpleType(paramType);
2019 if (isStructClass(simpleType)) {
2020 int methodNumId = intDecl.getMethodNumId(method);
2022 String helperMethod = methodNumId + "struct" + i;
2023 String tempVar = "struct" + methodNumId + "Size" + i;
2024 print(intDecl.getHelperMethodNumId(helperMethod) + ": ");
2025 print(tempVar + " = ___");
2026 println(helperMethod + "(rmiObj); break;");
2034 * HELPER: writeJavaMethodPermission() writes permission checks in skeleton
2036 private void writeJavaMethodPermission(String intface) {
2038 // Get all the different stubs
2039 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
2040 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
2041 String newIntface = intMeth.getKey();
2042 int newObjectId = getNewIntfaceObjectId(newIntface);
2043 println("if (_objectId == object" + newObjectId + "Id) {");
2044 println("if (!set" + newObjectId + "Allowed.contains(methodId)) {");
2045 println("throw new Error(\"Object with object Id: \" + _objectId + \" is not allowed to access method: \" + methodId);");
2049 println("throw new Error(\"Object Id: \" + _objectId + \" not recognized!\");");
2056 * HELPER: writeJavaWaitRequestInvokeMethod() writes the main loop of the skeleton class
2058 private void writeJavaWaitRequestInvokeMethod(Collection<String> methods, InterfaceDecl intDecl, boolean callbackExist, String intface) {
2060 // Use this set to handle two same methodIds
2061 Set<String> uniqueMethodIds = new HashSet<String>();
2062 println("private void ___waitRequestInvokeMethod() throws IOException {");
2063 // Write variables here if we have callbacks or enums or structs
2064 writeCountVarStructSkeleton(methods, intDecl);
2065 println("while (true) {");
2066 println("rmiObj.getMethodBytes();");
2067 println("int _objectId = rmiObj.getObjectId();");
2068 println("int methodId = rmiObj.getMethodId();");
2069 // Generate permission check
2070 writeJavaMethodPermission(intface);
2071 println("switch (methodId) {");
2072 // Print methods and method Ids
2073 for (String method : methods) {
2074 String methodId = intDecl.getMethodId(method);
2075 int methodNumId = intDecl.getMethodNumId(method);
2076 print("case " + methodNumId + ": ___");
2077 String helperMethod = methodId;
2078 if (uniqueMethodIds.contains(methodId))
2079 helperMethod = helperMethod + methodNumId;
2081 uniqueMethodIds.add(methodId);
2082 print(helperMethod + "(");
2083 writeInputCountVarStructSkeleton(method, intDecl);
2084 println("); break;");
2086 String method = "___initCallBack()";
2087 // Print case -9999 (callback handler) if callback exists
2088 if (callbackExist) {
2089 int methodId = intDecl.getHelperMethodNumId(method);
2090 println("case " + methodId + ": ___regCB(); break;");
2092 writeMethodCallStructSkeleton(methods, intDecl);
2093 println("default: ");
2094 println("throw new Error(\"Method Id \" + methodId + \" not recognized!\");");
2102 * generateJavaSkeletonClass() generate skeletons based on the methods list in Java
2104 public void generateJavaSkeletonClass() throws IOException {
2106 // Create a new directory
2107 String path = createDirectories(dir, subdir);
2108 for (String intface : mapIntfacePTH.keySet()) {
2109 // Open a new file to write into
2110 String newSkelClass = intface + "_Skeleton";
2111 FileWriter fw = new FileWriter(path + "/" + newSkelClass + ".java");
2112 pw = new PrintWriter(new BufferedWriter(fw));
2113 // Pass in set of methods and get import classes
2114 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2115 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
2116 List<String> methods = intDecl.getMethods();
2117 Set<String> importClasses = getImportClasses(methods, intDecl);
2118 List<String> stdImportClasses = getStandardJavaImportClasses();
2119 List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
2120 printImportStatements(allImportClasses);
2121 // Find out if there are callback objects
2122 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
2123 boolean callbackExist = !callbackClasses.isEmpty();
2124 // Write class header
2126 println("public class " + newSkelClass + " implements " + intface + " {\n");
2128 writePropertiesJavaSkeleton(intface, callbackExist, intDecl);
2129 // Write constructor
2130 writeConstructorJavaSkeleton(newSkelClass, intface, intDecl, methods, callbackExist);
2132 writeMethodJavaSkeleton(methods, intDecl, callbackClasses, false);
2133 // Write method helper
2134 writeMethodHelperJavaSkeleton(methods, intDecl, callbackClasses);
2135 // Write waitRequestInvokeMethod() - main loop
2136 writeJavaWaitRequestInvokeMethod(methods, intDecl, callbackExist, intface);
2139 System.out.println("IoTCompiler: Generated skeleton class " + newSkelClass + ".java...");
2145 * HELPER: writePropertiesJavaCallbackSkeleton() writes the properties of the callback skeleton class
2147 private void writePropertiesJavaCallbackSkeleton(String intface, boolean callbackExist) {
2149 println("private " + intface + " mainObj;");
2150 // For callback skeletons, this is its own object Id
2151 println("private static int objectId = 0;");
2153 if (callbackExist) {
2154 println("private static int objIdCnt = 0;");
2155 println("private IoTRMICall rmiCall;");
2162 * HELPER: writeConstructorJavaCallbackSkeleton() writes the constructor of the skeleton class
2164 private void writeConstructorJavaCallbackSkeleton(String newSkelClass, String intface, InterfaceDecl intDecl, Collection<String> methods) {
2166 println("public " + newSkelClass + "(" + intface + " _mainObj, int _objectId) throws Exception {");
2167 println("mainObj = _mainObj;");
2168 println("objectId = _objectId;");
2169 writeStructPermissionJavaSkeleton(methods, intDecl, intface);
2175 * HELPER: writeMethodHelperJavaCallbackSkeleton() writes the method helper of the callback skeleton class
2177 private void writeMethodHelperJavaCallbackSkeleton(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
2179 // Use this set to handle two same methodIds
2180 Set<String> uniqueMethodIds = new HashSet<String>();
2181 for (String method : methods) {
2183 List<String> methParams = intDecl.getMethodParams(method);
2184 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2185 if (isStructPresent(methParams, methPrmTypes)) { // Treat struct differently
2186 String methodId = intDecl.getMethodId(method);
2187 print("public void ___");
2188 String helperMethod = methodId;
2189 if (uniqueMethodIds.contains(methodId))
2190 helperMethod = helperMethod + intDecl.getMethodNumId(method);
2192 uniqueMethodIds.add(methodId);
2193 String retType = intDecl.getMethodType(method);
2194 print(helperMethod + "(");
2195 boolean begin = true;
2196 for (int i = 0; i < methParams.size(); i++) { // Print size variables
2197 String paramType = methPrmTypes.get(i);
2198 String param = methParams.get(i);
2199 String simpleType = getSimpleType(paramType);
2200 if (isStructClass(simpleType)) {
2201 if (!begin) { // Generate comma for not the beginning variable
2202 print(", "); begin = false;
2204 int methodNumId = intDecl.getMethodNumId(method);
2205 print("int struct" + methodNumId + "Size" + i);
2208 // Check if this is "void"
2209 if (retType.equals("void"))
2210 println(", IoTRMIObject rmiObj) {");
2212 println(", IoTRMIObject rmiObj) throws IOException {");
2213 writeMethodHelperStructJavaSkeleton(intDecl, methParams, methPrmTypes, method, callbackClasses);
2216 String methodId = intDecl.getMethodId(method);
2217 print("public void ___");
2218 String helperMethod = methodId;
2219 if (uniqueMethodIds.contains(methodId))
2220 helperMethod = helperMethod + intDecl.getMethodNumId(method);
2222 uniqueMethodIds.add(methodId);
2223 // Check if this is "void"
2224 String retType = intDecl.getMethodType(method);
2225 if (retType.equals("void"))
2226 println(helperMethod + "(IoTRMIObject rmiObj) {");
2228 println(helperMethod + "(IoTRMIObject rmiObj) throws IOException {");
2229 // Now, write the helper body of skeleton!
2230 writeStdMethodHelperBodyJavaSkeleton(intDecl, methParams, methPrmTypes, method, callbackClasses);
2234 // Write method helper for structs
2235 writeMethodHelperStructSetupJavaCallbackSkeleton(methods, intDecl);
2240 * HELPER: writeJavaCallbackWaitRequestInvokeMethod() writes the request invoke method of the callback skeleton class
2242 private void writeJavaCallbackWaitRequestInvokeMethod(Collection<String> methods, InterfaceDecl intDecl, boolean callbackExist) {
2244 // Use this set to handle two same methodIds
2245 Set<String> uniqueMethodIds = new HashSet<String>();
2246 println("public void invokeMethod(IoTRMIObject rmiObj) throws IOException {");
2247 // Write variables here if we have callbacks or enums or structs
2248 writeCountVarStructSkeleton(methods, intDecl);
2249 // Write variables here if we have callbacks or enums or structs
2250 println("int methodId = rmiObj.getMethodId();");
2251 // TODO: code the permission check here!
2252 println("switch (methodId) {");
2253 // Print methods and method Ids
2254 for (String method : methods) {
2255 String methodId = intDecl.getMethodId(method);
2256 int methodNumId = intDecl.getMethodNumId(method);
2257 print("case " + methodNumId + ": ___");
2258 String helperMethod = methodId;
2259 if (uniqueMethodIds.contains(methodId))
2260 helperMethod = helperMethod + methodNumId;
2262 uniqueMethodIds.add(methodId);
2263 print(helperMethod + "(");
2264 if (writeInputCountVarStructSkeleton(method, intDecl))
2265 println(", rmiObj); break;");
2267 println("rmiObj); break;");
2269 String method = "___initCallBack()";
2270 // Print case -9999 (callback handler) if callback exists
2271 if (callbackExist) {
2272 int methodId = intDecl.getHelperMethodNumId(method);
2273 println("case " + methodId + ": ___regCB(rmiObj); break;");
2275 writeMethodCallStructCallbackSkeleton(methods, intDecl);
2276 println("default: ");
2277 println("throw new Error(\"Method Id \" + methodId + \" not recognized!\");");
2284 * generateJavaCallbackSkeletonClass() generate callback skeletons based on the methods list in Java
2286 public void generateJavaCallbackSkeletonClass() throws IOException {
2288 // Create a new directory
2289 String path = createDirectories(dir, subdir);
2290 for (String intface : mapIntfacePTH.keySet()) {
2291 // Open a new file to write into
2292 String newSkelClass = intface + "_CallbackSkeleton";
2293 FileWriter fw = new FileWriter(path + "/" + newSkelClass + ".java");
2294 pw = new PrintWriter(new BufferedWriter(fw));
2295 // Pass in set of methods and get import classes
2296 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2297 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
2298 List<String> methods = intDecl.getMethods();
2299 Set<String> importClasses = getImportClasses(methods, intDecl);
2300 List<String> stdImportClasses = getStandardJavaImportClasses();
2301 List<String> allImportClasses = getAllLibClasses(stdImportClasses, importClasses);
2302 printImportStatements(allImportClasses);
2303 // Find out if there are callback objects
2304 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
2305 boolean callbackExist = !callbackClasses.isEmpty();
2306 // Write class header
2308 println("public class " + newSkelClass + " implements " + intface + " {\n");
2310 writePropertiesJavaCallbackSkeleton(intface, callbackExist);
2311 // Write constructor
2312 writeConstructorJavaCallbackSkeleton(newSkelClass, intface, intDecl, methods);
2314 writeMethodJavaSkeleton(methods, intDecl, callbackClasses, true);
2315 // Write method helper
2316 writeMethodHelperJavaCallbackSkeleton(methods, intDecl, callbackClasses);
2317 // Write waitRequestInvokeMethod() - main loop
2318 writeJavaCallbackWaitRequestInvokeMethod(methods, intDecl, callbackExist);
2321 System.out.println("IoTCompiler: Generated callback skeleton class " + newSkelClass + ".java...");
2327 * HELPER: writeMethodCplusLocalInterface() writes the method of the local interface
2329 private void writeMethodCplusLocalInterface(Collection<String> methods, InterfaceDecl intDecl) {
2331 for (String method : methods) {
2333 List<String> methParams = intDecl.getMethodParams(method);
2334 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2335 print("virtual " + checkAndGetCplusType(intDecl.getMethodType(method)) + " " +
2336 intDecl.getMethodId(method) + "(");
2337 for (int i = 0; i < methParams.size(); i++) {
2338 // Check for params with driver class types and exchange it
2339 // with its remote interface
2340 String paramType = checkAndGetParamClass(methPrmTypes.get(i));
2341 paramType = checkAndGetCplusType(paramType);
2342 // Check for arrays - translate into vector in C++
2343 String paramComplete = checkAndGetCplusArray(paramType, methParams.get(i));
2344 print(paramComplete);
2345 // Check if this is the last element (don't print a comma)
2346 if (i != methParams.size() - 1) {
2356 * HELPER: writeMethodCplusInterface() writes the method of the interface
2358 private void writeMethodCplusInterface(Collection<String> methods, InterfaceDecl intDecl) {
2360 for (String method : methods) {
2362 List<String> methParams = intDecl.getMethodParams(method);
2363 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2364 print("virtual " + checkAndGetCplusType(intDecl.getMethodType(method)) + " " +
2365 intDecl.getMethodId(method) + "(");
2366 for (int i = 0; i < methParams.size(); i++) {
2367 // Check for params with driver class types and exchange it
2368 // with its remote interface
2369 String paramType = methPrmTypes.get(i);
2370 paramType = checkAndGetCplusType(paramType);
2371 // Check for arrays - translate into vector in C++
2372 String paramComplete = checkAndGetCplusArray(paramType, methParams.get(i));
2373 print(paramComplete);
2374 // Check if this is the last element (don't print a comma)
2375 if (i != methParams.size() - 1) {
2385 * HELPER: generateEnumCplus() writes the enumeration declaration
2387 public void generateEnumCplus() throws IOException {
2389 // Create a new directory
2390 createDirectory(dir);
2391 for (String intface : mapIntfacePTH.keySet()) {
2392 // Get the right StructDecl
2393 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2394 EnumDecl enumDecl = (EnumDecl) decHandler.getEnumDecl(intface);
2395 Set<String> enumTypes = enumDecl.getEnumDeclarations();
2396 // Iterate over enum declarations
2397 for (String enType : enumTypes) {
2398 // Open a new file to write into
2399 FileWriter fw = new FileWriter(dir + "/" + enType + ".hpp");
2400 pw = new PrintWriter(new BufferedWriter(fw));
2401 // Write file headers
2402 println("#ifndef _" + enType.toUpperCase() + "_HPP__");
2403 println("#define _" + enType.toUpperCase() + "_HPP__");
2404 println("enum " + enType + " {");
2405 List<String> enumMembers = enumDecl.getMembers(enType);
2406 for (int i = 0; i < enumMembers.size(); i++) {
2408 String member = enumMembers.get(i);
2410 // Check if this is the last element (don't print a comma)
2411 if (i != enumMembers.size() - 1)
2419 System.out.println("IoTCompiler: Generated enum " + enType + ".hpp...");
2426 * HELPER: generateStructCplus() writes the struct declaration
2428 public void generateStructCplus() throws IOException {
2430 // Create a new directory
2431 createDirectory(dir);
2432 for (String intface : mapIntfacePTH.keySet()) {
2433 // Get the right StructDecl
2434 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2435 StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
2436 List<String> structTypes = structDecl.getStructTypes();
2437 // Iterate over enum declarations
2438 for (String stType : structTypes) {
2439 // Open a new file to write into
2440 FileWriter fw = new FileWriter(dir + "/" + stType + ".hpp");
2441 pw = new PrintWriter(new BufferedWriter(fw));
2442 // Write file headers
2443 println("#ifndef _" + stType.toUpperCase() + "_HPP__");
2444 println("#define _" + stType.toUpperCase() + "_HPP__");
2445 println("struct " + stType + " {");
2446 List<String> structMemberTypes = structDecl.getMemberTypes(stType);
2447 List<String> structMembers = structDecl.getMembers(stType);
2448 for (int i = 0; i < structMembers.size(); i++) {
2450 String memberType = structMemberTypes.get(i);
2451 String member = structMembers.get(i);
2452 String structTypeC = checkAndGetCplusType(memberType);
2453 String structComplete = checkAndGetCplusArray(structTypeC, member);
2454 println(structComplete + ";");
2459 System.out.println("IoTCompiler: Generated struct " + stType + ".hpp...");
2466 * generateCplusLocalInterfaces() writes the local interfaces and provides type-checking.
2468 * It needs to rewrite and exchange USERDEFINED types in input parameters of stub
2469 * and original interfaces, e.g. exchange Camera and CameraWithVideoAndRecording.
2470 * The local interface has to be the input parameter for the stub and the stub
2471 * interface has to be the input parameter for the local class.
2473 public void generateCplusLocalInterfaces() throws IOException {
2475 // Create a new directory
2476 createDirectory(dir);
2477 for (String intface : mapIntfacePTH.keySet()) {
2478 // Open a new file to write into
2479 FileWriter fw = new FileWriter(dir + "/" + intface + ".hpp");
2480 pw = new PrintWriter(new BufferedWriter(fw));
2481 // Write file headers
2482 println("#ifndef _" + intface.toUpperCase() + "_HPP__");
2483 println("#define _" + intface.toUpperCase() + "_HPP__");
2484 println("#include <iostream>");
2485 // Pass in set of methods and get include classes
2486 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2487 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
2488 List<String> methods = intDecl.getMethods();
2489 Set<String> includeClasses = getIncludeClasses(methods, intDecl, intface, true);
2490 printIncludeStatements(includeClasses); println("");
2491 println("using namespace std;\n");
2492 //writeStructCplus(structDecl);
2493 println("class " + intface); println("{");
2496 writeMethodCplusLocalInterface(methods, intDecl);
2500 System.out.println("IoTCompiler: Generated local interface " + intface + ".hpp...");
2506 * generateCPlusInterfaces() generate stub interfaces based on the methods list in C++
2508 * For C++ we use virtual classe as interface
2510 public void generateCPlusInterfaces() throws IOException {
2512 // Create a new directory
2513 String path = createDirectories(dir, subdir);
2514 for (String intface : mapIntfacePTH.keySet()) {
2516 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
2517 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
2519 // Open a new file to write into
2520 String newIntface = intMeth.getKey();
2521 FileWriter fw = new FileWriter(path + "/" + newIntface + ".hpp");
2522 pw = new PrintWriter(new BufferedWriter(fw));
2523 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
2524 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
2525 // Write file headers
2526 println("#ifndef _" + newIntface.toUpperCase() + "_HPP__");
2527 println("#define _" + newIntface.toUpperCase() + "_HPP__");
2528 println("#include <iostream>");
2529 // Pass in set of methods and get import classes
2530 Set<String> includeClasses = getIncludeClasses(intMeth.getValue(), intDecl, intface, false);
2531 List<String> stdIncludeClasses = getStandardCplusIncludeClasses();
2532 List<String> allIncludeClasses = getAllLibClasses(stdIncludeClasses, includeClasses);
2533 printIncludeStatements(allIncludeClasses); println("");
2534 println("using namespace std;\n");
2535 println("class " + newIntface);
2539 writeMethodCplusInterface(intMeth.getValue(), intDecl);
2543 System.out.println("IoTCompiler: Generated interface " + newIntface + ".hpp...");
2550 * HELPER: writeMethodCplusStub() writes the methods of the stub
2552 private void writeMethodCplusStub(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
2554 for (String method : methods) {
2556 List<String> methParams = intDecl.getMethodParams(method);
2557 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
2558 print(checkAndGetCplusType(intDecl.getMethodType(method)) + " " +
2559 intDecl.getMethodId(method) + "(");
2560 boolean isCallbackMethod = false;
2561 String callbackType = null;
2562 for (int i = 0; i < methParams.size(); i++) {
2564 String paramType = methPrmTypes.get(i);
2565 // Check if this has callback object
2566 if (callbackClasses.contains(paramType)) {
2567 isCallbackMethod = true;
2568 callbackType = paramType;
2569 // Even if there're 2 callback arguments, we expect them to be of the same interface
2571 String methPrmType = checkAndGetCplusType(methPrmTypes.get(i));
2572 String methParamComplete = checkAndGetCplusArray(methPrmType, methParams.get(i));
2573 print(methParamComplete);
2574 // Check if this is the last element (don't print a comma)
2575 if (i != methParams.size() - 1) {
2580 if (isCallbackMethod)
2581 writeCallbackMethodBodyCplusStub(intDecl, methParams, methPrmTypes, method, callbackType);
2583 writeStdMethodBodyCplusStub(intDecl, methParams, methPrmTypes, method);
2585 // Write the init callback helper method
2586 if (isCallbackMethod) {
2587 writeInitCallbackCplusStub(callbackType, intDecl);
2588 writeInitCallbackSendInfoCplusStub(intDecl);
2595 * HELPER: writeCallbackMethodBodyCplusStub() writes the callback method of the stub class
2597 private void writeCallbackMethodBodyCplusStub(InterfaceDecl intDecl, List<String> methParams,
2598 List<String> methPrmTypes, String method, String callbackType) {
2600 // Check if this is single object, array, or list of objects
2601 boolean isArrayOrList = false;
2602 String callbackParam = null;
2603 for (int i = 0; i < methParams.size(); i++) {
2605 String paramType = methPrmTypes.get(i);
2606 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
2607 String param = methParams.get(i);
2608 if (isArrayOrList(paramType, param)) { // Generate loop
2609 println("for (" + paramType + "* cb : " + getSimpleIdentifier(param) + ") {");
2610 println(callbackType + "_CallbackSkeleton* skel = new " + callbackType + "_CallbackSkeleton(cb, objIdCnt++);");
2611 isArrayOrList = true;
2612 callbackParam = getSimpleIdentifier(param);
2614 println(callbackType + "_CallbackSkeleton* skel = new " + callbackType + "_CallbackSkeleton(" +
2615 getSimpleIdentifier(param) + ", objIdCnt++);");
2616 println("vecCallbackObj.push_back(skel);");
2617 if (isArrayOrList(paramType, param))
2621 println("int numParam = " + methParams.size() + ";");
2622 println("int methodId = " + intDecl.getMethodNumId(method) + ";");
2623 String retType = intDecl.getMethodType(method);
2624 //String retTypeC = checkAndGetCplusType(retType);
2625 //println("string retType = \"" + checkAndGetCplusArrayType(getStructType(getEnumType(retTypeC))) + "\";");
2626 println("string retType = \"" + checkAndGetCplusRetClsType(getStructType(getEnumType(retType))) + "\";");
2627 // Generate array of parameter types
2628 print("string paramCls[] = { ");
2629 for (int i = 0; i < methParams.size(); i++) {
2630 String paramType = methPrmTypes.get(i);
2631 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
2633 } else { // Generate normal classes if it's not a callback object
2634 String paramTypeC = checkAndGetCplusArgClsType(methPrmTypes.get(i), methParams.get(i));
2635 print("\"" + paramTypeC + "\"");
2637 if (i != methParams.size() - 1) // Check if this is the last element
2641 print("int ___paramCB = ");
2643 println(callbackParam + ".size();");
2646 // Generate array of parameter objects
2647 print("void* paramObj[] = { ");
2648 for (int i = 0; i < methParams.size(); i++) {
2649 String paramType = methPrmTypes.get(i);
2650 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
2651 print("&___paramCB");
2653 print(getSimpleIdentifier(methParams.get(i)));
2654 if (i != methParams.size() - 1)
2658 // Check if this is "void"
2659 if (retType.equals("void")) {
2660 println("void* retObj = NULL;");
2661 println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
2662 } else { // We do have a return value
2663 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
2664 println(checkAndGetCplusType(retType) + " retVal;");
2666 println(checkAndGetCplusType(retType) + " retVal = " + generateCplusInitializer(retType) + ";");
2667 println("void* retObj = &retVal;");
2668 println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
2669 println("return retVal;");
2675 * HELPER: checkAndWriteEnumTypeCplusStub() writes the enum type (convert from enum to int)
2677 private void checkAndWriteEnumTypeCplusStub(List<String> methParams, List<String> methPrmTypes) {
2679 // Iterate and find enum declarations
2680 for (int i = 0; i < methParams.size(); i++) {
2681 String paramType = methPrmTypes.get(i);
2682 String param = methParams.get(i);
2683 if (isEnumClass(getGenericType(paramType))) {
2684 // Check if this is enum type
2685 if (isArrayOrList(paramType, param)) { // An array or vector
2686 println("int len" + i + " = " + getSimpleIdentifier(param) + ".size();");
2687 println("vector<int> paramEnum" + i + "(len" + i + ");");
2688 println("for (int i = 0; i < len" + i + "; i++) {");
2689 println("paramEnum" + i + "[i] = (int) " + getSimpleIdentifier(param) + "[i];");
2691 } else { // Just one element
2692 println("vector<int> paramEnum" + i + "(1);");
2693 println("paramEnum" + i + "[0] = (int) " + param + ";");
2701 * HELPER: checkAndWriteEnumRetTypeCplusStub() writes the enum return type (convert from enum to int)
2703 private void checkAndWriteEnumRetTypeCplusStub(String retType) {
2705 // Strips off array "[]" for return type
2706 String pureType = getSimpleArrayType(getGenericType(retType));
2707 // Take the inner type of generic
2708 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
2709 pureType = getGenericType(retType);
2710 if (isEnumClass(pureType)) {
2711 // Check if this is enum type
2712 println("vector<int> retEnumInt;");
2713 println("void* retObj = &retEnumInt;");
2714 println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
2715 if (isArrayOrList(retType, retType)) { // An array or vector
2716 println("int retLen = retEnumInt.size();");
2717 println("vector<" + pureType + "> retVal(retLen);");
2718 println("for (int i = 0; i < retLen; i++) {");
2719 println("retVal[i] = (" + pureType + ") retEnumInt[i];");
2721 } else { // Just one element
2722 println(pureType + " retVal = (" + pureType + ") retEnumInt[0];");
2724 println("return retVal;");
2730 * HELPER: checkAndWriteStructSetupCplusStub() writes the struct type setup
2732 private void checkAndWriteStructSetupCplusStub(List<String> methParams, List<String> methPrmTypes,
2733 InterfaceDecl intDecl, String method) {
2735 // Iterate and find struct declarations
2736 for (int i = 0; i < methParams.size(); i++) {
2737 String paramType = methPrmTypes.get(i);
2738 String param = methParams.get(i);
2739 String simpleType = getSimpleType(paramType);
2740 if (isStructClass(simpleType)) {
2741 // Check if this is enum type
2742 println("int numParam" + i + " = 1;");
2743 int methodNumId = intDecl.getMethodNumId(method);
2744 String helperMethod = methodNumId + "struct" + i;
2745 println("int methodIdStruct" + i + " = " + intDecl.getHelperMethodNumId(helperMethod) + ";");
2746 println("string retTypeStruct" + i + " = \"void\";");
2747 println("string paramClsStruct" + i + "[] = { \"int\" };");
2748 print("int structLen" + i + " = ");
2749 if (isArrayOrList(param, paramType)) { // An array
2750 println(getSimpleArrayType(param) + ".size();");
2751 } else { // Just one element
2754 println("void* paramObjStruct" + i + "[] = { &structLen" + i + " };");
2755 println("void* retStructLen" + i + " = NULL;");
2756 println("rmiCall->remoteCall(objectId, methodIdStruct" + i +
2757 ", retTypeStruct" + i + ", paramClsStruct" + i + ", paramObjStruct" + i +
2758 ", numParam" + i + ", retStructLen" + i + ");\n");
2765 * HELPER: writeLengthStructParamClassCplusStub() writes lengths of params
2767 private void writeLengthStructParamClassCplusStub(List<String> methParams, List<String> methPrmTypes) {
2769 // Iterate and find struct declarations - count number of params
2770 for (int i = 0; i < methParams.size(); i++) {
2771 String paramType = methPrmTypes.get(i);
2772 String param = methParams.get(i);
2773 String simpleType = getGenericType(paramType);
2774 if (isStructClass(simpleType)) {
2775 int members = getNumOfMembers(simpleType);
2776 if (isArrayOrList(param, paramType)) { // An array
2777 String structLen = param + ".size()";
2778 print(members + "*" + structLen);
2780 print(Integer.toString(members));
2783 if (i != methParams.size() - 1) {
2791 * HELPER: writeStructMembersCplusStub() writes member parameters of struct
2793 private void writeStructMembersCplusStub(String simpleType, String paramType, String param) {
2795 // Get the struct declaration for this struct and generate initialization code
2796 StructDecl structDecl = getStructDecl(simpleType);
2797 List<String> memTypes = structDecl.getMemberTypes(simpleType);
2798 List<String> members = structDecl.getMembers(simpleType);
2799 if (isArrayOrList(param, paramType)) { // An array or list
2800 println("for(int i = 0; i < " + param + ".size(); i++) {");
2802 if (isArrayOrList(param, paramType)) { // An array or list
2803 for (int i = 0; i < members.size(); i++) {
2804 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
2805 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
2806 println("paramCls[pos] = \"" + getSimpleType(getEnumType(prmType)) + "\";");
2807 print("paramObj[pos++] = &" + param + "[i].");
2808 print(getSimpleIdentifier(members.get(i)));
2812 } else { // Just one struct element
2813 for (int i = 0; i < members.size(); i++) {
2814 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
2815 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
2816 println("paramCls[pos] = \"" + getSimpleType(getEnumType(prmType)) + "\";");
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 = checkAndGetCplusType(methPrmTypes.get(i));
2845 String prmType = checkAndGetCplusArrayType(prmTypeC, methParams.get(i));
2846 println("paramCls[pos] = \"" + getSimpleType(getEnumType(prmType)) + "\";");
2847 print("paramObj[pos++] = &");
2848 print(getEnumParam(methPrmTypes.get(i), getSimpleIdentifier(methParams.get(i)), i));
2857 * HELPER: writeStructRetMembersCplusStub() writes member parameters of struct for return statement
2859 private void writeStructRetMembersCplusStub(String simpleType, String retType) {
2861 // Get the struct declaration for this struct and generate initialization code
2862 StructDecl structDecl = getStructDecl(simpleType);
2863 List<String> memTypes = structDecl.getMemberTypes(simpleType);
2864 List<String> members = structDecl.getMembers(simpleType);
2865 if (isArrayOrList(retType, retType)) { // An array or list
2866 println("for(int i = 0; i < retLen; i++) {");
2868 if (isArrayOrList(retType, retType)) { // An array or list
2869 for (int i = 0; i < members.size(); i++) {
2870 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
2871 print("structRet[i]." + getSimpleIdentifier(members.get(i)));
2872 println(" = retParam" + i + "[i];");
2875 } else { // Just one struct element
2876 for (int i = 0; i < members.size(); i++) {
2877 String prmType = checkAndGetArray(memTypes.get(i), members.get(i));
2878 print("structRet." + getSimpleIdentifier(members.get(i)));
2879 println(" = retParam" + i + ";");
2882 println("return structRet;");
2887 * HELPER: writeStructReturnCplusStub() writes member parameters of struct for return statement
2889 private void writeStructReturnCplusStub(String simpleType, String retType) {
2891 // Minimum retLen is 1 if this is a single struct object
2892 println("int retLen = 0;");
2893 println("void* retLenObj = { &retLen };");
2894 // Handle the returned struct!!!
2895 println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retLenObj);");
2896 int numMem = getNumOfMembers(simpleType);
2897 println("int numRet = " + numMem + "*retLen;");
2898 println("string retCls[numRet];");
2899 println("void* retObj[numRet];");
2900 StructDecl structDecl = getStructDecl(simpleType);
2901 List<String> memTypes = structDecl.getMemberTypes(simpleType);
2902 List<String> members = structDecl.getMembers(simpleType);
2904 if (isArrayOrList(retType, retType)) { // An array or list
2905 for (int i = 0; i < members.size(); i++) {
2906 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
2907 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
2908 println(getSimpleType(getEnumType(prmType)) + " retParam" + i + "[retLen];");
2910 } else { // Just one struct element
2911 for (int i = 0; i < members.size(); i++) {
2912 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
2913 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
2914 println(getSimpleType(getEnumType(prmType)) + " retParam" + i + ";");
2917 println("int retPos = 0;");
2918 // Get the struct declaration for this struct and generate initialization code
2919 if (isArrayOrList(retType, retType)) { // An array or list
2920 println("for(int i = 0; i < retLen; i++) {");
2921 for (int i = 0; i < members.size(); i++) {
2922 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
2923 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
2924 println("retCls[retPos] = \"" + getSimpleType(getEnumType(prmType)) + "\";");
2925 println("retObj[retPos++] = &retParam" + i + "[i];");
2928 } else { // Just one struct element
2929 for (int i = 0; i < members.size(); i++) {
2930 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
2931 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
2932 println("retCls[retPos] = \"" + getSimpleType(getEnumType(prmType)) + "\";");
2933 println("retObj[retPos++] = &retParam" + i + ";");
2936 println("rmiCall->getStructObjects(retCls, numRet, retObj);");
2937 if (isArrayOrList(retType, retType)) { // An array or list
2938 println("vector<" + simpleType + "> structRet(retLen);");
2940 println(simpleType + " structRet;");
2941 writeStructRetMembersCplusStub(simpleType, retType);
2946 * HELPER: writeStdMethodBodyCplusStub() writes the standard method body in the stub class
2948 private void writeStdMethodBodyCplusStub(InterfaceDecl intDecl, List<String> methParams,
2949 List<String> methPrmTypes, String method) {
2951 checkAndWriteStructSetupCplusStub(methParams, methPrmTypes, intDecl, method);
2952 println("int methodId = " + intDecl.getMethodNumId(method) + ";");
2953 String retType = intDecl.getMethodType(method);
2954 println("string retType = \"" + checkAndGetCplusRetClsType(getStructType(getEnumType(retType))) + "\";");
2955 // Generate array of parameter types
2956 if (isStructPresent(methParams, methPrmTypes)) {
2957 writeStructParamClassCplusStub(methParams, methPrmTypes);
2959 println("int numParam = " + methParams.size() + ";");
2960 print("string paramCls[] = { ");
2961 for (int i = 0; i < methParams.size(); i++) {
2962 String paramTypeC = checkAndGetCplusArgClsType(methPrmTypes.get(i), methParams.get(i));
2963 print("\"" + paramTypeC + "\"");
2964 // Check if this is the last element (don't print a comma)
2965 if (i != methParams.size() - 1) {
2970 checkAndWriteEnumTypeCplusStub(methParams, methPrmTypes);
2971 // Generate array of parameter objects
2972 print("void* paramObj[] = { ");
2973 for (int i = 0; i < methParams.size(); i++) {
2974 print("&" + getEnumParam(methPrmTypes.get(i), getSimpleIdentifier(methParams.get(i)), i));
2975 // Check if this is the last element (don't print a comma)
2976 if (i != methParams.size() - 1) {
2982 // Check if this is "void"
2983 if (retType.equals("void")) {
2984 println("void* retObj = NULL;");
2985 println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
2986 } else { // We do have a return value
2987 // Generate array of parameter types
2988 if (isStructClass(getGenericType(getSimpleArrayType(retType)))) {
2989 writeStructReturnCplusStub(getGenericType(getSimpleArrayType(retType)), retType);
2991 // Check if the return value NONPRIMITIVES
2992 if (isEnumClass(getSimpleArrayType(getGenericType(retType)))) {
2993 checkAndWriteEnumRetTypeCplusStub(retType);
2995 //if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
2996 if (isArrayOrList(retType,retType))
2997 println(checkAndGetCplusType(retType) + " retVal;");
2999 println(checkAndGetCplusType(retType) + " retVal = " + generateCplusInitializer(retType) + ";");
3001 println("void* retObj = &retVal;");
3002 println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
3003 println("return retVal;");
3011 * HELPER: writePropertiesCplusStub() writes the properties of the stub class
3013 private void writePropertiesCplusPermission(String intface) {
3015 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3016 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3017 String newIntface = intMeth.getKey();
3018 int newObjectId = getNewIntfaceObjectId(newIntface);
3019 println("const static int object" + newObjectId + "Id = " + newObjectId + ";\t//" + newIntface);
3020 println("static set<int> set" + newObjectId + "Allowed;");
3025 * HELPER: writePropertiesCplusStub() writes the properties of the stub class
3027 private void writePropertiesCplusStub(String intface, String newIntface, boolean callbackExist, Set<String> callbackClasses) {
3029 println("IoTRMICall *rmiCall;");
3030 //println("IoTRMIObject\t\t\t*rmiObj;");
3031 println("string address;");
3032 println("vector<int> ports;\n");
3033 // Get the object Id
3034 Integer objId = mapIntfaceObjId.get(intface);
3035 println("const static int objectId = " + objId + ";");
3036 mapNewIntfaceObjId.put(newIntface, objId);
3037 mapIntfaceObjId.put(intface, objId++);
3038 if (callbackExist) {
3039 // We assume that each class only has one callback interface for now
3040 Iterator it = callbackClasses.iterator();
3041 String callbackType = (String) it.next();
3042 println("// Callback properties");
3043 println("IoTRMIObject *rmiObj;");
3044 println("vector<" + callbackType + "*> vecCallbackObj;");
3045 println("static int objIdCnt;");
3046 // Generate permission stuff for callback stubs
3047 writePropertiesCplusPermission(callbackType);
3054 * HELPER: writeConstructorCplusStub() writes the constructor of the stub class
3056 private void writeConstructorCplusStub(String newStubClass, boolean callbackExist, Set<String> callbackClasses) {
3058 println(newStubClass +
3059 "(int _port, const char* _address, int _rev, bool* _bResult, vector<int> _ports) {");
3060 println("address = _address;");
3061 println("ports = _ports;");
3062 println("rmiCall = new IoTRMICall(_port, _address, _rev, _bResult);");
3063 if (callbackExist) {
3064 Iterator it = callbackClasses.iterator();
3065 String callbackType = (String) it.next();
3066 println("thread th1 (&" + newStubClass + "::___initCallBack, this);");
3067 println("th1.detach();");
3068 println("___regCB();");
3075 * HELPER: writeDeconstructorCplusStub() writes the deconstructor of the stub class
3077 private void writeDeconstructorCplusStub(String newStubClass, boolean callbackExist, Set<String> callbackClasses) {
3079 println("~" + newStubClass + "() {");
3080 println("if (rmiCall != NULL) {");
3081 println("delete rmiCall;");
3082 println("rmiCall = NULL;");
3084 if (callbackExist) {
3085 // We assume that each class only has one callback interface for now
3086 println("if (rmiObj != NULL) {");
3087 println("delete rmiObj;");
3088 println("rmiObj = NULL;");
3090 Iterator it = callbackClasses.iterator();
3091 String callbackType = (String) it.next();
3092 println("for(" + callbackType + "* cb : vecCallbackObj) {");
3093 println("delete cb;");
3094 println("cb = NULL;");
3103 * HELPER: writeCplusMethodCallbackPermission() writes permission checks in stub for callbacks
3105 private void writeCplusMethodCallbackPermission(String intface) {
3107 println("int methodId = IoTRMIObject::getMethodId(method);");
3108 // Get all the different stubs
3109 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3110 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3111 String newIntface = intMeth.getKey();
3112 int newObjectId = getNewIntfaceObjectId(newIntface);
3113 println("if (set" + newObjectId + "Allowed.find(methodId) == set" + newObjectId + "Allowed.end()) {");
3114 println("cerr << \"Callback object for " + intface + " is not allowed to access method: \" << methodId;");
3115 println("exit(-1);");
3122 * HELPER: writeInitCallbackCplusStub() writes the initialization of callback
3124 private void writeInitCallbackCplusStub(String intface, InterfaceDecl intDecl) {
3126 println("void ___initCallBack() {");
3127 println("bool bResult = false;");
3128 println("rmiObj = new IoTRMIObject(ports[0], &bResult);");
3129 println("while (true) {");
3130 println("char* method = rmiObj->getMethodBytes();");
3131 writeCplusMethodCallbackPermission(intface);
3132 println("int objId = IoTRMIObject::getObjectId(method);");
3133 println("if (objId < vecCallbackObj.size()) { // Check if still within range");
3134 println(intface + "_CallbackSkeleton* skel = dynamic_cast<" + intface +
3135 "_CallbackSkeleton*> (vecCallbackObj.at(objId));");
3136 println("skel->invokeMethod(rmiObj);");
3139 println("cerr << \"Illegal object Id: \" << to_string(objId);");
3140 // TODO: perhaps need to change this into "throw" to make it cleaner (allow stack unfolding)
3141 println("exit(-1);");
3149 * HELPER: writeCplusInitCallbackPermission() writes the permission for callback
3151 private void writeCplusInitCallbackPermission(String intface, InterfaceDecl intDecl, boolean callbackExist) {
3153 if (callbackExist) {
3154 String method = "___initCallBack()";
3155 int methodNumId = intDecl.getHelperMethodNumId(method);
3156 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3157 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3158 String newIntface = intMeth.getKey();
3159 int newObjectId = getNewIntfaceObjectId(newIntface);
3160 println("set" + newObjectId + "Allowed.insert(" + methodNumId + ");");
3167 * HELPER: writeInitCallbackSendInfoCplusStub() writes the initialization (send info part) of callback
3169 private void writeInitCallbackSendInfoCplusStub(InterfaceDecl intDecl) {
3171 // Generate info sending part
3172 println("void ___regCB() {");
3173 println("int numParam = 3;");
3174 String method = "___initCallBack()";
3175 int methodNumId = intDecl.getHelperMethodNumId(method);
3176 println("int methodId = " + methodNumId + ";");
3177 //writeCplusCallbackPermission(intface, methodNumId);
3178 println("string retType = \"void\";");
3179 println("string paramCls[] = { \"int\", \"string\", \"int\" };");
3180 println("int rev = 0;");
3181 println("void* paramObj[] = { &ports[0], &address, &rev };");
3182 println("void* retObj = NULL;");
3183 println("rmiCall->remoteCall(objectId, methodId, retType, paramCls, paramObj, numParam, retObj);");
3189 * generateCPlusStubClasses() generate stubs based on the methods list in C++
3191 public void generateCPlusStubClasses() throws IOException {
3193 // Create a new directory
3194 String path = createDirectories(dir, subdir);
3195 for (String intface : mapIntfacePTH.keySet()) {
3197 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3198 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3199 // Open a new file to write into
3200 String newIntface = intMeth.getKey();
3201 String newStubClass = newIntface + "_Stub";
3202 FileWriter fw = new FileWriter(path + "/" + newStubClass + ".hpp");
3203 pw = new PrintWriter(new BufferedWriter(fw));
3204 // Write file headers
3205 println("#ifndef _" + newStubClass.toUpperCase() + "_HPP__");
3206 println("#define _" + newStubClass.toUpperCase() + "_HPP__");
3207 println("#include <iostream>");
3208 // Find out if there are callback objects
3209 Set<String> methods = intMeth.getValue();
3210 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
3211 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
3212 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
3213 boolean callbackExist = !callbackClasses.isEmpty();
3214 if (callbackExist) // Need thread library if this has callback
3215 println("#include <thread>");
3216 println("#include \"" + newIntface + ".hpp\""); println("");
3217 println("using namespace std;"); println("");
3218 println("class " + newStubClass + " : public " + newIntface); println("{");
3219 println("private:\n");
3220 writePropertiesCplusStub(intface, newIntface, callbackExist, callbackClasses);
3221 println("public:\n");
3222 // Add default constructor and destructor
3223 println(newStubClass + "() { }"); println("");
3224 writeConstructorCplusStub(newStubClass, callbackExist, callbackClasses);
3225 writeDeconstructorCplusStub(newStubClass, callbackExist, callbackClasses);
3227 writeMethodCplusStub(methods, intDecl, callbackClasses);
3228 print("}"); println(";");
3230 writePermissionInitializationCplus(intface, newStubClass, intDecl);
3231 writeObjectIdCountInitializationCplus(newStubClass, callbackExist);
3234 System.out.println("IoTCompiler: Generated stub class " + newStubClass + ".hpp...");
3241 * HELPER: writePropertiesCplusCallbackStub() writes the properties of the stub class
3243 private void writePropertiesCplusCallbackStub(String intface, String newIntface, boolean callbackExist, Set<String> callbackClasses) {
3245 println("IoTRMICall *rmiCall;");
3246 // Get the object Id
3247 println("int objectId;");
3248 if (callbackExist) {
3249 // We assume that each class only has one callback interface for now
3250 Iterator it = callbackClasses.iterator();
3251 String callbackType = (String) it.next();
3252 println("// Callback properties");
3253 println("IoTRMIObject *rmiObj;");
3254 println("vector<" + callbackType + "*> vecCallbackObj;");
3255 println("static int objIdCnt;");
3256 // TODO: Need to initialize address and ports if we want to have callback-in-callback
3257 println("string address;");
3258 println("vector<int> ports;\n");
3259 writePropertiesCplusPermission(callbackType);
3266 * HELPER: writeConstructorCplusCallbackStub() writes the constructor of the stub class
3268 private void writeConstructorCplusCallbackStub(String newStubClass, boolean callbackExist, Set<String> callbackClasses) {
3270 println(newStubClass + "(IoTRMICall* _rmiCall, int _objectId) {");
3271 println("objectId = _objectId;");
3272 println("rmiCall = _rmiCall;");
3273 if (callbackExist) {
3274 Iterator it = callbackClasses.iterator();
3275 String callbackType = (String) it.next();
3276 println("thread th1 (&" + newStubClass + "::___initCallBack, this);");
3277 println("th1.detach();");
3278 println("___regCB();");
3285 * generateCPlusCallbackStubClasses() generate callback stubs based on the methods list in C++
3287 public void generateCPlusCallbackStubClasses() throws IOException {
3289 // Create a new directory
3290 String path = createDirectories(dir, subdir);
3291 for (String intface : mapIntfacePTH.keySet()) {
3293 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3294 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3295 // Open a new file to write into
3296 String newIntface = intMeth.getKey();
3297 String newStubClass = newIntface + "_CallbackStub";
3298 FileWriter fw = new FileWriter(path + "/" + newStubClass + ".hpp");
3299 pw = new PrintWriter(new BufferedWriter(fw));
3300 // Find out if there are callback objects
3301 Set<String> methods = intMeth.getValue();
3302 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
3303 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
3304 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
3305 boolean callbackExist = !callbackClasses.isEmpty();
3306 // Write file headers
3307 println("#ifndef _" + newStubClass.toUpperCase() + "_HPP__");
3308 println("#define _" + newStubClass.toUpperCase() + "_HPP__");
3309 println("#include <iostream>");
3311 println("#include <thread>");
3312 println("#include \"" + newIntface + ".hpp\""); println("");
3313 println("using namespace std;"); println("");
3314 println("class " + newStubClass + " : public " + newIntface); println("{");
3315 println("private:\n");
3316 writePropertiesCplusCallbackStub(intface, newIntface, callbackExist, callbackClasses);
3317 println("public:\n");
3318 // Add default constructor and destructor
3319 println(newStubClass + "() { }"); println("");
3320 writeConstructorCplusCallbackStub(newStubClass, callbackExist, callbackClasses);
3321 writeDeconstructorCplusStub(newStubClass, callbackExist, callbackClasses);
3323 writeMethodCplusStub(methods, intDecl, callbackClasses);
3326 writePermissionInitializationCplus(intface, newStubClass, intDecl);
3327 writeObjectIdCountInitializationCplus(newStubClass, callbackExist);
3330 System.out.println("IoTCompiler: Generated callback stub class " + newIntface + ".hpp...");
3337 * HELPER: writePropertiesCplusSkeleton() writes the properties of the skeleton class
3339 private void writePropertiesCplusSkeleton(String intface, boolean callbackExist, Set<String> callbackClasses) {
3341 println(intface + " *mainObj;");
3343 if (callbackExist) {
3344 Iterator it = callbackClasses.iterator();
3345 String callbackType = (String) it.next();
3346 String exchangeType = checkAndGetParamClass(callbackType);
3347 println("// Callback properties");
3348 println("static int objIdCnt;");
3349 println("vector<" + exchangeType + "*> vecCallbackObj;");
3350 println("IoTRMICall *rmiCall;");
3352 println("IoTRMIObject *rmiObj;\n");
3353 // Keep track of object Ids of all stubs registered to this interface
3354 writePropertiesCplusPermission(intface);
3360 * HELPER: writeObjectIdCountInitializationCplus() writes the initialization of objIdCnt variable
3362 private void writeObjectIdCountInitializationCplus(String newSkelClass, boolean callbackExist) {
3365 println("int " + newSkelClass + "::objIdCnt = 0;");
3370 * HELPER: writePermissionInitializationCplus() writes the initialization of permission set
3372 private void writePermissionInitializationCplus(String intface, String newSkelClass, InterfaceDecl intDecl) {
3374 // Keep track of object Ids of all stubs registered to this interface
3375 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3376 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3377 String newIntface = intMeth.getKey();
3378 int newObjectId = getNewIntfaceObjectId(newIntface);
3379 print("set<int> " + newSkelClass + "::set" + newObjectId + "Allowed {");
3380 Set<String> methodIds = intMeth.getValue();
3382 for (String methodId : methodIds) {
3383 int methodNumId = intDecl.getMethodNumId(methodId);
3384 print(Integer.toString(methodNumId));
3385 // Check if this is the last element (don't print a comma)
3386 if (i != methodIds.size() - 1) {
3397 * HELPER: writeStructPermissionCplusSkeleton() writes permission for struct helper
3399 private void writeStructPermissionCplusSkeleton(Collection<String> methods, InterfaceDecl intDecl, String intface) {
3401 // Use this set to handle two same methodIds
3402 for (String method : methods) {
3403 List<String> methParams = intDecl.getMethodParams(method);
3404 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
3405 // Check for params with structs
3406 for (int i = 0; i < methParams.size(); i++) {
3407 String paramType = methPrmTypes.get(i);
3408 String param = methParams.get(i);
3409 String simpleType = getSimpleType(paramType);
3410 if (isStructClass(simpleType)) {
3411 int methodNumId = intDecl.getMethodNumId(method);
3412 // Iterate over interfaces to give permissions to
3413 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
3414 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
3415 String newIntface = intMeth.getKey();
3416 int newObjectId = getNewIntfaceObjectId(newIntface);
3417 println("set" + newObjectId + "Allowed.insert(" + methodNumId + ");");
3426 * HELPER: writeConstructorCplusSkeleton() writes the constructor of the skeleton class
3428 private void writeConstructorCplusSkeleton(String newSkelClass, String intface, boolean callbackExist, InterfaceDecl intDecl, Collection<String> methods) {
3430 println(newSkelClass + "(" + intface + " *_mainObj, int _port) {");
3431 println("bool _bResult = false;");
3432 println("mainObj = _mainObj;");
3433 println("rmiObj = new IoTRMIObject(_port, &_bResult);");
3434 writeCplusInitCallbackPermission(intface, intDecl, callbackExist);
3435 writeStructPermissionCplusSkeleton(methods, intDecl, intface);
3436 println("___waitRequestInvokeMethod();");
3442 * HELPER: writeDeconstructorCplusSkeleton() writes the deconstructor of the skeleton class
3444 private void writeDeconstructorCplusSkeleton(String newSkelClass, boolean callbackExist, Set<String> callbackClasses) {
3446 println("~" + newSkelClass + "() {");
3447 println("if (rmiObj != NULL) {");
3448 println("delete rmiObj;");
3449 println("rmiObj = NULL;");
3451 if (callbackExist) {
3452 // We assume that each class only has one callback interface for now
3453 println("if (rmiCall != NULL) {");
3454 println("delete rmiCall;");
3455 println("rmiCall = NULL;");
3457 Iterator it = callbackClasses.iterator();
3458 String callbackType = (String) it.next();
3459 String exchangeType = checkAndGetParamClass(callbackType);
3460 println("for(" + exchangeType + "* cb : vecCallbackObj) {");
3461 println("delete cb;");
3462 println("cb = NULL;");
3471 * HELPER: writeStdMethodBodyCplusSkeleton() writes the standard method body in the skeleton class
3473 private void writeStdMethodBodyCplusSkeleton(List<String> methParams, String methodId, String methodType) {
3475 if (methodType.equals("void"))
3476 print("mainObj->" + methodId + "(");
3478 print("return mainObj->" + methodId + "(");
3479 for (int i = 0; i < methParams.size(); i++) {
3481 print(getSimpleIdentifier(methParams.get(i)));
3482 // Check if this is the last element (don't print a comma)
3483 if (i != methParams.size() - 1) {
3492 * HELPER: writeInitCallbackCplusSkeleton() writes the init callback method for skeleton class
3494 private void writeInitCallbackCplusSkeleton(boolean callbackSkeleton) {
3496 // This is a callback skeleton generation
3497 if (callbackSkeleton)
3498 println("void ___regCB(IoTRMIObject* rmiObj) {");
3500 println("void ___regCB() {");
3501 println("int numParam = 3;");
3502 println("int param1 = 0;");
3503 println("string param2 = \"\";");
3504 println("int param3 = 0;");
3505 println("string paramCls[] = { \"int\", \"string\", \"int\" };");
3506 println("void* paramObj[] = { ¶m1, ¶m2, ¶m3 };");
3507 println("rmiObj->getMethodParams(paramCls, numParam, paramObj);");
3508 println("bool bResult = false;");
3509 println("rmiCall = new IoTRMICall(param1, param2.c_str(), param3, &bResult);");
3515 * HELPER: writeMethodCplusSkeleton() writes the method of the skeleton class
3517 private void writeMethodCplusSkeleton(Collection<String> methods, InterfaceDecl intDecl,
3518 Set<String> callbackClasses, boolean callbackSkeleton) {
3520 for (String method : methods) {
3522 List<String> methParams = intDecl.getMethodParams(method);
3523 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
3524 String methodId = intDecl.getMethodId(method);
3525 String methodType = checkAndGetCplusType(intDecl.getMethodType(method));
3526 print(methodType + " " + methodId + "(");
3527 boolean isCallbackMethod = false;
3528 String callbackType = null;
3529 for (int i = 0; i < methParams.size(); i++) {
3531 String origParamType = methPrmTypes.get(i);
3532 if (callbackClasses.contains(origParamType)) { // Check if this has callback object
3533 isCallbackMethod = true;
3534 callbackType = origParamType;
3536 String paramType = checkAndGetParamClass(methPrmTypes.get(i));
3537 String methPrmType = checkAndGetCplusType(paramType);
3538 String methParamComplete = checkAndGetCplusArray(methPrmType, methParams.get(i));
3539 print(methParamComplete);
3540 // Check if this is the last element (don't print a comma)
3541 if (i != methParams.size() - 1) {
3546 // Now, write the body of skeleton!
3547 writeStdMethodBodyCplusSkeleton(methParams, methodId, intDecl.getMethodType(method));
3549 if (isCallbackMethod)
3550 writeInitCallbackCplusSkeleton(callbackSkeleton);
3556 * HELPER: writeCallbackCplusNumStubs() writes the numStubs variable
3558 private void writeCallbackCplusNumStubs(List<String> methParams, List<String> methPrmTypes, String callbackType) {
3560 for (int i = 0; i < methParams.size(); i++) {
3561 String paramType = methPrmTypes.get(i);
3562 String param = methParams.get(i);
3563 //if (callbackType.equals(paramType)) {
3564 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
3565 String exchParamType = checkAndGetParamClass(paramType);
3566 // Print array if this is array or list if this is a list of callback objects
3567 println("int numStubs" + i + " = 0;");
3574 * HELPER: writeCallbackCplusStubGeneration() writes the callback stub generation part
3576 private void writeCallbackCplusStubGeneration(List<String> methParams, List<String> methPrmTypes, String callbackType) {
3578 // Iterate over callback objects
3579 for (int i = 0; i < methParams.size(); i++) {
3580 String paramType = methPrmTypes.get(i);
3581 String param = methParams.get(i);
3582 // Generate a loop if needed
3583 if (checkCallbackType(paramType, callbackType)) { // Check if this has callback object
3584 String exchParamType = checkAndGetParamClass(paramType);
3585 if (isArrayOrList(paramType, param)) {
3586 println("vector<" + exchParamType + "> stub;");
3587 println("for (int objId = 0; objId < numStubs" + i + "; objId++) {");
3588 println(exchParamType + "* cb" + i + " = new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt);");
3589 println("stub" + i + ".push_back(cb);");
3590 println("vecCallbackObj.push_back(cb);");
3591 println("objIdCnt++;");
3594 println(exchParamType + "* stub" + i + " = new " + exchParamType + "_CallbackStub(rmiCall, objIdCnt);");
3595 println("vecCallbackObj.push_back(stub" + i + ");");
3596 println("objIdCnt++;");
3604 * HELPER: checkAndWriteEnumTypeCplusSkeleton() writes the enum type (convert from enum to int)
3606 private void checkAndWriteEnumTypeCplusSkeleton(List<String> methParams, List<String> methPrmTypes) {
3608 // Iterate and find enum declarations
3609 for (int i = 0; i < methParams.size(); i++) {
3610 String paramType = methPrmTypes.get(i);
3611 String param = methParams.get(i);
3612 String simpleType = getGenericType(paramType);
3613 if (isEnumClass(simpleType)) {
3614 // Check if this is enum type
3615 if (isArrayOrList(paramType, param)) { // An array
3616 println("int len" + i + " = paramEnumInt" + i + ".size();");
3617 println("vector<" + simpleType + "> paramEnum" + i + "(len" + i + ");");
3618 println("for (int i=0; i < len" + i + "; i++) {");
3619 println("paramEnum" + i + "[i] = (" + simpleType + ") paramEnumInt" + i + "[i];");
3621 } else { // Just one element
3622 println(simpleType + " paramEnum" + i + ";");
3623 println("paramEnum" + i + " = (" + simpleType + ") paramEnumInt" + i + "[0];");
3631 * HELPER: checkAndWriteEnumRetTypeCplusSkeleton() writes the enum return type (convert from enum to int)
3633 private void checkAndWriteEnumRetTypeCplusSkeleton(String retType) {
3635 // Strips off array "[]" for return type
3636 String pureType = getSimpleArrayType(getGenericType(retType));
3637 // Take the inner type of generic
3638 if (getParamCategory(retType) == ParamCategory.NONPRIMITIVES)
3639 pureType = getTypeOfGeneric(retType)[0];
3640 if (isEnumClass(pureType)) {
3641 // Check if this is enum type
3643 if (isArrayOrList(retType, retType)) { // An array
3644 println("int retLen = retEnum.size();");
3645 println("vector<int> retEnumInt(retLen);");
3646 println("for (int i=0; i < retLen; i++) {");
3647 println("retEnumInt[i] = (int) retEnum[i];");
3649 } else { // Just one element
3650 println("vector<int> retEnumInt(1);");
3651 println("retEnumInt[0] = (int) retEnum;");
3658 * HELPER: writeMethodHelperReturnCplusSkeleton() writes the return statement part in skeleton
3660 private void writeMethodInputParameters(List<String> methParams, List<String> methPrmTypes,
3661 Set<String> callbackClasses, String methodId) {
3663 print(methodId + "(");
3664 for (int i = 0; i < methParams.size(); i++) {
3665 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
3666 if (callbackClasses.contains(paramType))
3668 else if (isEnumClass(getGenericType(paramType))) // Check if this is enum type
3669 print("paramEnum" + i);
3670 else if (isStructClass(getGenericType(paramType))) // Struct type
3671 print("paramStruct" + i);
3673 print(getSimpleIdentifier(methParams.get(i)));
3674 if (i != methParams.size() - 1) {
3683 * HELPER: writeMethodHelperReturnCplusSkeleton() writes the return statement part in skeleton
3685 private void writeMethodHelperReturnCplusSkeleton(InterfaceDecl intDecl, List<String> methParams,
3686 List<String> methPrmTypes, String method, boolean isCallbackMethod, String callbackType,
3687 String methodId, Set<String> callbackClasses) {
3689 println("rmiObj->getMethodParams(paramCls, numParam, paramObj);");
3690 if (isCallbackMethod)
3691 writeCallbackCplusStubGeneration(methParams, methPrmTypes, callbackType);
3692 checkAndWriteEnumTypeCplusSkeleton(methParams, methPrmTypes);
3693 writeStructMembersInitCplusSkeleton(intDecl, methParams, methPrmTypes, method);
3694 // Check if this is "void"
3695 String retType = intDecl.getMethodType(method);
3696 // Check if this is "void"
3697 if (retType.equals("void")) {
3698 writeMethodInputParameters(methParams, methPrmTypes, callbackClasses, methodId);
3699 } else { // We do have a return value
3700 if (isEnumClass(getSimpleArrayType(getGenericType(retType)))) // Enum type
3701 print(checkAndGetCplusType(retType) + " retEnum = ");
3702 else if (isStructClass(getSimpleArrayType(getGenericType(retType)))) // Struct type
3703 print(checkAndGetCplusType(retType) + " retStruct = ");
3705 print(checkAndGetCplusType(retType) + " retVal = ");
3706 writeMethodInputParameters(methParams, methPrmTypes, callbackClasses, methodId);
3707 checkAndWriteEnumRetTypeCplusSkeleton(retType);
3708 if (isStructClass(getSimpleArrayType(getGenericType(retType)))) // Struct type
3709 writeStructReturnCplusSkeleton(getSimpleArrayType(getGenericType(retType)), retType);
3710 if (isEnumClass(getSimpleArrayType(getGenericType(retType)))) // Enum type
3711 println("void* retObj = &retEnumInt;");
3713 if (!isStructClass(getSimpleArrayType(getGenericType(retType)))) // Struct type
3714 println("void* retObj = &retVal;");
3715 String retTypeC = checkAndGetCplusType(retType);
3716 if (isStructClass(getSimpleArrayType(getGenericType(retType)))) // Struct type
3717 println("rmiObj->sendReturnObj(retObj, retCls, numRetObj);");
3719 println("rmiObj->sendReturnObj(retObj, \"" + checkAndGetCplusRetClsType(getEnumType(retType)) + "\");");
3725 * HELPER: writeStdMethodHelperBodyCplusSkeleton() writes the standard method body helper in the skeleton class
3727 private void writeStdMethodHelperBodyCplusSkeleton(InterfaceDecl intDecl, List<String> methParams,
3728 List<String> methPrmTypes, String method, String methodId, Set<String> callbackClasses) {
3730 // Generate array of parameter types
3731 boolean isCallbackMethod = false;
3732 String callbackType = null;
3733 print("string paramCls[] = { ");
3734 for (int i = 0; i < methParams.size(); i++) {
3735 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
3736 if (callbackClasses.contains(paramType)) {
3737 isCallbackMethod = true;
3738 callbackType = paramType;
3740 } else { // Generate normal classes if it's not a callback object
3741 String paramTypeC = checkAndGetCplusArgClsType(methPrmTypes.get(i), methParams.get(i));
3742 print("\"" + paramTypeC + "\"");
3744 if (i != methParams.size() - 1) {
3749 println("int numParam = " + methParams.size() + ";");
3750 if (isCallbackMethod)
3751 writeCallbackCplusNumStubs(methParams, methPrmTypes, callbackType);
3752 // Generate parameters
3753 for (int i = 0; i < methParams.size(); i++) {
3754 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
3755 if (!callbackClasses.contains(paramType)) {
3756 String methParamType = methPrmTypes.get(i);
3757 if (isEnumClass(getSimpleArrayType(getGenericType(methParamType)))) {
3758 // Check if this is enum type
3759 println("vector<int> paramEnumInt" + i + ";");
3761 String methPrmType = checkAndGetCplusType(methParamType);
3762 String methParamComplete = checkAndGetCplusArray(methPrmType, methParams.get(i));
3763 println(methParamComplete + ";");
3767 // Generate array of parameter objects
3768 print("void* paramObj[] = { ");
3769 for (int i = 0; i < methParams.size(); i++) {
3770 String paramType = returnGenericCallbackType(methPrmTypes.get(i));
3771 if (callbackClasses.contains(paramType))
3772 print("&numStubs" + i);
3773 else if (isEnumClass(getGenericType(paramType))) // Check if this is enum type
3774 print("¶mEnumInt" + i);
3776 print("&" + getSimpleIdentifier(methParams.get(i)));
3777 if (i != methParams.size() - 1) {
3782 // Write the return value part
3783 writeMethodHelperReturnCplusSkeleton(intDecl, methParams, methPrmTypes, method, isCallbackMethod,
3784 callbackType, methodId, callbackClasses);
3789 * HELPER: writeStructMembersCplusSkeleton() writes member parameters of struct
3791 private void writeStructMembersCplusSkeleton(String simpleType, String paramType,
3792 String param, String method, InterfaceDecl intDecl, int iVar) {
3794 // Get the struct declaration for this struct and generate initialization code
3795 StructDecl structDecl = getStructDecl(simpleType);
3796 List<String> memTypes = structDecl.getMemberTypes(simpleType);
3797 List<String> members = structDecl.getMembers(simpleType);
3798 int methodNumId = intDecl.getMethodNumId(method);
3799 String counter = "struct" + methodNumId + "Size" + iVar;
3800 if (isArrayOrList(param, paramType)) { // An array or list
3801 println("for(int i = 0; i < " + counter + "; i++) {");
3804 if (isArrayOrList(param, paramType)) { // An array or list
3805 for (int i = 0; i < members.size(); i++) {
3806 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
3807 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
3808 println(getSimpleType(getEnumType(prmType)) + " param" + i + "[" + counter + "];");
3810 } else { // Just one struct element
3811 for (int i = 0; i < members.size(); i++) {
3812 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
3813 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
3814 println(getSimpleType(getEnumType(prmType)) + " param" + i + ";");
3817 println("int pos = 0;");
3818 if (isArrayOrList(param, paramType)) { // An array or list
3819 println("for(int i = 0; i < retLen; i++) {");
3820 for (int i = 0; i < members.size(); i++) {
3821 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
3822 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
3823 println("paramCls[pos] = \"" + getSimpleType(getEnumType(prmType)) + "\";");
3824 println("paramObj[pos++] = ¶m" + i + "[i];");
3827 } else { // Just one struct element
3828 for (int i = 0; i < members.size(); i++) {
3829 String prmTypeC = checkAndGetCplusType(memTypes.get(i));
3830 String prmType = checkAndGetCplusArrayType(prmTypeC, members.get(i));
3831 println("paramCls[pos] = \"" + getSimpleType(getEnumType(prmType)) + "\";");
3832 println("paramObj[pos++] = ¶m" + i + ";");
3839 * HELPER: writeStructMembersInitCplusSkeleton() writes member parameters initialization of struct
3841 private void writeStructMembersInitCplusSkeleton(InterfaceDecl intDecl, List<String> methParams,
3842 List<String> methPrmTypes, String method) {
3844 for (int i = 0; i < methParams.size(); i++) {
3845 String paramType = methPrmTypes.get(i);
3846 String param = methParams.get(i);
3847 String simpleType = getGenericType(paramType);
3848 if (isStructClass(simpleType)) {
3849 int methodNumId = intDecl.getMethodNumId(method);
3850 String counter = "struct" + methodNumId + "Size" + i;
3852 if (isArrayOrList(param, paramType)) { // An array or list
3853 println("vector<" + simpleType + "> paramStruct" + i + ";");
3855 println(simpleType + " paramStruct" + i + ";");
3856 // Initialize members
3857 StructDecl structDecl = getStructDecl(simpleType);
3858 List<String> members = structDecl.getMembers(simpleType);
3859 List<String> memTypes = structDecl.getMemberTypes(simpleType);
3860 if (isArrayOrList(param, paramType)) { // An array or list
3861 println("for(int i = 0; i < " + counter + "; i++) {");
3862 for (int j = 0; j < members.size(); j++) {
3863 print("paramStruct" + i + "[i]." + getSimpleIdentifier(members.get(j)));
3864 println(" = param" + j + "[i];");
3867 } else { // Just one struct element
3868 for (int j = 0; j < members.size(); j++) {
3869 print("paramStruct" + i + "." + getSimpleIdentifier(members.get(j)));
3870 println(" = param" + j + ";");
3879 * HELPER: writeStructReturnCplusSkeleton() writes parameters of struct for return statement
3881 private void writeStructReturnCplusSkeleton(String simpleType, String retType) {
3883 // Minimum retLen is 1 if this is a single struct object
3884 if (isArrayOrList(retType, retType))
3885 println("int retLen = retStruct.size();");
3886 else // Just single struct object
3887 println("int retLen = 1;");
3888 println("void* retLenObj = &retLen;");
3889 println("rmiObj->sendReturnObj(retLenObj, \"int\");");
3890 int numMem = getNumOfMembers(simpleType);
3891 println("int numRetObj = " + numMem + "*retLen;");
3892 println("string retCls[numRetObj];");
3893 println("void* retObj[numRetObj];");
3894 println("int retPos = 0;");
3895 // Get the struct declaration for this struct and generate initialization code
3896 StructDecl structDecl = getStructDecl(simpleType);
3897 List<String> memTypes = structDecl.getMemberTypes(simpleType);
3898 List<String> members = structDecl.getMembers(simpleType);
3899 if (isArrayOrList(retType, retType)) { // An array or list
3900 println("for(int i = 0; i < retLen; i++) {");
3901 for (int i = 0; i < members.size(); i++) {
3902 String paramTypeC = checkAndGetCplusType(memTypes.get(i));
3903 String prmType = checkAndGetCplusArrayType(paramTypeC, members.get(i));
3904 println("retCls[retPos] = \"" + getSimpleType(getEnumType(prmType)) + "\";");
3905 print("retObj[retPos++] = &retStruct[i].");
3906 print(getEnumParam(memTypes.get(i), getSimpleIdentifier(members.get(i)), i));
3910 } else { // Just one struct element
3911 for (int i = 0; i < members.size(); i++) {
3912 String paramTypeC = checkAndGetCplusType(memTypes.get(i));
3913 String prmType = checkAndGetCplusArrayType(paramTypeC, members.get(i));
3914 println("retCls[retPos] = \"" + getSimpleType(getEnumType(prmType)) + "\";");
3915 print("retObj[retPos++] = &retStruct.");
3916 print(getEnumParam(memTypes.get(i), getSimpleIdentifier(members.get(i)), i));
3925 * HELPER: writeMethodHelperStructCplusSkeleton() writes the struct in skeleton
3927 private void writeMethodHelperStructCplusSkeleton(InterfaceDecl intDecl, List<String> methParams,
3928 List<String> methPrmTypes, String method, String methodId, Set<String> callbackClasses) {
3930 // Generate array of parameter objects
3931 boolean isCallbackMethod = false;
3932 String callbackType = null;
3933 print("int numParam = ");
3934 writeLengthStructParamClassSkeleton(methParams, methPrmTypes, method, intDecl);
3936 println("string paramCls[numParam];");
3937 println("void* paramObj[numParam];");
3938 // Iterate again over the parameters
3939 for (int i = 0; i < methParams.size(); i++) {
3940 String paramType = methPrmTypes.get(i);
3941 String param = methParams.get(i);
3942 String simpleType = getGenericType(paramType);
3943 if (isStructClass(simpleType)) {
3944 writeStructMembersCplusSkeleton(simpleType, paramType, param, method, intDecl, i);
3946 String prmType = returnGenericCallbackType(methPrmTypes.get(i));
3947 if (callbackClasses.contains(prmType)) {
3948 isCallbackMethod = true;
3949 callbackType = paramType;
3950 writeCallbackCplusNumStubs(methParams, methPrmTypes, callbackType);
3951 println("paramCls[pos] = \"int\";");
3952 println("paramObj[pos++] = &numStubs" + i + ";");
3953 } else { // Generate normal classes if it's not a callback object
3954 String paramTypeC = checkAndGetCplusType(methPrmTypes.get(i));
3955 String prmTypeC = checkAndGetCplusArrayType(paramTypeC, methParams.get(i));
3956 if (isEnumClass(getGenericType(paramTypeC))) { // Check if this is enum type
3957 println("vector<int> paramEnumInt" + i + ";");
3959 String methParamComplete = checkAndGetCplusArray(paramTypeC, methParams.get(i));
3960 println(methParamComplete + ";");
3962 println("paramCls[pos] = \"" + getEnumType(prmTypeC) + "\";");
3963 if (isEnumClass(getGenericType(paramType))) // Check if this is enum type
3964 println("paramObj[pos++] = ¶mEnumInt" + i);
3966 println("paramObj[pos++] = &" + getSimpleIdentifier(methParams.get(i)) + ";");
3970 // Write the return value part
3971 writeMethodHelperReturnCplusSkeleton(intDecl, methParams, methPrmTypes, method, isCallbackMethod,
3972 callbackType, methodId, callbackClasses);
3977 * HELPER: writeMethodHelperCplusSkeleton() writes the method helper of the skeleton class
3979 private void writeMethodHelperCplusSkeleton(Collection<String> methods, InterfaceDecl intDecl, Set<String> callbackClasses) {
3981 // Use this set to handle two same methodIds
3982 Set<String> uniqueMethodIds = new HashSet<String>();
3983 for (String method : methods) {
3985 List<String> methParams = intDecl.getMethodParams(method);
3986 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
3987 if (isStructPresent(methParams, methPrmTypes)) { // Treat struct differently
3988 String methodId = intDecl.getMethodId(method);
3990 String helperMethod = methodId;
3991 if (uniqueMethodIds.contains(methodId))
3992 helperMethod = helperMethod + intDecl.getMethodNumId(method);
3994 uniqueMethodIds.add(methodId);
3995 String retType = intDecl.getMethodType(method);
3996 print(helperMethod + "(");
3997 boolean begin = true;
3998 for (int i = 0; i < methParams.size(); i++) { // Print size variables
3999 String paramType = methPrmTypes.get(i);
4000 String param = methParams.get(i);
4001 String simpleType = getSimpleType(paramType);
4002 if (isStructClass(simpleType)) {
4003 if (!begin) { // Generate comma for not the beginning variable
4004 print(", "); begin = false;
4006 int methodNumId = intDecl.getMethodNumId(method);
4007 print("int struct" + methodNumId + "Size" + i);
4011 writeMethodHelperStructCplusSkeleton(intDecl, methParams, methPrmTypes, method, methodId, callbackClasses);
4014 String methodId = intDecl.getMethodId(method);
4016 String helperMethod = methodId;
4017 if (uniqueMethodIds.contains(methodId))
4018 helperMethod = helperMethod + intDecl.getMethodNumId(method);
4020 uniqueMethodIds.add(methodId);
4021 // Check if this is "void"
4022 String retType = intDecl.getMethodType(method);
4023 println(helperMethod + "() {");
4024 // Now, write the helper body of skeleton!
4025 writeStdMethodHelperBodyCplusSkeleton(intDecl, methParams, methPrmTypes, method, methodId, callbackClasses);
4029 // Write method helper for structs
4030 writeMethodHelperStructSetupCplusSkeleton(methods, intDecl);
4035 * HELPER: writeMethodHelperStructSetupCplusSkeleton() writes the method helper of struct in skeleton class
4037 private void writeMethodHelperStructSetupCplusSkeleton(Collection<String> methods,
4038 InterfaceDecl intDecl) {
4040 // Use this set to handle two same methodIds
4041 for (String method : methods) {
4043 List<String> methParams = intDecl.getMethodParams(method);
4044 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4045 // Check for params with structs
4046 for (int i = 0; i < methParams.size(); i++) {
4047 String paramType = methPrmTypes.get(i);
4048 String param = methParams.get(i);
4049 String simpleType = getSimpleType(paramType);
4050 if (isStructClass(simpleType)) {
4051 int methodNumId = intDecl.getMethodNumId(method);
4053 String helperMethod = methodNumId + "struct" + i;
4054 println(helperMethod + "() {");
4055 // Now, write the helper body of skeleton!
4056 println("string paramCls[] = { \"int\" };");
4057 println("int numParam = 1;");
4058 println("int param0 = 0;");
4059 println("void* paramObj[] = { ¶m0 };");
4060 println("rmiObj->getMethodParams(paramCls, numParam, paramObj);");
4061 println("return param0;");
4070 * HELPER: writeMethodHelperStructSetupCplusCallbackSkeleton() writes the method helper of struct in skeleton class
4072 private void writeMethodHelperStructSetupCplusCallbackSkeleton(Collection<String> methods,
4073 InterfaceDecl intDecl) {
4075 // Use this set to handle two same methodIds
4076 for (String method : methods) {
4078 List<String> methParams = intDecl.getMethodParams(method);
4079 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4080 // Check for params with structs
4081 for (int i = 0; i < methParams.size(); i++) {
4082 String paramType = methPrmTypes.get(i);
4083 String param = methParams.get(i);
4084 String simpleType = getSimpleType(paramType);
4085 if (isStructClass(simpleType)) {
4086 int methodNumId = intDecl.getMethodNumId(method);
4088 String helperMethod = methodNumId + "struct" + i;
4089 println(helperMethod + "(IoTRMIObject* rmiObj) {");
4090 // Now, write the helper body of skeleton!
4091 println("string paramCls[] = { \"int\" };");
4092 println("int numParam = 1;");
4093 println("int param0 = 0;");
4094 println("void* paramObj[] = { ¶m0 };");
4095 println("rmiObj->getMethodParams(paramCls, numParam, paramObj);");
4096 println("return param0;");
4105 * HELPER: writeCplusMethodPermission() writes permission checks in skeleton
4107 private void writeCplusMethodPermission(String intface) {
4109 // Get all the different stubs
4110 Map<String,Set<String>> mapNewIntMethods = mapInt2NewInts.get(intface);
4111 for (Map.Entry<String,Set<String>> intMeth : mapNewIntMethods.entrySet()) {
4112 String newIntface = intMeth.getKey();
4113 int newObjectId = getNewIntfaceObjectId(newIntface);
4114 println("if (_objectId == object" + newObjectId + "Id) {");
4115 println("if (set" + newObjectId + "Allowed.find(methodId) == set" + newObjectId + "Allowed.end()) {");
4116 println("cerr << \"Object with object Id: \" << _objectId << \" is not allowed to access method: \" << methodId << endl;");
4117 println("exit(-1);");
4121 println("cerr << \"Object Id: \" << _objectId << \" not recognized!\" << endl;");
4122 println("exit(-1);");
4129 * HELPER: writeCplusWaitRequestInvokeMethod() writes the main loop of the skeleton class
4131 private void writeCplusWaitRequestInvokeMethod(Collection<String> methods, InterfaceDecl intDecl, boolean callbackExist, String intface) {
4133 // Use this set to handle two same methodIds
4134 Set<String> uniqueMethodIds = new HashSet<String>();
4135 println("void ___waitRequestInvokeMethod() {");
4136 // Write variables here if we have callbacks or enums or structs
4137 writeCountVarStructSkeleton(methods, intDecl);
4138 println("while (true) {");
4139 println("rmiObj->getMethodBytes();");
4140 println("int _objectId = rmiObj->getObjectId();");
4141 println("int methodId = rmiObj->getMethodId();");
4142 // Generate permission check
4143 writeCplusMethodPermission(intface);
4144 println("switch (methodId) {");
4145 // Print methods and method Ids
4146 for (String method : methods) {
4147 String methodId = intDecl.getMethodId(method);
4148 int methodNumId = intDecl.getMethodNumId(method);
4149 print("case " + methodNumId + ": ___");
4150 String helperMethod = methodId;
4151 if (uniqueMethodIds.contains(methodId))
4152 helperMethod = helperMethod + methodNumId;
4154 uniqueMethodIds.add(methodId);
4155 print(helperMethod + "(");
4156 writeInputCountVarStructSkeleton(method, intDecl);
4157 println("); break;");
4159 String method = "___initCallBack()";
4160 // Print case -9999 (callback handler) if callback exists
4161 if (callbackExist) {
4162 int methodId = intDecl.getHelperMethodNumId(method);
4163 println("case " + methodId + ": ___regCB(); break;");
4165 writeMethodCallStructSkeleton(methods, intDecl);
4166 println("default: ");
4167 println("cerr << \"Method Id \" << methodId << \" not recognized!\" << endl;");
4168 println("throw exception();");
4176 * generateCplusSkeletonClass() generate skeletons based on the methods list in C++
4178 public void generateCplusSkeletonClass() throws IOException {
4180 // Create a new directory
4181 String path = createDirectories(dir, subdir);
4182 for (String intface : mapIntfacePTH.keySet()) {
4183 // Open a new file to write into
4184 String newSkelClass = intface + "_Skeleton";
4185 FileWriter fw = new FileWriter(path + "/" + newSkelClass + ".hpp");
4186 pw = new PrintWriter(new BufferedWriter(fw));
4187 // Write file headers
4188 println("#ifndef _" + newSkelClass.toUpperCase() + "_HPP__");
4189 println("#define _" + newSkelClass.toUpperCase() + "_HPP__");
4190 println("#include <iostream>");
4191 println("#include \"" + intface + ".hpp\"\n");
4192 // Pass in set of methods and get import classes
4193 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4194 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
4195 List<String> methods = intDecl.getMethods();
4196 Set<String> includeClasses = getIncludeClasses(methods, intDecl, intface, true);
4197 List<String> stdIncludeClasses = getStandardCplusIncludeClasses();
4198 List<String> allIncludeClasses = getAllLibClasses(stdIncludeClasses, includeClasses);
4199 printIncludeStatements(allIncludeClasses); println("");
4200 println("using namespace std;\n");
4201 // Find out if there are callback objects
4202 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
4203 boolean callbackExist = !callbackClasses.isEmpty();
4204 // Write class header
4205 println("class " + newSkelClass + " : public " + intface); println("{");
4206 println("private:\n");
4208 writePropertiesCplusSkeleton(intface, callbackExist, callbackClasses);
4209 println("public:\n");
4210 // Write constructor
4211 writeConstructorCplusSkeleton(newSkelClass, intface, callbackExist, intDecl, methods);
4212 // Write deconstructor
4213 writeDeconstructorCplusSkeleton(newSkelClass, callbackExist, callbackClasses);
4215 writeMethodCplusSkeleton(methods, intDecl, callbackClasses, false);
4216 // Write method helper
4217 writeMethodHelperCplusSkeleton(methods, intDecl, callbackClasses);
4218 // Write waitRequestInvokeMethod() - main loop
4219 writeCplusWaitRequestInvokeMethod(methods, intDecl, callbackExist, intface);
4221 writePermissionInitializationCplus(intface, newSkelClass, intDecl);
4222 writeObjectIdCountInitializationCplus(newSkelClass, callbackExist);
4225 System.out.println("IoTCompiler: Generated skeleton class " + newSkelClass + ".hpp...");
4231 * HELPER: writePropertiesCplusCallbackSkeleton() writes the properties of the callback skeleton class
4233 private void writePropertiesCplusCallbackSkeleton(String intface, boolean callbackExist, Set<String> callbackClasses) {
4235 println(intface + " *mainObj;");
4236 // Keep track of object Ids of all stubs registered to this interface
4237 println("int objectId;");
4239 if (callbackExist) {
4240 Iterator it = callbackClasses.iterator();
4241 String callbackType = (String) it.next();
4242 String exchangeType = checkAndGetParamClass(callbackType);
4243 println("// Callback properties");
4244 println("IoTRMICall* rmiCall;");
4245 println("vector<" + exchangeType + "*> vecCallbackObj;");
4246 println("static int objIdCnt;");
4253 * HELPER: writeConstructorCplusCallbackSkeleton() writes the constructor of the skeleton class
4255 private void writeConstructorCplusCallbackSkeleton(String newSkelClass, String intface, boolean callbackExist, InterfaceDecl intDecl, Collection<String> methods) {
4257 println(newSkelClass + "(" + intface + " *_mainObj, int _objectId) {");
4258 println("mainObj = _mainObj;");
4259 println("objectId = _objectId;");
4260 writeStructPermissionCplusSkeleton(methods, intDecl, intface);
4266 * HELPER: writeDeconstructorCplusStub() writes the deconstructor of the stub class
4268 private void writeDeconstructorCplusCallbackSkeleton(String newStubClass, boolean callbackExist,
4269 Set<String> callbackClasses) {
4271 println("~" + newStubClass + "() {");
4272 if (callbackExist) {
4273 // We assume that each class only has one callback interface for now
4274 println("if (rmiCall != NULL) {");
4275 println("delete rmiCall;");
4276 println("rmiCall = NULL;");
4278 Iterator it = callbackClasses.iterator();
4279 String callbackType = (String) it.next();
4280 String exchangeType = checkAndGetParamClass(callbackType);
4281 println("for(" + exchangeType + "* cb : vecCallbackObj) {");
4282 println("delete cb;");
4283 println("cb = NULL;");
4292 * HELPER: writeMethodHelperCplusCallbackSkeleton() writes the method helper of callback skeleton class
4294 private void writeMethodHelperCplusCallbackSkeleton(Collection<String> methods, InterfaceDecl intDecl,
4295 Set<String> callbackClasses) {
4297 // Use this set to handle two same methodIds
4298 Set<String> uniqueMethodIds = new HashSet<String>();
4299 for (String method : methods) {
4301 List<String> methParams = intDecl.getMethodParams(method);
4302 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4303 if (isStructPresent(methParams, methPrmTypes)) { // Treat struct differently
4304 String methodId = intDecl.getMethodId(method);
4306 String helperMethod = methodId;
4307 if (uniqueMethodIds.contains(methodId))
4308 helperMethod = helperMethod + intDecl.getMethodNumId(method);
4310 uniqueMethodIds.add(methodId);
4311 String retType = intDecl.getMethodType(method);
4312 print(helperMethod + "(");
4313 boolean begin = true;
4314 for (int i = 0; i < methParams.size(); i++) { // Print size variables
4315 String paramType = methPrmTypes.get(i);
4316 String param = methParams.get(i);
4317 String simpleType = getSimpleType(paramType);
4318 if (isStructClass(simpleType)) {
4319 if (!begin) { // Generate comma for not the beginning variable
4320 print(", "); begin = false;
4322 int methodNumId = intDecl.getMethodNumId(method);
4323 print("int struct" + methodNumId + "Size" + i);
4326 println(", IoTRMIObject* rmiObj) {");
4327 writeMethodHelperStructCplusSkeleton(intDecl, methParams, methPrmTypes, method, methodId, callbackClasses);
4330 String methodId = intDecl.getMethodId(method);
4332 String helperMethod = methodId;
4333 if (uniqueMethodIds.contains(methodId))
4334 helperMethod = helperMethod + intDecl.getMethodNumId(method);
4336 uniqueMethodIds.add(methodId);
4337 // Check if this is "void"
4338 String retType = intDecl.getMethodType(method);
4339 println(helperMethod + "(IoTRMIObject* rmiObj) {");
4340 // Now, write the helper body of skeleton!
4341 writeStdMethodHelperBodyCplusSkeleton(intDecl, methParams, methPrmTypes, method, methodId, callbackClasses);
4345 // Write method helper for structs
4346 writeMethodHelperStructSetupCplusCallbackSkeleton(methods, intDecl);
4351 * HELPER: writeCplusCallbackWaitRequestInvokeMethod() writes the request invoke method of the skeleton callback class
4353 private void writeCplusCallbackWaitRequestInvokeMethod(Collection<String> methods, InterfaceDecl intDecl,
4354 boolean callbackExist) {
4356 // Use this set to handle two same methodIds
4357 Set<String> uniqueMethodIds = new HashSet<String>();
4358 println("void invokeMethod(IoTRMIObject* rmiObj) {");
4359 // Write variables here if we have callbacks or enums or structs
4360 writeCountVarStructSkeleton(methods, intDecl);
4361 // Write variables here if we have callbacks or enums or structs
4362 println("int methodId = rmiObj->getMethodId();");
4363 // TODO: code the permission check here!
4364 println("switch (methodId) {");
4365 // Print methods and method Ids
4366 for (String method : methods) {
4367 String methodId = intDecl.getMethodId(method);
4368 int methodNumId = intDecl.getMethodNumId(method);
4369 print("case " + methodNumId + ": ___");
4370 String helperMethod = methodId;
4371 if (uniqueMethodIds.contains(methodId))
4372 helperMethod = helperMethod + methodNumId;
4374 uniqueMethodIds.add(methodId);
4375 print(helperMethod + "(");
4376 if (writeInputCountVarStructSkeleton(method, intDecl))
4377 println(", rmiObj); break;");
4379 println("rmiObj); break;");
4381 String method = "___initCallBack()";
4382 // Print case -9999 (callback handler) if callback exists
4383 if (callbackExist) {
4384 int methodId = intDecl.getHelperMethodNumId(method);
4385 println("case " + methodId + ": ___regCB(rmiObj); break;");
4387 writeMethodCallStructCallbackSkeleton(methods, intDecl);
4388 println("default: ");
4389 println("cerr << \"Method Id \" << methodId << \" not recognized!\" << endl;");
4390 println("throw exception();");
4397 * generateCplusCallbackSkeletonClass() generate callback skeletons based on the methods list in C++
4399 public void generateCplusCallbackSkeletonClass() throws IOException {
4401 // Create a new directory
4402 String path = createDirectories(dir, subdir);
4403 for (String intface : mapIntfacePTH.keySet()) {
4404 // Open a new file to write into
4405 String newSkelClass = intface + "_CallbackSkeleton";
4406 FileWriter fw = new FileWriter(path + "/" + newSkelClass + ".hpp");
4407 pw = new PrintWriter(new BufferedWriter(fw));
4408 // Write file headers
4409 println("#ifndef _" + newSkelClass.toUpperCase() + "_HPP__");
4410 println("#define _" + newSkelClass.toUpperCase() + "_HPP__");
4411 println("#include <iostream>");
4412 println("#include \"" + intface + ".hpp\"\n");
4413 // Pass in set of methods and get import classes
4414 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4415 InterfaceDecl intDecl = (InterfaceDecl) decHandler.getInterfaceDecl(intface);
4416 List<String> methods = intDecl.getMethods();
4417 Set<String> includeClasses = getIncludeClasses(methods, intDecl, intface, true);
4418 List<String> stdIncludeClasses = getStandardCplusIncludeClasses();
4419 List<String> allIncludeClasses = getAllLibClasses(stdIncludeClasses, includeClasses);
4420 printIncludeStatements(allIncludeClasses); println("");
4421 // Find out if there are callback objects
4422 Set<String> callbackClasses = getCallbackClasses(methods, intDecl);
4423 boolean callbackExist = !callbackClasses.isEmpty();
4424 println("using namespace std;\n");
4425 // Write class header
4426 println("class " + newSkelClass + " : public " + intface); println("{");
4427 println("private:\n");
4429 writePropertiesCplusCallbackSkeleton(intface, callbackExist, callbackClasses);
4430 println("public:\n");
4431 // Write constructor
4432 writeConstructorCplusCallbackSkeleton(newSkelClass, intface, callbackExist, intDecl, methods);
4433 // Write deconstructor
4434 writeDeconstructorCplusCallbackSkeleton(newSkelClass, callbackExist, callbackClasses);
4436 writeMethodCplusSkeleton(methods, intDecl, callbackClasses, true);
4437 // Write method helper
4438 writeMethodHelperCplusCallbackSkeleton(methods, intDecl, callbackClasses);
4439 // Write waitRequestInvokeMethod() - main loop
4440 writeCplusCallbackWaitRequestInvokeMethod(methods, intDecl, callbackExist);
4442 writeObjectIdCountInitializationCplus(newSkelClass, callbackExist);
4445 System.out.println("IoTCompiler: Generated callback skeleton class " + newSkelClass + ".hpp...");
4451 * generateInitializer() generate initializer based on type
4453 public String generateCplusInitializer(String type) {
4455 // Generate dummy returns for now
4456 if (type.equals("short")||
4457 type.equals("int") ||
4458 type.equals("long") ||
4459 type.equals("float")||
4460 type.equals("double")) {
4463 } else if ( type.equals("String") ||
4464 type.equals("string")) {
4467 } else if ( type.equals("char") ||
4468 type.equals("byte")) {
4471 } else if ( type.equals("boolean")) {
4481 * setDirectory() sets a new directory for stub files
4483 public void setDirectory(String _subdir) {
4490 * printUsage() prints the usage of this compiler
4492 public static void printUsage() {
4494 System.out.println();
4495 System.out.println("Sentinel interface and stub compiler version 1.0");
4496 System.out.println("Copyright (c) 2015-2016 University of California, Irvine - Programming Language Group.");
4497 System.out.println("All rights reserved.");
4498 System.out.println("Usage:");
4499 System.out.println("\tjava IoTCompiler -help / --help / -h\n");
4500 System.out.println("\t\tDisplay this help texts\n\n");
4501 System.out.println("\tjava IoTCompiler [<main-policy-file> <req-policy-file>]");
4502 System.out.println("\tjava IoTCompiler [<main-policy-file> <req-policy-file>] [options]\n");
4503 System.out.println("\t\tTake one or more pairs of main-req policy files, and generate Java and/or C++ files\n");
4504 System.out.println("Options:");
4505 System.out.println("\t-java\t<directory>\tGenerate Java stub files");
4506 System.out.println("\t-cplus\t<directory>\tGenerate C++ stub files");
4507 System.out.println();
4512 * parseFile() prepares Lexer and Parser objects, then parses the file
4514 public static ParseNode parseFile(String file) {
4516 ParseNode pn = null;
4518 ComplexSymbolFactory csf = new ComplexSymbolFactory();
4519 ScannerBuffer lexer =
4520 new ScannerBuffer(new Lexer(new BufferedReader(new FileReader(file)),csf));
4521 Parser parse = new Parser(lexer,csf);
4522 pn = (ParseNode) parse.parse().value;
4523 } catch (Exception e) {
4524 e.printStackTrace();
4525 throw new Error("IoTCompiler: ERROR parsing policy file or wrong command line option: " + file + "\n");
4533 * Basic helper functions
4536 boolean newline=true;
4539 private void print(String str) {
4542 if (str.equals("}"))
4544 for(int i=0; i<tab; i++)
4554 * This function converts Java to C++ type for compilation
4556 private String convertType(String type) {
4558 if (mapPrimitives.containsKey(type))
4559 return mapPrimitives.get(type);
4566 * A collection of methods with print-to-file functionality
4568 private void println(String str) {
4571 if (str.contains("}") && !str.contains("{"))
4573 for(int i=0; i<tab; i++)
4582 private void updatetabbing(String str) {
4584 tablevel+=count(str,'{')-count(str,'}');
4588 private int count(String str, char key) {
4589 char[] array = str.toCharArray();
4591 for(int i=0; i<array.length; i++) {
4592 if (array[i] == key)
4599 private void createDirectory(String dirName) {
4601 File file = new File(dirName);
4602 if (!file.exists()) {
4604 System.out.println("IoTCompiler: Directory " + dirName + " has been created!");
4606 System.out.println("IoTCompiler: Failed to create directory " + dirName + "!");
4609 System.out.println("IoTCompiler: Directory " + dirName + " exists...");
4614 // Create a directory and possibly a sub directory
4615 private String createDirectories(String dir, String subdir) {
4618 createDirectory(path);
4619 if (subdir != null) {
4620 path = path + "/" + subdir;
4621 createDirectory(path);
4627 // Inserting array members into a Map object
4628 // that maps arrKey to arrVal objects
4629 private void arraysToMap(Map map, Object[] arrKey, Object[] arrVal) {
4631 for(int i = 0; i < arrKey.length; i++) {
4633 map.put(arrKey[i], arrVal[i]);
4638 // Check and find object Id for new interface in mapNewIntfaceObjId (callbacks)
4639 // Throw an error if the new interface is not found!
4640 // Basically the compiler needs to parse the policy (and requires) files for callback class first
4641 private int getNewIntfaceObjectId(String newIntface) {
4643 if (!mapNewIntfaceObjId.containsKey(newIntface)) {
4644 throw new Error("IoTCompiler: Need to parse policy and requires files for callback class first! " +
4645 "Please place the two files for callback class in front...\n");
4647 int retObjId = mapNewIntfaceObjId.get(newIntface);
4653 // Return parameter category, i.e. PRIMITIVES, NONPRIMITIVES, USERDEFINED, ENUM, or STRUCT
4654 private ParamCategory getParamCategory(String paramType) {
4656 if (mapPrimitives.containsKey(paramType)) {
4657 return ParamCategory.PRIMITIVES;
4658 // We can either use mapNonPrimitivesJava or mapNonPrimitivesCplus here
4659 } else if (mapNonPrimitivesJava.containsKey(getSimpleType(paramType))) {
4660 return ParamCategory.NONPRIMITIVES;
4661 } else if (isEnumClass(paramType)) {
4662 return ParamCategory.ENUM;
4663 } else if (isStructClass(paramType)) {
4664 return ParamCategory.STRUCT;
4666 return ParamCategory.USERDEFINED;
4670 // Return full class name for non-primitives to generate Java import statements
4671 // e.g. java.util.Set for Set
4672 private String getNonPrimitiveJavaClass(String paramNonPrimitives) {
4674 return mapNonPrimitivesJava.get(paramNonPrimitives);
4678 // Return full class name for non-primitives to generate Cplus include statements
4679 // e.g. #include <set> for Set
4680 private String getNonPrimitiveCplusClass(String paramNonPrimitives) {
4682 return mapNonPrimitivesCplus.get(paramNonPrimitives);
4686 // Get simple types, e.g. HashSet for HashSet<...>
4687 // Basically strip off the "<...>"
4688 private String getSimpleType(String paramType) {
4690 // Check if this is generics
4691 if(paramType.contains("<")) {
4692 String[] type = paramType.split("<");
4699 // Generate a set of standard classes for import statements
4700 private List<String> getStandardJavaIntfaceImportClasses() {
4702 List<String> importClasses = new ArrayList<String>();
4703 // Add the standard list first
4704 importClasses.add("java.util.List");
4705 importClasses.add("java.util.ArrayList");
4707 return importClasses;
4711 // Generate a set of standard classes for import statements
4712 private List<String> getStandardJavaImportClasses() {
4714 List<String> importClasses = new ArrayList<String>();
4715 // Add the standard list first
4716 importClasses.add("java.io.IOException");
4717 importClasses.add("java.util.List");
4718 importClasses.add("java.util.ArrayList");
4719 importClasses.add("java.util.Arrays");
4720 importClasses.add("iotrmi.Java.IoTRMICall");
4721 importClasses.add("iotrmi.Java.IoTRMIObject");
4723 return importClasses;
4727 // Generate a set of standard classes for import statements
4728 private List<String> getStandardCplusIncludeClasses() {
4730 List<String> importClasses = new ArrayList<String>();
4731 // Add the standard list first
4732 importClasses.add("<vector>");
4733 importClasses.add("<set>");
4734 importClasses.add("\"IoTRMICall.hpp\"");
4735 importClasses.add("\"IoTRMIObject.hpp\"");
4737 return importClasses;
4741 // Combine all classes for import statements
4742 private List<String> getAllLibClasses(Collection<String> stdLibClasses, Collection<String> libClasses) {
4744 List<String> allLibClasses = new ArrayList<String>(stdLibClasses);
4745 // Iterate over the list of import classes
4746 for (String str : libClasses) {
4747 if (!allLibClasses.contains(str)) {
4748 allLibClasses.add(str);
4751 return allLibClasses;
4756 // Generate a set of classes for import statements
4757 private Set<String> getImportClasses(Collection<String> methods, InterfaceDecl intDecl) {
4759 Set<String> importClasses = new HashSet<String>();
4760 for (String method : methods) {
4761 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4762 for (String paramType : methPrmTypes) {
4764 String simpleType = getSimpleType(paramType);
4765 if (getParamCategory(simpleType) == ParamCategory.NONPRIMITIVES) {
4766 importClasses.add(getNonPrimitiveJavaClass(simpleType));
4770 return importClasses;
4774 // Handle and return the correct enum declaration
4775 // In Java, if we declare enum in Camera interface, then it becomes "Camera.<enum>"
4776 private String getEnumParamDecl(String type, InterfaceDecl intDecl) {
4778 // Strips off array "[]" for return type
4779 String pureType = getSimpleArrayType(type);
4780 // Take the inner type of generic
4781 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
4782 pureType = getTypeOfGeneric(type)[0];
4783 if (isEnumClass(pureType)) {
4784 String enumType = intDecl.getInterface() + "." + type;
4791 // Handle and return the correct type
4792 private String getEnumParam(String type, String param, int i) {
4794 // Strips off array "[]" for return type
4795 String pureType = getSimpleArrayType(type);
4796 // Take the inner type of generic
4797 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
4798 pureType = getTypeOfGeneric(type)[0];
4799 if (isEnumClass(pureType)) {
4800 String enumParam = "paramEnum" + i;
4807 // Handle and return the correct enum declaration translate into int[]
4808 private String getEnumType(String type) {
4810 // Strips off array "[]" for return type
4811 String pureType = getSimpleArrayType(type);
4812 // Take the inner type of generic
4813 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
4814 pureType = getGenericType(type);
4815 if (isEnumClass(pureType)) {
4816 String enumType = "int[]";
4822 // Handle and return the correct enum declaration translate into int* for C
4823 private String getEnumCplusClsType(String type) {
4825 // Strips off array "[]" for return type
4826 String pureType = getSimpleArrayType(type);
4827 // Take the inner type of generic
4828 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
4829 pureType = getGenericType(type);
4830 if (isEnumClass(pureType)) {
4831 String enumType = "int*";
4838 // Handle and return the correct struct declaration
4839 private String getStructType(String type) {
4841 // Strips off array "[]" for return type
4842 String pureType = getSimpleArrayType(type);
4843 // Take the inner type of generic
4844 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES)
4845 pureType = getGenericType(type);
4846 if (isStructClass(pureType)) {
4847 String structType = "int";
4854 // Check if this an enum declaration
4855 private boolean isEnumClass(String type) {
4857 // Just iterate over the set of interfaces
4858 for (String intface : mapIntfacePTH.keySet()) {
4859 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4860 EnumDecl enumDecl = (EnumDecl) decHandler.getEnumDecl(intface);
4861 Set<String> setEnumDecl = enumDecl.getEnumDeclarations();
4862 if (setEnumDecl.contains(type))
4869 // Check if this an struct declaration
4870 private boolean isStructClass(String type) {
4872 // Just iterate over the set of interfaces
4873 for (String intface : mapIntfacePTH.keySet()) {
4874 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4875 StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
4876 List<String> listStructDecl = structDecl.getStructTypes();
4877 if (listStructDecl.contains(type))
4884 // Return a struct declaration
4885 private StructDecl getStructDecl(String type) {
4887 // Just iterate over the set of interfaces
4888 for (String intface : mapIntfacePTH.keySet()) {
4889 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4890 StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
4891 List<String> listStructDecl = structDecl.getStructTypes();
4892 if (listStructDecl.contains(type))
4899 // Return number of members (-1 if not found)
4900 private int getNumOfMembers(String type) {
4902 // Just iterate over the set of interfaces
4903 for (String intface : mapIntfacePTH.keySet()) {
4904 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
4905 StructDecl structDecl = (StructDecl) decHandler.getStructDecl(intface);
4906 List<String> listStructDecl = structDecl.getStructTypes();
4907 if (listStructDecl.contains(type))
4908 return structDecl.getNumOfMembers(type);
4914 // Generate a set of classes for include statements
4915 private Set<String> getIncludeClasses(Collection<String> methods, InterfaceDecl intDecl, String intface, boolean needExchange) {
4917 Set<String> includeClasses = new HashSet<String>();
4918 for (String method : methods) {
4920 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4921 List<String> methParams = intDecl.getMethodParams(method);
4922 for (int i = 0; i < methPrmTypes.size(); i++) {
4924 String simpleType = getSimpleType(methPrmTypes.get(i));
4925 String param = methParams.get(i);
4926 if (getParamCategory(simpleType) == ParamCategory.NONPRIMITIVES) {
4927 includeClasses.add("<" + getNonPrimitiveCplusClass(simpleType) + ">");
4928 } else if (getParamCategory(simpleType) == ParamCategory.USERDEFINED) {
4929 // For original interface, we need it exchanged... not for stub interfaces
4931 includeClasses.add("\"" + exchangeParamType(simpleType) + ".hpp\"");
4932 includeClasses.add("\"" + exchangeParamType(simpleType) + "_CallbackStub.hpp\"");
4934 includeClasses.add("\"" + simpleType + ".hpp\"");
4935 includeClasses.add("\"" + simpleType + "_CallbackSkeleton.hpp\"");
4937 } else if (getParamCategory(getSimpleArrayType(simpleType)) == ParamCategory.ENUM) {
4938 includeClasses.add("\"" + simpleType + ".hpp\"");
4939 } else if (getParamCategory(getSimpleArrayType(simpleType)) == ParamCategory.STRUCT) {
4940 includeClasses.add("\"" + simpleType + ".hpp\"");
4941 } else if (param.contains("[]")) {
4942 // Check if this is array for C++; translate into vector
4943 includeClasses.add("<vector>");
4947 return includeClasses;
4951 // Generate a set of callback classes
4952 private Set<String> getCallbackClasses(Collection<String> methods, InterfaceDecl intDecl) {
4954 Set<String> callbackClasses = new HashSet<String>();
4955 for (String method : methods) {
4957 List<String> methPrmTypes = intDecl.getMethodParamTypes(method);
4958 List<String> methParams = intDecl.getMethodParams(method);
4959 for (int i = 0; i < methPrmTypes.size(); i++) {
4961 String type = methPrmTypes.get(i);
4962 if (getParamCategory(type) == ParamCategory.USERDEFINED) {
4963 callbackClasses.add(type);
4964 } else if (getParamCategory(type) == ParamCategory.NONPRIMITIVES) {
4965 // Can be a List<...> of callback objects ...
4966 String genericType = getTypeOfGeneric(type)[0];
4967 if (getParamCategory(type) == ParamCategory.USERDEFINED) {
4968 callbackClasses.add(type);
4973 return callbackClasses;
4977 // Print import statements into file
4978 private void printImportStatements(Collection<String> importClasses) {
4980 for(String cls : importClasses) {
4981 println("import " + cls + ";");
4986 // Print include statements into file
4987 private void printIncludeStatements(Collection<String> includeClasses) {
4989 for(String cls : includeClasses) {
4990 println("#include " + cls);
4995 // Get the C++ version of a non-primitive type
4996 // e.g. set for Set and map for Map
4997 // Input nonPrimitiveType has to be generics in format
4998 private String[] getTypeOfGeneric(String nonPrimitiveType) {
5000 // Handle <, >, and , for 2-type generic/template
5001 String[] substr = nonPrimitiveType.split("<")[1].split(">")[0].split(",");
5006 // Gets generic type inside "<" and ">"
5007 private String getGenericType(String type) {
5009 // Handle <, >, and , for 2-type generic/template
5010 if (getParamCategory(type) == ParamCategory.NONPRIMITIVES) {
5011 String[] substr = type.split("<")[1].split(">")[0].split(",");
5018 // This helper function strips off array declaration, e.g. int[] becomes int
5019 private String getSimpleArrayType(String type) {
5021 // Handle [ for array declaration
5022 String substr = type;
5023 if (type.contains("[]")) {
5024 substr = type.split("\\[\\]")[0];
5030 // This helper function strips off array declaration, e.g. D[] becomes D
5031 private String getSimpleIdentifier(String ident) {
5033 // Handle [ for array declaration
5034 String substr = ident;
5035 if (ident.contains("[]")) {
5036 substr = ident.split("\\[\\]")[0];
5042 // Checks and gets type in C++
5043 private String checkAndGetCplusType(String paramType) {
5045 if (getParamCategory(paramType) == ParamCategory.PRIMITIVES) {
5046 return convertType(paramType);
5047 } else if (getParamCategory(paramType) == ParamCategory.NONPRIMITIVES) {
5049 // Check for generic/template format
5050 if (paramType.contains("<") && paramType.contains(">")) {
5052 String genericClass = getSimpleType(paramType);
5053 String[] genericType = getTypeOfGeneric(paramType);
5054 String cplusTemplate = null;
5055 if (genericType.length == 1) // Generic/template with one type
5056 cplusTemplate = getNonPrimitiveCplusClass(genericClass) +
5057 "<" + convertType(genericType[0]) + ">";
5058 else // Generic/template with two types
5059 cplusTemplate = getNonPrimitiveCplusClass(genericClass) +
5060 "<" + convertType(genericType[0]) + "," + convertType(genericType[1]) + ">";
5061 return cplusTemplate;
5063 return getNonPrimitiveCplusClass(paramType);
5064 } else if(paramType.contains("[]")) { // Array type (used for return type only)
5065 String cArray = "vector<" + convertType(getSimpleArrayType(paramType)) + ">";
5067 } else if(getParamCategory(paramType) == ParamCategory.USERDEFINED) {
5068 return paramType + "*";
5070 // Just return it as is if it's not non-primitives
5072 //return checkAndGetParamClass(paramType, true);
5076 // Detect array declaration, e.g. int A[],
5077 // then generate "int A[]" in C++ as "vector<int> A"
5078 private String checkAndGetCplusArray(String paramType, String param) {
5080 String paramComplete = null;
5081 // Check for array declaration
5082 if (param.contains("[]")) {
5083 paramComplete = "vector<" + paramType + "> " + param.replace("[]","");
5085 // Just return it as is if it's not an array
5086 paramComplete = paramType + " " + param;
5088 return paramComplete;
5092 // Detect array declaration, e.g. int A[],
5093 // then generate "int A[]" in C++ as "vector<int> A"
5094 // This method just returns the type
5095 private String checkAndGetCplusArrayType(String paramType) {
5097 String paramTypeRet = null;
5098 // Check for array declaration
5099 if (paramType.contains("[]")) {
5100 String type = paramType.split("\\[\\]")[0];
5101 paramTypeRet = checkAndGetCplusType(type) + "[]";
5102 } else if (paramType.contains("vector")) {
5103 // Just return it as is if it's not an array
5104 String type = paramType.split("<")[1].split(">")[0];
5105 paramTypeRet = checkAndGetCplusType(type) + "[]";
5107 paramTypeRet = paramType;
5109 return paramTypeRet;
5113 // Detect array declaration, e.g. int A[],
5114 // then generate "int A[]" in C++ as "vector<int> A"
5115 // This method just returns the type
5116 private String checkAndGetCplusArrayType(String paramType, String param) {
5118 String paramTypeRet = null;
5119 // Check for array declaration
5120 if (param.contains("[]")) {
5121 paramTypeRet = checkAndGetCplusType(paramType) + "[]";
5122 } else if (paramType.contains("vector")) {
5123 // Just return it as is if it's not an array
5124 String type = paramType.split("<")[1].split(">")[0];
5125 paramTypeRet = checkAndGetCplusType(type) + "[]";
5127 paramTypeRet = paramType;
5129 return paramTypeRet;
5133 // Return the class type for class resolution (for return value)
5134 // - Check and return C++ array class, e.g. int A[] into int*
5135 // - Check and return C++ vector class, e.g. List<Integer> A into vector<int>
5136 private String checkAndGetCplusRetClsType(String paramType) {
5138 String paramTypeRet = null;
5139 // Check for array declaration
5140 if (paramType.contains("[]")) {
5141 String type = paramType.split("\\[\\]")[0];
5142 paramTypeRet = getSimpleArrayType(type) + "*";
5143 } else if (paramType.contains("<") && paramType.contains(">")) {
5144 // Just return it as is if it's not an array
5145 String type = paramType.split("<")[1].split(">")[0];
5146 paramTypeRet = "vector<" + getGenericType(type) + ">";
5148 paramTypeRet = paramType;
5150 return paramTypeRet;
5154 // Return the class type for class resolution (for method arguments)
5155 // - Check and return C++ array class, e.g. int A[] into int*
5156 // - Check and return C++ vector class, e.g. List<Integer> A into vector<int>
5157 private String checkAndGetCplusArgClsType(String paramType, String param) {
5159 String paramTypeRet = getEnumCplusClsType(paramType);
5160 if (!paramTypeRet.equals(paramType))
5161 // Just return if it is an enum type
5162 // Type will still be the same if it's not an enum type
5163 return paramTypeRet;
5165 // Check for array declaration
5166 if (param.contains("[]")) {
5167 paramTypeRet = getSimpleArrayType(paramType) + "*";
5168 } else if (paramType.contains("<") && paramType.contains(">")) {
5169 // Just return it as is if it's not an array
5170 String type = paramType.split("<")[1].split(">")[0];
5171 paramTypeRet = "vector<" + getGenericType(type) + ">";
5173 paramTypeRet = paramType;
5175 return paramTypeRet;
5179 // Detect array declaration, e.g. int A[],
5180 // then generate type "int[]"
5181 private String checkAndGetArray(String paramType, String param) {
5183 String paramTypeRet = null;
5184 // Check for array declaration
5185 if (param.contains("[]")) {
5186 paramTypeRet = paramType + "[]";
5188 // Just return it as is if it's not an array
5189 paramTypeRet = paramType;
5191 return paramTypeRet;
5195 // Is array or list?
5196 private boolean isArrayOrList(String paramType, String param) {
5198 // Check for array declaration
5201 else if (isList(paramType))
5209 // For return type we use retType as input parameter
5210 private boolean isArray(String param) {
5212 // Check for array declaration
5213 if (param.contains("[]"))
5221 private boolean isList(String paramType) {
5223 // Check for array declaration
5224 if (paramType.contains("List"))
5231 // Get the right type for a callback object
5232 private String checkAndGetParamClass(String paramType) {
5234 // Check if this is generics
5235 if(getParamCategory(paramType) == ParamCategory.USERDEFINED) {
5236 return exchangeParamType(paramType);
5242 // Returns the other interface for type-checking purposes for USERDEFINED
5243 // classes based on the information provided in multiple policy files
5244 // e.g. return CameraWithXXX instead of Camera
5245 private String exchangeParamType(String intface) {
5247 // Param type that's passed is the interface name we need to look for
5248 // in the map of interfaces, based on available policy files.
5249 DeclarationHandler decHandler = mapIntDeclHand.get(intface);
5250 if (decHandler != null) {
5251 // We've found the required interface policy files
5252 RequiresDecl reqDecl = (RequiresDecl) decHandler.getRequiresDecl(intface);
5253 Set<String> setExchInt = reqDecl.getInterfaces();
5254 if (setExchInt.size() == 1) {
5255 Iterator iter = setExchInt.iterator();
5256 return (String) iter.next();
5258 throw new Error("IoTCompiler: Ambiguous stub interfaces: " + setExchInt.toString() +
5259 ". Only one new interface can be declared if the object " + intface +
5260 " needs to be passed in as an input parameter!\n");
5263 // NULL value - this means policy files missing
5264 throw new Error("IoTCompiler: Parameter type lookup failed for " + intface +
5265 "... Please provide the necessary policy files for user-defined types." +
5266 " If this is an array please type the brackets after the variable name," +
5267 " e.g. \"String str[]\", not \"String[] str\"." +
5268 " If this is a Collections (Java) / STL (C++) type, this compiler only" +
5269 " supports List/ArrayList (Java) or list (C++).\n");
5274 public static void main(String[] args) throws Exception {
5276 // If there is no argument or just "--help" or "-h", then invoke printUsage()
5277 if ((args[0].equals("-help") ||
5278 args[0].equals("--help")||
5279 args[0].equals("-h")) ||
5280 (args.length == 0)) {
5282 IoTCompiler.printUsage();
5284 } else if (args.length > 1) {
5286 IoTCompiler comp = new IoTCompiler();
5289 // Parse main policy file
5290 ParseNode pnPol = IoTCompiler.parseFile(args[i]);
5291 // Parse "requires" policy file
5292 ParseNode pnReq = IoTCompiler.parseFile(args[i+1]);
5293 // Get interface name
5294 String intface = ParseTreeHandler.getOrigIntface(pnPol);
5295 comp.setDataStructures(intface, pnPol, pnReq);
5296 comp.getMethodsForIntface(intface);
5298 // 1) Check if this is the last option before "-java" or "-cplus"
5299 // 2) Check if this is really the last option (no "-java" or "-cplus")
5300 } while(!args[i].equals("-java") &&
5301 !args[i].equals("-cplus") &&
5304 // Generate everything if we don't see "-java" or "-cplus"
5305 if (i == args.length) {
5306 comp.generateEnumJava();
5307 comp.generateStructJava();
5308 comp.generateJavaLocalInterfaces();
5309 comp.generateJavaInterfaces();
5310 comp.generateJavaStubClasses();
5311 comp.generateJavaCallbackStubClasses();
5312 comp.generateJavaSkeletonClass();
5313 comp.generateJavaCallbackSkeletonClass();
5314 comp.generateEnumCplus();
5315 comp.generateStructCplus();
5316 comp.generateCplusLocalInterfaces();
5317 comp.generateCPlusInterfaces();
5318 comp.generateCPlusStubClasses();
5319 comp.generateCPlusCallbackStubClasses();
5320 comp.generateCplusSkeletonClass();
5321 comp.generateCplusCallbackSkeletonClass();
5323 // Check other options
5324 while(i < args.length) {
5326 if (!args[i].equals("-java") &&
5327 !args[i].equals("-cplus")) {
5328 throw new Error("IoTCompiler: ERROR - unrecognized command line option: " + args[i] + "\n");
5330 if (i + 1 < args.length) {
5331 comp.setDirectory(args[i+1]);
5333 throw new Error("IoTCompiler: ERROR - please provide <directory> after option: " + args[i] + "\n");
5335 if (args[i].equals("-java")) {
5336 comp.generateEnumJava();
5337 comp.generateStructJava();
5338 comp.generateJavaLocalInterfaces();
5339 comp.generateJavaInterfaces();
5340 comp.generateJavaStubClasses();
5341 comp.generateJavaCallbackStubClasses();
5342 comp.generateJavaSkeletonClass();
5343 comp.generateJavaCallbackSkeletonClass();
5345 comp.generateEnumCplus();
5346 comp.generateStructCplus();
5347 comp.generateCplusLocalInterfaces();
5348 comp.generateCPlusInterfaces();
5349 comp.generateCPlusStubClasses();
5350 comp.generateCPlusCallbackStubClasses();
5351 comp.generateCplusSkeletonClass();
5352 comp.generateCplusCallbackSkeletonClass();
5359 // Need to at least have exactly 2 parameters, i.e. main policy file and requires file
5360 IoTCompiler.printUsage();
5361 throw new Error("IoTCompiler: At least two arguments (main and requires policy files) have to be provided!\n");